Check insert mysql php

PHP MySQL Get Last Inserted ID

If we perform an INSERT or UPDATE on a table with an AUTO_INCREMENT field, we can get the ID of the last inserted/updated record immediately.

In the table «MyGuests», the «id» column is an AUTO_INCREMENT field:

CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)

The following examples are equal to the examples from the previous page (PHP Insert Data Into MySQL), except that we have added one single line of code to retrieve the ID of the last inserted record. We also echo the last inserted ID:

Example (MySQLi Object-oriented)

$servername = «localhost»;
$username = «username»;
$password = «password»;
$dbname = «myDB»;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) die(«Connection failed: » . $conn->connect_error);
>

$sql = «INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘John’, ‘Doe’, ‘john@example.com’)»;

if ($conn->query($sql) === TRUE) $last_id = $conn->insert_id;
echo «New record created successfully. Last inserted ID is: » . $last_id;
> else echo «Error: » . $sql . «
» . $conn->error;
>

Example (MySQLi Procedural)

$servername = «localhost»;
$username = «username»;
$password = «password»;
$dbname = «myDB»;

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) die(«Connection failed: » . mysqli_connect_error());
>

$sql = «INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘John’, ‘Doe’, ‘john@example.com’)»;

if (mysqli_query($conn, $sql)) $last_id = mysqli_insert_id($conn);
echo «New record created successfully. Last inserted ID is: » . $last_id;
> else echo «Error: » . $sql . «
» . mysqli_error($conn);
>

Example (PDO)

$servername = «localhost»;
$username = «username»;
$password = «password»;
$dbname = «myDBPDO»;

try $conn = new PDO(«mysql:host=$servername;dbname=$dbname», $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = «INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘John’, ‘Doe’, ‘john@example.com’)»;
// use exec() because no results are returned
$conn->exec($sql);
$last_id = $conn->lastInsertId();
echo «New record created successfully. Last inserted ID is: » . $last_id;
> catch(PDOException $e) echo $sql . «
» . $e->getMessage();
>

Источник

mysqli_affected_rows

Returns the number of rows affected by the last INSERT , UPDATE , REPLACE or DELETE query. Works like mysqli_num_rows() for SELECT statements.

Parameters

Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

Return Values

An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records were updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query returned an error or that mysqli_affected_rows() was called for an unbuffered SELECT query.

Note:

If the number of affected rows is greater than the maximum int value ( PHP_INT_MAX ), the number of affected rows will be returned as a string.

Examples

Example #1 $mysqli->affected_rows example

mysqli_report ( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
$mysqli = new mysqli ( «localhost» , «my_user» , «my_password» , «world» );

/* Insert rows */
$mysqli -> query ( «CREATE TABLE Language SELECT * from CountryLanguage» );
printf ( «Affected rows (INSERT): %d\n» , $mysqli -> affected_rows );

$mysqli -> query ( «ALTER TABLE Language ADD Status int default 0» );

/* update rows */
$mysqli -> query ( «UPDATE Language SET Status=1 WHERE Percentage > 50» );
printf ( «Affected rows (UPDATE): %d\n» , $mysqli -> affected_rows );

/* delete rows */
$mysqli -> query ( «DELETE FROM Language WHERE Percentage < 50" );
printf ( «Affected rows (DELETE): %d\n» , $mysqli -> affected_rows );

/* select all rows */
$result = $mysqli -> query ( «SELECT CountryCode FROM Language» );
printf ( «Affected rows (SELECT): %d\n» , $mysqli -> affected_rows );

/* Delete table Language */
$mysqli -> query ( «DROP TABLE Language» );

mysqli_report ( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
$link = mysqli_connect ( «localhost» , «my_user» , «my_password» , «world» );

/* Insert rows */
mysqli_query ( $link , «CREATE TABLE Language SELECT * from CountryLanguage» );
printf ( «Affected rows (INSERT): %d\n» , mysqli_affected_rows ( $link ));

mysqli_query ( $link , «ALTER TABLE Language ADD Status int default 0» );

/* update rows */
mysqli_query ( $link , «UPDATE Language SET Status=1 WHERE Percentage > 50» );
printf ( «Affected rows (UPDATE): %d\n» , mysqli_affected_rows ( $link ));

/* delete rows */
mysqli_query ( $link , «DELETE FROM Language WHERE Percentage < 50" );
printf ( «Affected rows (DELETE): %d\n» , mysqli_affected_rows ( $link ));

/* select all rows */
$result = mysqli_query ( $link , «SELECT CountryCode FROM Language» );
printf ( «Affected rows (SELECT): %d\n» , mysqli_affected_rows ( $link ));

/* Delete table Language */
mysqli_query ( $link , «DROP TABLE Language» );

The above examples will output:

Affected rows (INSERT): 984 Affected rows (UPDATE): 168 Affected rows (DELETE): 815 Affected rows (SELECT): 169

See Also

  • mysqli_num_rows() — Gets the number of rows in the result set
  • mysqli_info() — Retrieves information about the most recently executed query

User Contributed Notes 7 notes

On «INSERT INTO ON DUPLICATE KEY UPDATE» queries, though one may expect affected_rows to return only 0 or 1 per row on successful queries, it may in fact return 2.

From Mysql manual: «With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row and 2 if an existing row is updated.»

Here’s the sum breakdown _per row_:
+0: a row wasn’t updated or inserted (likely because the row already existed, but no field values were actually changed during the UPDATE)
+1: a row was inserted
+2: a row was updated

If you need to know specifically whether the WHERE condition of an UPDATE operation failed to match rows, or that simply no rows required updating you need to instead check mysqli::$info.

As this returns a string that requires parsing, you can use the following to convert the results into an associative array.

preg_match_all ( ‘/(\S[^:]+): (\d+)/’ , $mysqli -> info , $matches );
$info = array_combine ( $matches [ 1 ], $matches [ 2 ]);
?>

Procedural style:

preg_match_all ( ‘/(\S[^:]+): (\d+)/’ , mysqli_info ( $link ), $matches );
$info = array_combine ( $matches [ 1 ], $matches [ 2 ]);
?>

You can then use the array to test for the different conditions

if ( $info [ ‘Rows matched’ ] == 0 ) echo «This operation did not match any rows.\n» ;
> elseif ( $info [ ‘Changed’ ] == 0 ) echo «This operation matched rows, but none required updating.\n» ;
>

if ( $info [ ‘Changed’ ] < $info [ 'Rows matched' ]) echo ( $info [ 'Rows matched' ] - $info [ 'Changed' ]). " rows matched but were not changed.\n" ;
>
?>

This approach can be used with any query that mysqli::$info supports (INSERT INTO, LOAD DATA, ALTER TABLE, and UPDATE), for other any queries it returns an empty array.

For any UPDATE operation the array returned will have the following elements:

Array
(
[Rows matched] => 1
[Changed] => 0
[Warnings] => 0
)

While using prepared statements, even if there is no result set (Like in an UPDATE or DELETE), you still need to store the results before affected_rows returns the actual number:

$del_stmt -> execute ();
$del_stmt -> store_result ();
$count = $del_stmt -> affected_rows ;
?>

Otherwise things will just be frustrating ..

Under the hood, this calls into mysql_affected_rows (1). The MariaDB function ROW_COUNT() mentions (2) that it is the equivalent of that C API function. These two lines, SQL followed by PHP, should be equivalent:

I found this useful to double check things in an SQL prompt, to make sure affected_rows is reflecting what I expect (changed rows as opposed to matched rows in an update statement), which indeed it did.

empty($db->affected_rows) will return TRUE even if affected_rows is greater than 0. Manually check < 1 if you're looking for failure.

This may seem obvious, but if you do an UPDATE with each of the values in your SET clause having the exact same value that is already in the table, then affected_rows returns 0. For example:

$mysqli = new mysqli ( $host , $usr , $pwd , $db , $port );
$appointment_date = «2015-12-07» ;
$sql = «update appointments set appointment_date = ? where appointment_id = 78» ;
$stmt = $mysqli -> prepare ( $sql );
$stmt -> bind_param ( «s» , $appointment_date );
$stmt -> execute ();
echo $mysqli -> affected_rows . «
» ;
?>

This returns 1 the first time I run it after changing the value of the $appointment_date variable. When I run it a second time (making no changes), it returns 0. I also verified the same behavior without using prepared statements.

For «INSERT» or «UPDATE» statement for modifying data contained in one row of one table I checked if number of affected rows equals 1 to determine success of the operation. It works fine both for errors and false value of WHERE condition (that might be generated according to specific application user acces privileges).
if ( $mysqli -> affected_rows == 1 ) echo «success» ;
>
else echo «fail» ;
>
?>

Checking if mysqli->affected_rows will equal -1 or not is not a good method of determining success of «INSERT IGNORE» statements. Example: Ignoring duplicate key errors while inserting some rows containing data provided by user only if they will match specified unique constraint causes returning of -1 value by mysqli->affected_rows even if rows were inserted. (checked on MySQL 5.0.85 linux and php 5.2.9-2 windows). However mysqli->sqlstate returns no error if statement was executed successfully.
if ( $mysqli -> affected_rows !=- 1 ) echo «success» ; // for «INSERT IGNORE» statements will not occur if there were any duplicate key errors ignored during execution of the query
>
else echo «fail» ; // «INSERT IGNORE» statements causing any duplicate key errors (however ignored) lead to mysqli->affected_rows equal -1
>

// Example below works for «INSERT IGNORE» stattements, too
if ( $mysqli -> sqlstate == «00000» ) echo «success» ;
>
else echo «fail» ;
>
?>

Источник

PHP MySQL Insert Data

After a database and a table have been created, we can start adding data in them.

Here are some syntax rules to follow:

  • The SQL query must be quoted in PHP
  • String values inside the SQL query must be quoted
  • Numeric values must not be quoted
  • The word NULL must not be quoted

The INSERT INTO statement is used to add new records to a MySQL table:

To learn more about SQL, please visit our SQL tutorial.

In the previous chapter we created an empty table named «MyGuests» with five columns: «id», «firstname», «lastname», «email» and «reg_date». Now, let us fill the table with data.

Note: If a column is AUTO_INCREMENT (like the «id» column) or TIMESTAMP with default update of current_timesamp (like the «reg_date» column), it is no need to be specified in the SQL query; MySQL will automatically add the value.

The following examples add a new record to the «MyGuests» table:

Example (MySQLi Object-oriented)

$servername = «localhost»;
$username = «username»;
$password = «password»;
$dbname = «myDB»;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) die(«Connection failed: » . $conn->connect_error);
>

$sql = «INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘John’, ‘Doe’, ‘john@example.com’)»;

if ($conn->query($sql) === TRUE) echo «New record created successfully»;
> else echo «Error: » . $sql . «
» . $conn->error;
>

Example (MySQLi Procedural)

$servername = «localhost»;
$username = «username»;
$password = «password»;
$dbname = «myDB»;

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) die(«Connection failed: » . mysqli_connect_error());
>

$sql = «INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘John’, ‘Doe’, ‘john@example.com’)»;

if (mysqli_query($conn, $sql)) echo «New record created successfully»;
> else echo «Error: » . $sql . «
» . mysqli_error($conn);
>

Example (PDO)

$servername = «localhost»;
$username = «username»;
$password = «password»;
$dbname = «myDBPDO»;

try $conn = new PDO(«mysql:host=$servername;dbname=$dbname», $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = «INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘John’, ‘Doe’, ‘john@example.com’)»;
// use exec() because no results are returned
$conn->exec($sql);
echo «New record created successfully»;
> catch(PDOException $e) echo $sql . «
» . $e->getMessage();
>

Источник

Читайте также:  Html javascript php book
Оцените статью