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

前端 未结 5 1889
执念已碎
执念已碎 2020-12-10 05:09

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-

相关标签:
5条回答
  • 2020-12-10 05:40
    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

    0 讨论(0)
  • 2020-12-10 05:52

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

    0 讨论(0)
  • 2020-12-10 05:55

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

    0 讨论(0)
  • 2020-12-10 05:57
    $result = mysql_query("INSERT INTO PEOPLE (NAME ) VALUES ('COLE')"));
    if($result)
    {
    echo "Success";
    
    }
    else
    {
    echo "Error";
    
    }
    
    0 讨论(0)
  • 2020-12-10 06:04

    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;
    
    0 讨论(0)
提交回复
热议问题