Execute Insert
<?php $mysqli = new mysqli (); $mysqli->connect ("localhost", "root", "root", "test"); if ($mysqli->connect_errno) {die ($mysqli->connect_error); } $mysqli->set_charset ("UTF8"); $sql = "INSERT into mysqli (ID, name) VALUES (null, ' liming ')"; $res = $mysqli->query ($sql); Var_dump ($res); if ($res) { echo $mysqli->insert_id; } else { echo "error:". $mysqli->errno. ":". $mysqli Error; } $mysqli->close ();? >
Perform an update
<?php $mysqli = new mysqli (); $mysqli->connect ("localhost", "root", "root", "test"); if ($mysqli->connect_errno) {die ($mysqli->connect_error); } $mysqli->set_charset ("UTF8"); $sql = "Update mysqli set name = ' DoUpdate ' where id>8;"; $res = $mysqli->query ($sql); Var_dump ($res); if ($res) { echo $mysqli->affected_rows;//Returns the number of record bars affected by the previous SQL statement } else { echo "error:". $mysqli errno. ":". $mysqli->error; } $mysqli->close ();? >
Perform the delete
<?php $mysqli = new mysqli (); $mysqli->connect ("localhost", "root", "root", "test"); if ($mysqli->connect_errno) {die ($mysqli->connect_error); } $mysqli->set_charset ("UTF8"); $sql = "Delete from mysqli where id>8;"; $res = $mysqli->query ($sql); Var_dump ($res); if ($res) { echo $mysqli->affected_rows;//Returns the number of record bars affected by the previous SQL statement } else { echo "error:". $mysqli errno. ":". $mysqli->error; } $mysqli->close ();? >
Note a
There are several scenarios for affected_rows values, as an example of deleting records
1->sql statement is executed normally, the number of records deleted is greater than 0, then the number of records affected is affected_rows
2->sql statement Normal execution, no record is eligible, that is, the deleted record is 0, then Affected_rows is 0
3->sql Statement Error, that is, the SQL statement is not actually executed, because the error is stop, the value of Affected_rows is 1
Note two
INSERT_ID is the auto_increment value in the database table that is currently available before the SQL statement is executed (this value can be viewed by executing the show CREATE TABLE tablename in the database command line), not after the SQL statement is inserted auto_ The value of the increment.
Assuming that the first database is empty, after inserting 1 data, the ID becomes 1, and Auto_increment becomes 2, and then inserts multiple data at one time through the INSERT statement, and then gets the value of auto_increment (that is, insert_id). The value does not change to the ID of the primary key of the last inserted data, but rather to the 2 that precedes the insertion of more than one piece of data.
If there is no auto_increment in the table, INSERT_ID returns 0.
Mysqli Object-oriented--insert, UPDATE, delete