问题
I have to select data from MySQL Database. I have been looking for the answer, but still haven't found any. I am learning from W3School
My MySQL doesn't have any username or password, so my code looks like this:
<?php
$servername = "localhost";
$dbName = "db_Test";
//Create Connection
$conn = mysqli_connect($servername, $dbName);
//Check Connection
if(!$conn){
die("Connection Failed. ". mysqli_connect_error());
}
$sql = "SELECT ID, Name, Category, Description, Price FROM items";
$result = mysqli_query($conn, $sql);
if(!$result){
die(mysqli_error($conn));
}
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
echo "ID: ".$row['ID']." Name: ".$row['Name']." Category: ".$row['Category']."<br>";
}
}
?>
First I got this error
mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in
On further tracing it back in the stack, I got this:
No database selected
I don't know what I'm doing wrong. So can you explain it to me and give me the solution. Thanks in advance
回答1:
Set mysql username and passwork something like this.
$username = "root";
$password = "";
And set connection like this.
$conn = mysqli_connect($servername, $username, $password, $dbname);
来源:https://stackoverflow.com/questions/39653957/no-database-selected-error-in-php-with-mysqli