使用 MySQLi 在 PHP 中没有选择数据库错误 [英] No Database selected error in PHP with MySQLi

查看:29
本文介绍了使用 MySQLi 在 PHP 中没有选择数据库错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须从 MySQL 数据库中选择数据.我一直在寻找答案,但仍然没有找到.我正在学习 W3School

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

我的 MySQL 没有任何用户名或密码,所以我的代码如下所示:

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>";
    }
}
?>

首先我得到这个错误

mysqli_num_rows() 期望参数 1 是 mysqli_result,布尔值在

mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in

在堆栈中进一步追踪它时,我得到了这个:

On further tracing it back in the stack, I got this:

未选择数据库

我不知道我做错了什么.所以你能不能给我解释一下,给我解决办法.提前致谢

I don't know what I'm doing wrong. So can you explain it to me and give me the solution. Thanks in advance

推荐答案

像这样设置 mysql 用户名和密码.

Set mysql username and passwork something like this.

$username = "root";
$password = "";

并像这样设置连接.

$conn = mysqli_connect($servername, $username, $password, $dbname);

这篇关于使用 MySQLi 在 PHP 中没有选择数据库错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆