Reputation: 9840
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";
?>
Upvotes: 18
Views: 130576
Reputation: 7527
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).
Upvotes: 9
Reputation: 1667
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
Upvotes: 2
Reputation: 29071
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;
Upvotes: 3
Reputation: 706
$result = mysql_query("INSERT INTO PEOPLE (NAME ) VALUES ('COLE')"));
if($result)
{
echo "Success";
}
else
{
echo "Error";
}
Upvotes: 40