php-mysqlHow to check the result of an insert in PHP and MySQL?
To check the result of an insert in PHP and MySQL, you can use the mysqli_affected_rows() function. This function returns the number of rows affected by the last INSERT, UPDATE, REPLACE or DELETE query.
Example code
$sql = "INSERT INTO table_name (column1, column2, column3) VALUES (value1, value2, value3)";
$result = mysqli_query($conn, $sql);
if (mysqli_affected_rows($conn) > 0) {
echo "Insert successful";
} else {
echo "Insert failed";
}
Output example
Insert successful
Code explanation
$sql: This is the SQL query used to insert data into the table.$result: This is the result of the query.mysqli_query($conn, $sql): This is the function used to execute the query.$connis the connection to the database.mysqli_affected_rows($conn): This is the function used to check the number of rows affected by the query.ifstatement: This is used to check if the query was successful or not.
Helpful links
More of Php Mysql
- How to output XML from MySQL using PHP?
- How to connect to a MySQL database using PHP?
- How to write an update query in MySQL using PHP?
- How to use a MySQL union in PHP?
- How to set a timeout for MySQL query in PHP?
- What port to connect to MySQL from PHP?
- How to convert a MySQL timestamp to a datetime in PHP?
- How to export data from MySQL to Excel using PHP?
- How to create an SSL connection to MySQL using PHP?
- How to change database in MySQL with PHP?
See more codes...