PDO:: exec explanation

  • 2021-11-14 05:15:32
  • OfStack

PDO::exec

PDO:: exec-Executes an SQL statement and returns the number of rows affected (PHP 5 > = 5.1.0, PECL pdo > = 0.1.0)

Description

Grammar


int PDO::exec ( string $statement )

PDO::exec() Executes an SQL statement in a single function call, returning the number of rows affected by the statement.

PDO::exec() No result is returned from 1 SELECT statement. For SELECT statements that only need to be issued once in the program, you can consider using PDO::query() .

Parameter description:

statement: The SQL statement to be preprocessed and executed.

Return value

PDO::exec() Returns the number of rows affected by modifying or deleting SQL statements. If there are no affected rows, PDO:: exec () returns 0.

The following example relies incorrectly on the return value of PDO:: exec (), where a statement with a number of affected rows of 0 results in a call to die ():


<?php
$db->exec() or die(print_r($db->errorInfo(), true));
?>

Instances

Execute 1 DELETE statement

Counts the number of rows deleted by an DELETE statement without an WHERE sentence.


<?php
$dbh = new PDO('odbc:sample', 'db2inst1', 'ibmdb2');
/*  Delete  FRUIT  All rows in the data table that meet the conditions  */
$count = $dbh->exec("DELETE FROM fruit WHERE colour = 'red'");
/*  Returns the number of rows deleted  */
print("Deleted $count rows.\n");
?>

The above routine outputs:

Deleted 1 rows.

Summarize


Related articles: