I’m working on a PHP script and encountering an issue that I can’t seem to resolve. The script is supposed to fetch data from a MySQL database and display it on a webpage. However, I’m getting an “Undefined variable” error. Here is the part of my code that’s causing the issue:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDatabase";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name FROM myTable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
The error I’m getting is:
Notice: Undefined variable: row in /path/to/my/script.php on line 16
I’ve double-checked my database connection and query, and they seem to be working fine. What could be causing this issue, and how can I fix it?
The "Undefined variable" error in PHP typically occurs when you're trying to use a variable that hasn't been initialized or defined within the current scope. In your case, the error is happening because the $row variable is not being defined in the scope where you're trying to access it. <?php error_reporting(E_ALL); ini_set('display_errors', 1); $servername = "localhost"; $username = "root"; $password = ""; $dbname = "myDatabase"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT id, name FROM myTable"; $result = $conn->query($sql); if ($result === false) { die("Query failed: " . $conn->error); } if ($result->num_rows > 0) { $row = null; // Initialize the variable while($row = $result->fetch_assoc()) { echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>"; } } else { echo "0 results"; } $conn->cloRead more
The “Undefined variable” error in PHP typically occurs when you’re trying to use a variable that hasn’t been initialized or defined within the current scope. In your case, the error is happening because the
$row
variable is not being defined in the scope where you’re trying to access it.I hope this helps! If you have any further questions, feel free to ask.
See less