Hi I can connect to my database but it's says that I have 0 rows! I've tried different ways to connect to my database, but all of them always return 0 rows so it will not show any data from the database.
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM keys";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Key: " . $row["key"]. " " . $row["used"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
SELECT * FROM keys
^
KEYS
is a reserved term , hence your query fails to execute and no data is returned, at the very least escape it.
Best option would be to change your field name to something that's not reserved.
Something funny to note
You're saying if there are some rows in my result show me those but if there are no rows in my result then show me the number of rows. In short, displaying the number of rows when your query fails is utterly pointless! That will be a good place to display an error message returned by the database driver
keys is reserved keyword
in mysql it must be in backtick as
$sql = "SELECT * FROM `keys`";
Your query fails and your got 0 result always
To check error in query use
if (!$conn->query("Your_QUERY")) {
printf("Errormessage: %s\n", $conn->error);
}
I think you have to use this code for get result :-
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM `keys`";
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Key: " . $row["key"]. " " . $row["used"]. "<br>";
}
} else {
echo "0 results";
echo "Rows:". mysqli_num_rows($result);
}
$conn->close();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.