Summary of PHP PDO operations_javascript skills
0x01: Test whether PDO is installed successfully
Run the following code. If the parameter error is prompted, PDO has been installed. If the object does not exist, modify the PHP configuration file php.ini and cancel the comment in front of php_pdo_yourssqlserverhere.extis.
$test=new PDO();
0x02: Connect to database
Run the Apache server, make sure the server is running and PDO is installed successfully, then let’s connect to the database.
$dsn = 'mysql:dbname=demo;host=localhost;port=3306';
$username = 'root';
$password = 'password_here';
try {
$db = new PDO($dsn, $username, $password);
} catch(PDOException $e) {
Die('Could not connect to the database:
' . $e);
}
0x03: Basic query
Using query and exec methods in PDO makes database query very simple. If you want to get the number of rows in the query result, exec is very easy to use, so it is very useful for SELECT query statements.
$statement = <<
FROM `foods`
WHERE `healthy` = 0
SQL;
$foods = $db->query($statement);
If the above query is correct, $foods is now a PDO Statement object. We can get the results we need from this object and how many result sets we have queried in total.
0x04: Get the number of lines
If you are using a Mysql database, the PDO Statement contains a rowCount method to get the number of rows in the result set, as shown in the following code:
echo $foods->rowCount;
0x05: Traverse the result set
PDO Statment can be traversed using the forech statement, as shown in the following code:
foreach($foods->FetchAll() as $food) {
echo $food['name'] . '
';
}
PDO also supports the Fetch method, which only returns the first result.
0x06: Escape special characters entered by the user
PDO provides a method called quote, which can escape special characters in places with quotes in the input string.
$input= this is's' a '''pretty dange'rous str'ing
After transferring using quote method:
$db->quote($input): 'this is's' a '''pretty dange'rous str'ing'
0x07: exec()
PDO can use the exec() method to implement UPDATE, DELETE and INSERT operations. After execution, it will return the number of affected rows:
$statement = <<
WHERE `healthy` = 1;
SQL;
echo $db->exec($statement);
0x08: Prepared statement
Although exec methods and queries are still widely used and supported in PHP, the PHP official website still requires everyone to use prepared statements instead. Why? Mainly because: it's safer. Prepared statements do not insert parameters directly into the actual query, which avoids many potential SQL injections.
However, for some reason, PDO does not actually use preprocessing. It simulates preprocessing and inserts parameter data into the statement before passing it to the SQL server. This makes some The system is vulnerable to SQL injection.
If your SQL server does not really support preprocessing, we can easily fix this problem by passing parameters during PDO initialization as follows:
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
Here is our first prepared statement:
$statement = $db->prepare('SELECT * FROM foods WHERE `name`=? AND `healthy`=?');
$statement2 = $db->prepare('SELECT * FROM foods WHERE `name`=:name AND `healthy`=:healthy)';
As shown in the above code, there are two ways to create parameters, named and anonymous (cannot appear in one statement at the same time). You can then use bindValue to type in your input:
$statement->bindValue(1, 'Cake');
$statement->bindValue(2, true);
$statement2->bindValue(':name', 'Pie');
$statement2->bindValue(':healthy', false);
Note that you need to include a colon (:) when using named parameters. PDO also has a bindParam method that can bind values by reference, which means that it only looks for the corresponding value when the statement is executed.
The only thing left to do now is to execute our statement:
$statement->execute();
$statement2->execute();
//Get our results:
$cake = $statement->Fetch();
$pie = $statement2->Fetch();
In order to avoid the code fragmentation caused by using only bindValue, you can use an array as a parameter to the execute method, like this:
$statement->execute(array(1 => 'Cake', 2 => true));
$statement2->execute(array(':name' => 'Pie', ':healthy' => false));
0x09: Transaction
A transaction executes a set of queries but does not save their effects in the database. The advantage of this is that if you execute 4 interdependent insert statements, when one fails, you can roll back so that other data cannot be inserted into the database, ensuring that interdependent fields can be inserted correctly. You need to make sure that the database engine you use supports transactions.
0x10: Start transaction
You can simply use the beginTransaction() method to start a transaction:
$db->beginTransaction();
$db->inTransaction(); // true!
Then you can continue to execute your database operation statements and commit the transaction at the end:
$db->commit();
There is also a method similar to the rollBack() in MySQLi, but it does not roll back all types (such as using DROP TABLE in MySQL). This method is not really reliable. I recommend trying to avoid relying on this method.
0x11: Other useful options
There are several options you can consider. These can be entered as the fourth parameter when initializing your object.
$options = array($option1 => $value1, $option[..]);
$db = new PDO($dsn, $username, $password, $options);
PDO::ATTR_DEFAULT_FETCH_MODE
You can choose what type of result set PDO will return, such as PDO::FETCH_ASSOC, which will allow you to use $result['column_name'], or PDO::FETCH_OBJ, which will return an anonymous object for you to use $result->column_name
You can also put the results into a specific class (model) by setting a read mode for each individual query, like this:
$query = $db->query('SELECT * FROM `foods`');
$foods = $query->fetchAll(PDO::FETCH_CLASS, 'Food');
PDO::ATTR_ERRMODE
We have already explained this above, but people who like TryCatch need to use: PDO::ERRMODE_EXCEPTION. If you want to throw a PHP warning for whatever reason, use PDO::ERRMODE_WARNING.
PDO::ATTR_TIMEOUT
When you are worried about loading time, you can use this attribute to specify a timeout for your query, in seconds. Note that if the time you set is exceeded, an E_WARNING exception will be thrown by default, unless PDO::ATTR_ERRMODE was changed.

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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











This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7
