0

So I have this code in a php file:

$query="INSERT INTO tec (name) VALUES ('$name')";
$done=mysql_query($query);
if($done == 'null') {
    $output = json_encode(array('type'=>'error', 'message' => $mess['error'].$done.'</b></div>'));
} else {
    $output = json_encode(array('type'=>'success', 'message' => $mess['success']));
}

It inserts a name into a table named "tec". If $done == 'null' then I print an error message. The problem is that when I run the code, it inserts the data correctly, but I get the error message. I tried to read $done and its equal to 1. Should I do something like:

if($done == 1){
    //OK
}else{
    //NOT OK
}

Or is there any way to fix this?

JCAguilera
  • 944
  • 1
  • 13
  • 32
  • 2
    [Please, don't use `mysql_*` functions in new code](http://stackoverflow.com/questions/12859942/). They are no longer maintained [and are officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). See the [red box](http://uk.php.net/manual/en/function.mysql-connect.php)? Learn about [*prepared statements*](https://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) - [this article](http://php.net/manual/en/mysqlinfo.api.choosing.php) will help you decide which one is best for you. – John Conde Feb 22 '17 at 14:52

4 Answers4

2

As per the documentation of mysql_query function's php manual

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.

For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.

So, search if it's TRUE or FALSE.

if ($done == TRUE) {
Qirel
  • 25,449
  • 7
  • 45
  • 62
2

The documentation says that mysql_query returns FALSE on error. That means instead of testing whether it's equal to 'null' (a string which compares as TRUE), you could just test the boolean-ness directly:

if($done){
    //OK
}else{
    //NOT OK
}

I would be remiss if I didn't mention that the mysql_* family of functions is deprecated, unsafe, and will be removed from future versions of PHP! Instead, I can personally recommend PDO, which I've used with a good amount of success.

Ben
  • 5,952
  • 4
  • 33
  • 44
  • @Juanky Awesome! Could you please accept my answer? Then I could get that strangely addicting point bonus. – Ben Feb 22 '17 at 15:00
1

Hi I think you should use boolean just try this (you'd better use mysqli instead mysql

if(!done) 
{
// something wrong
 echo mysql.. 
}
else 
{
// everything works fine....
}
1

The error catching must be like the following:

if($done === false){
    //NOT OK
}else{
    //OK
}

But as @John Conde mentioned do not use mysql_* because its deprecated.

raffi
  • 139
  • 1
  • 9