JCAguilera
JCAguilera

Reputation: 976

Getting an error when trying to insert data to table

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?

Upvotes: 0

Views: 57

Answers (4)

Abhishek Kumar
Abhishek Kumar

Reputation: 99

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) {

Upvotes: 2

raffi
raffi

Reputation: 139

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.

Upvotes: 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....
}

Upvotes: 1

Ben
Ben

Reputation: 6348

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.

Upvotes: 2

Related Questions