Kartik Prabhu
Kartik Prabhu

Reputation: 411

SQL INSERT statement being performed when it shoudn't

So my android application sends JSON data to the server, and the PHP script takes it, first checks if there are existing records of that user, and if not, adds them to the database. For some reason here, it's not working. The INSERT statement is always being performed. When I'm checking the count on a different PHP page, I'm getting the right count (using the same exact query).

But something is going on here. A new row is always being added, and I don't know why. Any help is appreciated.

<?php

require_once('connection.php');

$data = json_decode($_SERVER['HTTP_JSON'], true);

$name = $data['name'];
$profilePicture = $data['profilePicture'];
$googleId = $data['googleId'];

//First see if the user is already in the database
//$find_existing_query = "SELECT * FROM users WHERE googleId = '".$googleId."'";
$find_existing_query = "SELECT COUNT(*) FROM users WHERE name = $name";
$find_query_result = mysql_query($find_existing_query);
$find_query_rows = mysql_fetch_assoc($find_query_result);
$count = $find_query_rows['COUNT(*)'];

//Add user if there are no rows returned
if($count == 0)
{
    $add_user_query = "INSERT INTO users (name, profilePicture, googleId) VALUES ('".$name."', '".$profilePicture."', '".$googleId."')";
    mysql_query($add_user_query);
}

$qry = "SELECT * FROM users";

$result = mysql_query($qry);
$rows = array();
while($r = mysql_fetch_assoc($result)){
    $rows[] = $r;
}
echo json_encode($rows);

mysql_close();

?>

Upvotes: 0

Views: 38

Answers (2)

Rigel1121
Rigel1121

Reputation: 2034

You've forgot to append and put single quote in your query. I should be like this:

$find_existing_query = "SELECT COUNT(*) FROM users WHERE name = '".$name."'";

Upvotes: 1

John Conde
John Conde

Reputation: 219864

Your query fails due to a syntax error which makes mysql_fetch_assoc() return false which when type juggled equals zero.

You forgot to put quotes around the string value in your query.

$find_existing_query = "SELECT COUNT(*) FROM users WHERE name = $name";

should be

$find_existing_query = "SELECT COUNT(*) FROM users WHERE name = '$name'";

Upvotes: 3

Related Questions