No Database selected error in PHP with MySQLi [duplicate]

為{幸葍}努か 提交于 2021-02-17 07:18:29

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!