I'm trying to execute a MySQL query in PHP but I am having some problems. It appears that when running this query in PHP it always returns 0 rows, but running this in my console works as expected.
<?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);
The output:
SELECT COUNT(*) FROM accounts WHERE name = 'testUser' AND email = 'abc123@gmail.com'
Result set has 0 rows.
Account does not exist! Creating...
Created account!
Then in the table we see the expected:
mysql> select * from accounts;
+----+----------+------------------+----------+-----------+
| id | name | email | password | ip |
+----+----------+------------------+----------+-----------+
| 10 | testUser | abc123@gmail.com | abc123 | localhost |
+----+----------+------------------+----------+-----------+
1 row in set (0.00 sec)
But when the query is ran again it has the same exact output and another row is created.
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)
Any ideas on why it cannot detect that the data exists in a row already?