Mysqli num row返回不起作用

时间:2014-01-31 04:59:38

标签: php mysql mysqli

我想知道为什么它不适用于mysqli eventhou mysql_num_row正在工作。

if (mysql_num_rows($rows) > 0) {
    echo "<p>That name has been taken </p>";
}

那是mysql。但是,我尝试将其转换为mysqli。

 if (mysqli_num_rows($rows) > 0) {
        echo "<p>That name has been taken </p>";
    }

它应该显示在屏幕上,但事实并非如此。并且没有显示任何错误消息。或者我错过了什么?有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您可以尝试以下代码:

$connect = new mysqli("localhost", "user", "password", "database");
$query = "SELECT name FROM table";

$statement= mysqli_prepare($connect, $query)
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);

if (mysqli_stmt_num_rows($statement) > 0) {
    echo "<p>That name has been taken </p>";
}   

mysqli_stmt_close($statement);
mysqli_close($connect);

答案 1 :(得分:0)

首先,快速了解mysql_*mysqli_*函数之间的一些差异。

mysql_*中,您的数据库连接将有3个参数,然后为您的数据库选择提供单独的行。

例如:

$db = mysql_connect("host","username", "password");
$db_selected = mysql_select_db('db_name', $db);
if (!$db_selected) {
    die ('Can\'t use this : ' . mysql_error());
}

您的查询将首先出现,然后是您的数据库连接。

例如:

mysql_query($query,$db);

但在mysqli_*中,事情发生了变化,包括参数位置。你现在放了所有4个参数,例如(如果你还没有这样做):

$db = new mysqli("host","username", "password", "db_name");

if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

然后首先是数据库连接,然后是查询,而不是相反:

mysqli_query($db,$query);

示例查询:

$email = mysqli_real_escape_string($db,$_POST['email']);
$query = mysqli_query($db, "SELECT * FROM table_name WHERE email='".$email."'");

if(mysqli_num_rows($query) > 0){

    echo "email already exists";
}else{
    $sql="INSERT INTO table_name (email) VALUES ('$email')";
    if (!mysqli_query($db,$sql))
    {
        die('Error: ' . mysqli_error($db));
    }
}