1

I want to check if id is exists or not. if id is not exists then i need to insert a row in sql database. here is my code. but problem is it always insert a row.

mysql_select_db($database_include, $include);
$query_user = "SELECT * FROM `user` WHERE `userid` = '$id'";
$user = mysql_query($query_user, $include) or die(mysql_error());
$row_user = mysql_fetch_assoc($user);
$totalRows_user = mysql_num_rows($user);



if($totalRows_user == 0){
mysql_select_db($database_include, $include);
$query_insert = "INSERT INTO user (userid, point, followors)VALUES ($id,'10','0');";
$user = mysql_query($query_insert, $include) or die(mysql_error());
}

what to do?

Samuel Scott
  • 199
  • 1
  • 1
  • 8
  • [Little Bobby](http://bobby-tables.com/) says [your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard Jun 06 '16 at 18:07
  • Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Jun 06 '16 at 18:07

2 Answers2

1

You could try the ON DUPLICATE KEY UPDATE feature of mysql, with that you can make the insert/update in one sentence...

http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html

0

if($totalRows_user == 0) can be implicitly cast as false, indicating an error with your last query.

from docs on mysql_num_rows

The number of rows in a result set on success or FALSE on failure.

use the identical operator ===

if($totalRows_user === 0)
Jeff Puckett
  • 33,491
  • 16
  • 111
  • 160