且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

[PHP + MySQL]数据库SELECT查询未返回结果

更新时间:2023-01-31 09:18:47

问题在这里:

您在这段代码中两次使用了mysqli_query():

You're using mysqli_query() twice in this piece of code:

$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));

if (!$result = mysqli_query($conn, $sql)) {
printf("Errormessage: %s\n", mysqli_error($conn));
}

您需要删除一个并执行以下操作:

You need to remove one and do:

if (!$result) {
printf("Errormessage: %s\n", mysqli_error($conn));
}

同时添加逃生路线else{...} affected_rows() 也.

while adding an escape route else{...} and affected_rows() also.

  • 这是查询失败的原因.

这是您使用$conn两次,而不是在查询中使用变量引用:

This, you're using $conn twice and not using a variable reference for your query:

mysqli_select_db($conn, $dbName);
$sql = "SELECT * FROM tbl_users WHERE id = 1";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));

将其更改为并使用 mysqli_connect() 的4参数方案>,因为此时已经创建了数据库:(假设ID上面已经创建了ID"1").

Change it to and using the 4 parameters scheme of mysqli_connect(), since the DB has already been created at this point: (assuming the id of "1" has already been created above that).

$dbName = "myDB";
$conn = mysqli_connect($serverName, $username, $password, $dbName);

$sql = "SELECT * FROM tbl_users WHERE id = 1";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));

if (!$result) {
printf("Errormessage: %s\n", mysqli_error($conn));
}
else{ echo "Success"; }

或删除or die(mysqli_error($conn))并让错误继续传递(如果有的话).

or by removing or die(mysqli_error($conn)) and getting the error passed on after, if any.

$dbName = "myDB";
$conn = mysqli_connect($serverName, $username, $password, $dbName);

$sql = "SELECT * FROM tbl_users WHERE id = 1";
$result = mysqli_query($conn, $sql);

if (!$result) {
printf("Errormessage: %s\n", mysqli_error($conn));
}
else{ echo "Success"; }

(其他修改)

您也可以尝试此方法,并将其与我上面已经说过的结合使用:

You could also try this method and used in conjunction with what I already stated above:

$numrows = mysqli_num_rows($result);

if($numrows > 0){
// do something
}


错误报告 添加到文件顶部,这将有助于发现错误.


Add error reporting to the top of your file(s) which will help find errors.

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

// rest of your code

侧注:错误报告仅应在登台进行,而绝不能在生产中进行.

Sidenote: Error reporting should only be done in staging, and never production.