PHP DB连接问题

时间:2011-03-25 02:26:31

标签: php

我收到错误:

  

警告:mysqli_num_rows()要求参数1为mysqli_result,第23行/home/mjcrawle/public_html/home/index.php中给出布尔值

第23行原来是$num_results = mysqli_num_rows($result);,但我认为错误进一步发展但我找不到它。

我用来连接数据库的实际代码是(我知道如果数据库无法连接,则存在冗余):

任何帮助都会很精彩,错误的原因会很棒!

/*Connect To DB*/
$conn = mysqli_connect($host, $user, $pwd)
        or die("Could not connect: " . mysql_error()); //connect to server
    mysqli_select_db($conn, $database)
        or die("Error: Could not connect to the database: " . mysql_error());

    /*Check for Connection*/
    if(mysqli_connect_errno()){
        /*Display Error message if fails*/
        echo 'Error, could not connect to the database please try again later.';
    exit();
    }

/* Query for states */
$query = "SELECT StateAbbreviation, StateName, FROM USState ORDER BY StateName";
$result = mysqli_query($conn, $query);
$num_results = mysqli_num_rows($result);
?>

3 个答案:

答案 0 :(得分:3)

FROM中的query = "SELECT StateAbbreviation, StateName, FROM USState ORDER BY StateName";之前有一个额外的逗号,您可能会收到错误,但在执行查询时没有结果。

答案 1 :(得分:0)

如果查询失败,mysqli_query将返回布尔值false

$result = mysqli_query($conn, $query);之后,您应该在继续之前测试返回值:

if ( ! $result){
   $error = mysqli_error($conn);
   //do something with the error message
}

请参阅EmCo的答案,了解您的查询失败的原因。

答案 2 :(得分:0)

<?php $con=mysqli_connect('localhost','root','','dbname') or die ("Connection Failed"); ?>

这是DB Connection的简单方法