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-
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
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).
Check: http://php.net/manual/en/function.mysql-affected-rows.php
$result = mysql_query("INSERT INTO PEOPLE (NAME ) VALUES ('COLE')"));
if($result)
{
echo "Success";
}
else
{
echo "Error";
}
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;