18

I am inserting data to a MySQL DB, In case if the insertion fails i need to give an appropriate error message indicating so. According to my code below i will be Echo-ing the message Inserted if the insertion was success or failure.

What i want to do is to echo the Inserted message only when the data insertion is a success, and return fail if it fails. How can i modify my code to do so ?

<?php

mysql_connect("localhost", "root", "123") or die(mysql_error());
mysql_select_db("swm_database") or die(mysql_error());

mysql_query("INSERT INTO PEOPLE (NAME ) VALUES ('COLE')")or die(mysql_error()); 

echo "Inserted";
?>
1
  • the answers below already state what you should do, but think about using mysqli or PDO rather than the mysql_* functions. Commented Jul 25, 2012 at 12:56

5 Answers 5

40
$result = mysql_query("INSERT INTO PEOPLE (NAME ) VALUES ('COLE')"));
if($result)
{
echo "Success";

}
else
{
echo "Error";

}
Sign up to request clarification or add additional context in comments.

Comments

9

According to the book PHP and MySQL for Dynamic Web Sites (4th edition)

Example:

$r = mysqli_query($dbc, $q);

For simple queries like INSERT, UPDATE, DELETE, etc. (which do not return records), the $r variable—short for result—will be either TRUE or FALSE, depending upon whether the query executed successfully.

Keep in mind that “executed successfully” means that it ran without error; it doesn’t mean that the query’s execution necessarily had the desired result; you’ll need to test for that.

Then how to test?

While the mysqli_num_rows() function will return the number of rows generated by a SELECT query, mysqli_affected_rows() returns the number of rows affected by an INSERT, UPDATE, or DELETE query. It’s used like so:

$num = mysqli_affected_rows($dbc);

Unlike mysqli_num_rows(), the one argument the function takes is the database connection ($dbc), not the results of the previous query ($r).

Comments

3

After INSERT query you can use ROW_COUNT() to check for successful insert operation as:

SELECT IF(ROW_COUNT() = 1,  "Insert Success", "Insert Failed") As status;

2 Comments

Return true does not guarantee the data has been inserted into database, can I say so ?
yes, this is safest way as return true will not work in case of INSERT IGNORE query.
2
if (mysql_query("INSERT INTO PEOPLE (NAME ) VALUES ('COLE')")or die(mysql_error())) {
  echo 'Success';
} else {
  echo 'Fail';
} 

Although since you have or die(mysql_error()) it will show the mysql_error() on the screen when it fails. You should probably remove that if it isnt the desired result

Comments

2

Check: http://php.net/manual/en/function.mysql-affected-rows.php

1 Comment

Helpful, but please do not add a link only answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.