A case of PDO query operation using PDO to connect to mysql
This article mainly introduces relevant information about the detailed explanation of examples of php mysql PDO query operations. I hope this article can help everyone. Friends in need can refer to
php mysql PDO query operations. Detailed example
<?php $dbh = new PDO('mysql:host=localhost;dbname=access_control', 'root', ''); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $dbh->exec('set names utf8'); /*添加*/ //$sql = "INSERT INTO `user` SET `login`=:login AND `password`=:password"; $sql = "INSERT INTO `user` (`login` ,`password`)VALUES (:login, :password)"; $stmt = $dbh->prepare($sql); $stmt->execute(array(':login'=>'kevin2',':password'=>'')); echo $dbh->lastinsertid(); /*修改*/ $sql = "UPDATE `user` SET `password`=:password WHERE `user_id`=:userId"; $stmt = $dbh->prepare($sql); $stmt->execute(array(':userId'=>'7', ':password'=>'4607e782c4d86fd5364d7e4508bb10d9')); echo $stmt->rowCount(); /*删除*/ $sql = "DELETE FROM `user` WHERE `login` LIKE 'kevin_'"; //kevin% $stmt = $dbh->prepare($sql); $stmt->execute(); echo $stmt->rowCount(); /*查询*/ $login = 'kevin%'; $sql = "SELECT * FROM `user` WHERE `login` LIKE :login"; $stmt = $dbh->prepare($sql); $stmt->execute(array(':login'=>$login)); while($row = $stmt->fetch(PDO::FETCH_ASSOC)){ print_r($row); } print_r( $stmt->fetchAll(PDO::FETCH_ASSOC)); ?>
1 Establish a connection
<?php $dbh=newPDO('mysql:host=localhost;port=3306; dbname=test',$user,$pass,array( PDO::ATTR_PERSISTENT=>true )); ?>
Persistent Sexual link PDO::ATTR_PERSISTENT=>true
2. Catching errors
<?php try{ $dbh=newPDO('mysql:host=localhost;dbname=test',$user,$pass); $dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); $dbh->exec("SET CHARACTER SET utf8"); $dbh=null; //断开连接 }catch(PDOException$e){ print"Error!:".$e->getMessage()."<br/>"; die(); } ?>
3. Transaction
<?php try{ $dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); $dbh->beginTransaction();//开启事务 $dbh->exec("insertintostaff(id,first,last)values(23,'Joe','Bloggs')"); $dbh->exec("insertintosalarychange(id,amount,changedate) values(23,50000,NOW())"); $dbh->commit();//提交事务 }catch(Exception$e){ $dbh->rollBack();//错误回滚 echo"Failed:".$e->getMessage(); } ?>
4. Error handling
a. Silent mode (Default mode)
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_SILENT); //不显示错误 $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);//显示警告错误,并继续执行 $dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);//产生致命错误,PDOException
<?php try{ $dbh = new PDO($dsn, $user, $password); $sql = 'Select * from city where CountryCode =:country'; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); $stmt = $dbh->prepare($sql); $stmt->bindParam(':country', $country, PDO::PARAM_STR); $stmt->execute(); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { print $row['Name'] . "/t"; } } // if there is a problem we can handle it here catch (PDOException $e) { echo 'PDO Exception Caught. '; echo 'Error with the database: <br />'; echo 'SQL Query: ', $sql; echo 'Error: ' . $e->getMessage(); } ?>
1. Use query()
<?php $dbh->query($sql); 当$sql 中变量可以用$dbh->quote($params); //转义字符串的数据 $sql = 'Select * from city where CountryCode ='.$dbh->quote($country); foreach ($dbh->query($sql) as $row) { print $row['Name'] . "/t"; print $row['CountryCode'] . "/t"; print $row['Population'] . "/n"; } ?>
2. Use prepare, bindParam and execute [recommended, you can also add, modify, delete]
<?php $dbh->prepare($sql); 产生了个PDOStatement对象 PDOStatement->bindParam() PDOStatement->execute();//可以在这里放绑定的相应变量 ?>
3. Things
<?php try { $dbh = new PDO('mysql:host=localhost;dbname=test', 'root', ''); $dbh->query('set names utf8;'); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $dbh->beginTransaction(); $dbh->exec("Insert INTO `test`.`table` (`name` ,`age`)VALUES ('mick', 22);"); $dbh->exec("Insert INTO `test`.`table` (`name` ,`age`)VALUES ('lily', 29);"); $dbh->exec("Insert INTO `test`.`table` (`name` ,`age`)VALUES ('susan', 21);"); $dbh->commit(); } catch (Exception $e) { $dbh->rollBack(); echo "Failed: " . $e->getMessage(); } ?>
Common PDO methods:
PDO::query() is mainly used for operations with recorded results returned (PDOStatement), especially select operations.
PDO::exec() is mainly for operations that do not return a result set. Such as insert, update and other operations. Returns the number of affected rows.
PDO::lastInsertId() returns the last ID of the last insertion operation, but please note: if you insert into tb(col1,col2) values(v1,v2),(v11,v22).. For multiple records, lastinsertid() returns only the ID when the first record (v1, v2) was inserted, not the record ID of the last record inserted.
PDOStatement::fetch() is used to obtain a record. Use while to traverse.
PDOStatement::fetchAll() is to get all records into one.
PDOStatement::fetchcolumn([int column_indexnum]) is used to directly access the column. The parameter column_indexnum is the index value of the column in the row starting from 0. However, this method can only obtain one column of the same row at a time and only needs to be executed once. , jump to the next line. Therefore, it is easier to use when directly accessing a certain column, but it is not useful when traversing multiple columns.
PDOStatement::rowcount() is suitable for obtaining the number of records when using the query("select...") method. Can also be used in preprocessing. $stmt->rowcount();
PDOStatement::columncount() is suitable for obtaining the number of columns of records when using the query("select...") method.
Notes:
1. Choose fetch or fetchall?
When using a small record set, using fetchall is more efficient and reduces the number of retrieval times from the database. However, for a large result set, using fetchall will put a lot of burden on the system. The amount of data the database needs to transmit to the WEB front-end is too large and inefficient.
2. fetch() or fetchall() has several parameters:
##
mixed pdostatement::fetch([int fetch_style [,int cursor_orientation [,int cursor_offset]]]) array pdostatement::fetchAll(int fetch_style)
■$row=$rs->fetchAll(PDO::FETCH_ASSOC); The FETCH_ASSOC parameter determines that only associative arrays are returned.
■$row=$rs->fetchAll(PDO::FETCH_NUM); Returns the index array
■$row=$rs->fetchAll(PDO::FETCH_OBJ); If fetch() returns the object , if it is fetchall(), return a two-dimensional array composed of objects
The above is the detailed content of A case of PDO query operation using PDO to connect to mysql. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.

Navicat itself does not store the database password, and can only retrieve the encrypted password. Solution: 1. Check the password manager; 2. Check Navicat's "Remember Password" function; 3. Reset the database password; 4. Contact the database administrator.

View the MySQL database with the following command: Connect to the server: mysql -u Username -p Password Run SHOW DATABASES; Command to get all existing databases Select database: USE database name; View table: SHOW TABLES; View table structure: DESCRIBE table name; View data: SELECT * FROM table name;

Create a database using Navicat Premium: Connect to the database server and enter the connection parameters. Right-click on the server and select Create Database. Enter the name of the new database and the specified character set and collation. Connect to the new database and create the table in the Object Browser. Right-click on the table and select Insert Data to insert the data.

Copying a table in MySQL requires creating new tables, inserting data, setting foreign keys, copying indexes, triggers, stored procedures, and functions. The specific steps include: creating a new table with the same structure. Insert data from the original table into a new table. Set the same foreign key constraint (if the original table has one). Create the same index. Create the same trigger (if the original table has one). Create the same stored procedure or function (if the original table is used).

Navicat for MariaDB cannot view the database password directly because the password is stored in encrypted form. To ensure the database security, there are three ways to reset your password: reset your password through Navicat and set a complex password. View the configuration file (not recommended, high risk). Use system command line tools (not recommended, you need to be proficient in command line tools).

Common reasons why Navicat cannot connect to the database and its solutions: 1. Check the server's running status; 2. Check the connection information; 3. Adjust the firewall settings; 4. Configure remote access; 5. Troubleshoot network problems; 6. Check permissions; 7. Ensure version compatibility; 8. Troubleshoot other possibilities.

You can create a new MySQL connection in Navicat by following the steps: Open the application and select New Connection (Ctrl N). Select "MySQL" as the connection type. Enter the hostname/IP address, port, username, and password. (Optional) Configure advanced options. Save the connection and enter the connection name.
