Hongmu Notes
Home Language Notes sqlite uses PDO to execute SQL statements exec(), query()
Language Notes mySql

sqlite uses PDO to execute SQL statements exec(), query()

sqlite uses PDO to execute SQL statements exec(), query()

In PHP scripts, executing SQL queries to interact with the database through PDO can be divided into three different strategies. Which method to use depends on what operations you want to do.

1. Use the PDO::exec() method

When executing queries without result sets such as INSERT, UPDATE, and DELETE, use the exec() method in the PDO object to execute them.该方法成功执行后,将返回受影响的行数。 Note that this method cannot be used for SELECT queries. An example looks like this:


<?php
    try {
        $pdo = new PDO ('mysql:host=localhost;dbname=testdb','root','123');
        $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
        $pdo->exec('set names "utf8"');
    } catch (PDOException $e) {
        exit("数据库连接失败: ".$e -> getMessage());
    }

    $sql = "UPDATE contactInfo SET phone='15801680168' where name='高某某'";

    //使用exec()方法可以执行INSERT、UPDATE、DELETE等

    $affected = $pdo->exec($sql);

    if ($affected) {
        echo "数据表中受影响的行数为: ".$affected;
    } else {
        print_r($pdo->errorInfo());
    }
    
 ?>

2. Use the PDO::query() method

When executing a SELECT query that returns a result set, or when the number of rows affected is not important, the query() method on the PDO object should be used. If the method successfully executes the specified query, it returns a PDOStatement object. If you use the query() method and want to know the total number of data rows obtained, you can use the rowCount() method in the PDOStatement object to obtain it. Sample code looks like this:


 <?php  
     try {
        $pdo = new PDO ('mysql:host=localhost;dbname=testdb','root','123');
        $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
        $pdo->exec('set names "utf8"');
    } catch (PDOException $e) {
        exit("数据库连接失败: ".$e -> getMessage());
    }
    $sql = "SELECT name, phone, email FROM contactInfo WHERE departmentId='D01'";
    try {
        //执行SELECT查询,并返回PDOstatement对象  
        $pdostatement = $pdo->query("$sql");
        echo "一共从表中获取到".$pdostatement->rowCount()."条记录:n";
        //利用循环输出
        foreach ($pdostatement as $row) {
            echo $row['name'] . "t";           //输出从表中获取到的联系人的名字
            echo $row['phone'] . "t";       //输出从表中获取到的联系人的电话
            echo $row['email'] . "n";       //输出从表中获取到的联系人的电子邮件
        }
    } catch (PDOException $e) {
        echo $e->getMessage(); 
    }
 ?>

3. Use the two methods PDO::prepare() and PDOStatement::execute()

When the same query needs to be executed multiple times (sometimes iteratively passing in different column values), it will be more efficient to use prepared statements. To use prepared statements, you need to use the prepare() method in the PDO object to prepare a query to be executed, and then use the execute() method in the PDOStatement object to execute it.

 
微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

Mysql efficiency improvement: limit this piece of shit

Mysql efficiency improvement: limit this piece of shit Language Notes mySql

In mysql, the efficiency of limit is not high, especially my millions of data, limit 100000, 50, so writing, the query is even slower, at first it was quite fast, and the server cup behind it was directly filled for me! I thought the server was hacked, so I looked for the problem. I looked for it for a few days, but it turned out to be this dog, which made me angry! So I inquired about the principle of limit, emmm, change! Must be changed ...
👁 155
SQL statement to truncate the database

SQL statement to truncate the database Language Notes mySql

The TRUNCATE command can be used to clear a table; however, if you need to clear an entire database, you must clear each table individually. Below is an example SQL statement for clearing an entire database: SET foreign_key_checks = 0; SELECT CONCAT('TRUNCATE TABLE `',table_name,'`;') FR...
👁 297
Query error: #1075-Incorrect table definition; there can be only one auto column, and it must be defined as a key.

Query error: #1075-Incorrect table definition; there can be only one auto column, and it must be defined as a key. Language Notes mySql

This error message indicates that you have defined multiple auto-increment columns when creating a table, or that you have not defined an auto-increment column as a primary key or a unique key; as a result, MySQL is unable to create the table. In MySQL, there can be only one auto-increment column, and it must be defined as a primary key or a unique key. Here are some possible ways to resolve this issue: Ensure that there is only one auto-increment column: You should check your table definition to confirm that only one column is defined as an auto-increment column. If you need...
👁 409

Recommended reading

Responsive ceramicware tableware website template 0932

Responsive ceramicware tableware website template 0932 Practical Collection Yiyou template

This set of eyoucms responsive templates is suitable for the ceramic ware and tableware industry. The design style is elegant and exquisite, and can display ceramic tableware products, utensil series, brand stories and space matching. Helps ceramic brands to display products online and attract home and gift customers. Template display Installation instructions Website backend: /login.php Account: admin Password: admin Related articles Yiyou CMS installation FAQ summary Yiyou...
👁 62
(Adaptive mobile version) Responsive interior design website template – Download source code for interior decoration company websites – 0973

(Adaptive mobile version) Responsive interior design website template – Download source code for interior decoration company websites – 0973 Practical Collection pbootcms Template

A responsive interior design website template and PbootCMS website template for decoration companies, compatible with both PC and WAP devices. The modern, professional design style is ideal for showcasing interior design projects, construction expertise, and service workflows. This template helps decoration companies attract homeowners online and secure new projects. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn...
👁 48
Notes on website resource file source code description

Notes on website resource file source code description Language Notes

All source code resources on this site come from public channels on the Internet. We have built, installed and tested locally, and repaired and optimized a large number of compatibility issues (such as section confusion, abnormal styles, running errors, etc.). After eliminating resources that were inoperable or seriously defective, we moderately processed some pictures and display information, and finally compiled and released them for developers to learn and communicate. Due to limited website time and energy, there may still be some undiscovered resources...
👁 90
(Adaptive Mobile Version) Industrial Equipment Website Template – Responsive Mechanical Equipment Website Source Code Download: 0974

(Adaptive Mobile Version) Industrial Equipment Website Template – Responsive Mechanical Equipment Website Source Code Download: 0974 Practical Collection pbootcms Template

An industrial equipment and responsive mechanical machinery PbootCMS website template compatible with both PC and WAP devices. The professional industrial design style is ideal for machinery manufacturing companies to showcase their product ranges. It helps mechanical companies establish an online brand presence and attract industrial customers. Template Preview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn...
👁 48