[php] Insert data to MySql DB and display if insertion is success or failure

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";
?>

This question is related to php mysql

The answer is


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


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;


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