Home  >  Article  >  Backend Development  >  Detailed explanation of PDO::exec in PHP (with code examples)

Detailed explanation of PDO::exec in PHP (with code examples)

autoload
autoloadOriginal
2021-04-23 12:39:472736browse

Detailed explanation of PDO::exec in PHP (with code examples)

After connecting to the database in PHP, many SQL instructions can be executed directly in PHP, and the executed The function is the exec() function. This article will take you through the use of the exec() function.

First of all, we need to understand the syntax of the exec() function:

exec    ( string $statement   )
  • $statement: SQL statement to be preprocessed and executed .

  • Return value: Returns the number of rows affected by the modify or delete SQL statement. If there are no affected rows, 0 is returned.

Code example:

<?php

$type="mysql";
$servername="localhost";
$dbname="my_database";
$dsn="$type:host=$servername;dbname=$dbname";

$username="root";
$password="root123456";

$pdo=new PDO($dsn,$username,$password);
//错误模式,用于抛出异常
$pdo->setAttribute(PDO::ATTR_CASE, PDO::CASE_UPPER);

$sql="insert into fate values(&#39;5&#39;,&#39;张三&#39;,&#39;66&#39;)";
$pdo->exec($sql);
$sql2="select * from fate where id=5";
$statement =$pdo->query($sql2);
print_r($statement->fetch());
?>
输出:Array
(
    [ID] => 5      [0] => 5
    [NAME] => 张三 [1] => 张三
    [AGE] => 66    [2] => 66
)

Recommendation: 2021 PHP interview questions summary (collection)》《php video tutorial

The above is the detailed content of Detailed explanation of PDO::exec in PHP (with code examples). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn