Reputation: 13
I have a PHP script which connects to a database setup up with MAMP.
However it doesn't seem to be able to connect to the database. Every time I tried, it has failed with the message:
This page isn’t working localhost is currently unable to handle this request. HTTP ERROR 500
<?php
$host = "localhost:8889";
$dbusername = "root";
$dbpassword = "root";
$dbname = "HMSDb";
//Create connection
$conn = new mysqli_connect($host, $dbusername, $dbpassword, $dbname);
$sql = "SELECT * FROM login;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($rows = mysqli_fetch_assoc($result)) {
echo $row['username'] . "<br>";
} else {
echo "Fail";
}
?>
Upvotes: 1
Views: 45839
Reputation: 35
Your code will work. If it rewrite like
$host = "localhost";
$dbusername = "root"; // username
$dbpassword = "password"; // your password
$dbname = "test"; // dbname
//Create connection
$conn = new mysqli($host, $dbusername, $dbpassword, $dbname);
$sql = "SELECT * FROM fruit";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
echo "<ul>";
if ($resultCheck > 0) {
while ($rows = mysqli_fetch_assoc($result)) {
//echo $row['username'] . "<br>";
echo "<li> A ".$rows["name"]." is ".$rows["color"]. "</li>";
}
} else {
echo "Fail";
}
echo "</ul>";
I test the code with my table . Please make respective changes in your code..
All the best
Anes
Upvotes: 0
Reputation: 6384
HTTP 500
code stands for a server error. As said Tim, check your server logs.
By the way, you should fix your if
statement by adding the missing curly braket {
:
if ($resultCheck > 0) {
while ($rows = mysqli_fetch_assoc($result)) {
echo $row['username'] . "<br>";
}
} // <- missing curly bracket
else {
echo "Fail";
}
Upvotes: 4
Reputation: 1015
The best place to start would be to check your server logs.
Their location depends on what your system is and how you installed your web server. Google should help to find them, error_log
is what you seek.
But this particular problem may be caused by your $host
including the port. If you need to specify a non-default port, add it as per the documentation as an additional argument to mysqli_connect()
after $dbname
.
Edit:
After a live test, my error_log
indicates the cause is the use of the new
keyword. Remove it from:
$conn = new mysqli_connect($host, $dbusername, $dbpassword, $dbname);
or use mysqli();
instead. mysqli_connect()
is a function, not a class, and as such it cannot be instantiated with the new
keyword.
The error: Uncaught Error: Class 'mysqli_connect' not found in /index.php
Of course, fix your missing bracket too as Amessihel mentioned.
Upvotes: 2