PHP中的MySQL:始终返回0行

时间:2016-06-14 13:41:10

标签: php mysql

我试图在PHP中执行MySQL查询,但我遇到了一些问题。看来,当在PHP中运行此查询时,它总是返回0行,但在我的控制台中运行它会按预期工作。

<?php
include '../mysql.php';
$name = $_POST["name"];
$email = $_POST["email"];
$sql = "SELECT COUNT(*) FROM accounts WHERE name = '" . $name . "' AND email = '" . $email . "'";
echo $sql . "</br>";
$res = mysqli_query($connection, $sql);
if(!$res) {
    die("Query Failed!");
}
$row_cnt = $result->num_rows;
printf("Result set has %d rows.</br>", $row_cnt);
if($row_cnt > 0) {
    echo "Account exists!";
} else {
    echo "Account does not exist! Creating...</br>";
    if(mysqli_query($connection, "INSERT INTO accounts (`name`, `email`, `password`, `ip`) VALUES ('" . $name . "', '" . $email . "', 'abc123', 'localhost')")) {
        echo "Created account!";
    } else {
        echo "Failed to create account";
    }
}
mysqli_free_result($res);
mysql_close($connection);

输出:

SELECT COUNT(*) FROM accounts WHERE name = 'testUser' AND email = 'abc123@gmail.com'
Result set has 0 rows.
Account does not exist! Creating...
Created account!

然后在表格中我们看到了预期:

mysql> select * from accounts;
+----+----------+------------------+----------+-----------+
| id | name     | email            | password | ip        |
+----+----------+------------------+----------+-----------+
| 10 | testUser | abc123@gmail.com | abc123   | localhost |
+----+----------+------------------+----------+-----------+
1 row in set (0.00 sec)

但是当再次运行查询时,它具有相同的确切输出并且创建了另一行。

mysql> select * from accounts;
+----+----------+------------------+----------+-----------+
| id | name     | email            | password | ip        |
+----+----------+------------------+----------+-----------+
| 10 | testUser | abc123@gmail.com | abc123   | localhost |
| 11 | testUser | abc123@gmail.com | abc123   | localhost |
+----+----------+------------------+----------+-----------+
2 rows in set (0.00 sec)

关于它为什么无法检测到数据已经连续存在的任何想法?

1 个答案:

答案 0 :(得分:4)

你有两个不同的变量,$ result和$ res。 改变这个:

$row_cnt = $result->num_rows;

要:

$row_cnt = $res->num_rows;

<强>更新

同样改变这个:

$sql = "SELECT COUNT(*) FROM accounts WHERE name = '" . $name . "' AND email = '" . $email . "'";

要:

$sql = "SELECT * FROM accounts WHERE name = '" . $name . "' AND email = '" . $email . "'";

否则您的$ res将始终等于1,因此应用程序将无法按预期运行。   - 德文郡

更新#2:

关闭连接
mysqli_close($connection); 

相反

mysql_close($connection);

不要把这两个混在一起! - 萨蒂

更新#3

阅读有关清理PHP变量以保护应用程序的信息。可以找到一个好的帖子here,并在谷歌上提供更多的帖子。