Reputation: 1412
I am currently trying to connect to a database and display the first names of all the students in the table "STUDENTS". I seem to be connecting fine, as my ping() seems to go through fine. I am not receiving an error message of any sort, but my query/displaying the results seems to not be working. Can anyone help me to solve this issue?
<?php
$user = 'root';
$password = 'root';
$db = 'gradebook';
$host = 'localhost';
$port = 8889;
$link = mysqli_init();
$connection = mysqli_real_connect($link, $host, $user, $password, $db, $port)
or die("Cannot connect to database server.");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* check if server is alive */
if (mysqli_ping($link)) {
printf ("Our connection is ok!\n </br>");
} else {
printf ("Error: %s\n", mysqli_error($link));
}
$query = "SELECT * FROM STUDENTS";
$statement = $connection->prepare($query);
$statement->execute();
$statement->bind_result($First_name);
while ($statement->fetch()) {
print $First_name . '</br>';
}
mysqli_close($link);
?>
Upvotes: 0
Views: 38
Reputation: 54831
Please, start with turning on error reporting.
Then - read mysqli-manuals carefully.
$link = mysqli_init();
returns object.
mysqli_real_connect
returns bool.
And you're trying to execute prepare
method on bool variable:
$statement = $connection->prepare($query);
Surely it doesn't work. And if you had error reporting on
- you would see a relevant error message. So, assuming everything else is fine:
$statement = $link->prepare($query); // NOT $connection
$statement->execute();
$statement->bind_result($First_name);
while ($statement->fetch()) {
print $First_name . '</br>';
}
Upvotes: 2