How can the PHP code be modified to correctly display the bank names instead of showing "Resource id #5"?
The issue is caused by attempting to directly output the result of a MySQL query, which returns a resource identifier instead of the actual data. To correctly display the bank names, we need to fetch the data from the query result and then loop through the rows to display each bank name.
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query to fetch bank names
$sql = "SELECT bank_name FROM banks";
$result = $conn->query($sql);
// Check if there are any results
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "Bank Name: " . $row["bank_name"] . "<br>";
}
} else {
echo "0 results";
}
// Close connection
$conn->close();
Related Questions
- What are the best practices for sanitizing user input in PHP before storing it in a MySQL database?
- What are the common methods used for user authentication in PHP applications, and how can developers ensure the security of login systems?
- What are the potential pitfalls of using if() statements in PHP for user authentication, and how can they be avoided?