Brief introduction
Let's look at the PDO class together. PDO is the abbreviation for PHP Data objects, which is described as "lightweight, compatible interface for accessing databases in PHP." Although its name is not nice, PDO is a favorite way to access a database in PHP.
Different from the Mysqli
Mysqli and PDO are very similar, and there are two main differences:
1.MySQLi can only access MySQL, but PDO can access 12 different databases
2.PDO No ordinary function call (mysqli_*functions)
Start Step
First, you need to make sure that your PHP has the PDO plugin installed. You can use the results of $test=new PDO () to test. If the hint says is the parameter does not match, that proves already installed the PDO plug-in, if say is the object does not exist, you have to confirm first in Pho.ini whether Php_pdo_yourssqlserverhere.extis is commented out. If there is no such sentence, then you have to install PDO, here is not long-winded.
Connection
Now we confirm that the server is working and start connecting to the database:
$dsn = ' mysql:dbname=demo;host=localhost;port=3306 ';
$username = ' root ';
$password = ' Password_here ';
try {
$db = new PDO ($DSN, $username, $password);//also allows an extra parameter of configuration
} catch (Pdoexc Eption $e) {
die (' could not connect to the database:<br/> '. $e);
}
All statements and variables are self explanatory except for $DSN. DSN refers to the data source name, with a variety of input types. The most common is the one we just used, and the PHP website explains the other available DSN.
You can omit other additional parameters for the DSN by simply following the database driver with a colon, for example (MySQL:). In this case PDO will attempt to connect to the local database. Just like when you use mysqli, you need to specify the database name in the query.
The last thing you need to be aware of is that we use try-catch blocks to wrap our initialization objects. When a PDO connection fails, the pdoexception exception is thrown rather than when the query fails. If you want you can use the following code $db=line to select the exception pattern.
$db->setattribute (Pdo::attr_errmode, pdo::errmode_exception);
Or you can pass parameters directly on PDO initialization:
$db = new PDO ($DSN, $username, $password, Array (
pdo::attr_errmode => pdo::errmode_exception
));
We are now using the wrong way-simply return false when we fail, and there is no reason to not handle the exception.
Basic Query
The use of query and exec two methods in PDO makes database queries very simple. If you want the row number of the query results exec is very handy, so it is very useful for select query statements.
Now let's look at both of these methods by using one of the following examples:
$statement = <<<sql
SELECT * from
' foods '
WHERE ' healthy ' = 0
SQL;
$foods = $db->query ($statement);
Assuming our query is correct, $foods is now a PDO statement object, we can use it to get our results or to see how many result sets we've found in this query.
Number of rows
The disadvantage is that PDO does not provide a uniform way to calculate the number of rows returned. PDO statement contains a method called rowcount, but this method does not guarantee a role in every SQL drive (fortunately, it works in the MySQL database).
If your SQL driver doesn't support this approach, you have 2 choices: use two queries (SELECT COUNT (*)) or use simple count ($foods) to get the number of rows.
Fortunately for our MySQL example, we can use the following simple method to output the correct number of rows.
echo $foods->rowcount ();
Traverse result set
It is not difficult to print out these delicious foods:
foreach ($foods->fetchall () as $food) {
echo $food [' name ']. ' <br/> ';
}
The only thing to note is that PDO also supports the Fetch method, which only returns the first result, which is useful for querying only one result set.
Escape user input (special characters)
Have you ever heard of (Mysqli_) real_escape_string, which is used to ensure that users enter security data. PDO provides a method called quote, which can be used to escape special characters in quotes in an input string.
$input: This is ' a ' ' a ' ' Pretty Dange ' rous str ' ing
After escaping, you end up with the following result:
$db->quote ($input): ' This is\ ' s\ ' a \ ' \ ' Pretty dange\ ' rous '-str\ ' ing '
exec ()
As mentioned above, you can use the Exec () method to implement Update,delete and insert operations, which will return the number of affected rows after execution:
$statement = <<<sql
DELETE from ' Foods '
WHERE ' healthy ' = 1;
SQL;
echo $db->exec ($statement); Outputs number of deleted rows
Preprocessing statements
Although the Exec method and query are still heavily used and supported in PHP, the PHP official web site requires that you use the method of preprocessing statements instead. Why, then? Mainly because: it is more secure. Preprocessing statements do not insert parameters directly into the actual query, which avoids many potential SQL injections.
However, for some reason, PDO actually does not really use preprocessing, it is in the analog preprocessing way, the parameter data is inserted into the statement before passing the statement to the SQL Server, which makes some systems susceptible to SQL injection.
If your SQL Server does not really support preprocessing, we can easily fix this problem by initializing the PDO Shishun in the following way:
$db->setattribute (Pdo::attr_emulate_prepares, false);
Now let's start with our first preprocessing statement:
$statement = $db->prepare (' SELECT * from Foods WHERE ' name ' =? and ' healthy ' =? ');
$statement 2 = $db->prepare (' SELECT * from Foods WHERE ' name ' =:name ' and ' healthy ' =:healthy ') ';
As you can see, there are two ways to create parameters, named and Anonymous (not appearing in a single statement at the same time). Then you can use Bindvalue to tap into your input:
$statement->bindvalue (1, ' Cake ');
$statement->bindvalue (2, true);
$statement 2->bindvalue (': Name ', ' Pie ');
$statement 2->bindvalue (': Healthy ', false);
Note that when you use named parameters, you include a colon (:). PDO also has a Bindparam method that can refer to a binding value, which means it only looks for the corresponding value when the statement executes.
The only thing left to do now is to execute our statement:
$statement->execute ();
$statement 2->execute ();
Get our results:
$cake = $statement->fetch ();
$pie = $statement 2->fetch ();
To avoid using only code fragments brought by Bindvalue, you can use an array to give the Execute method an argument, like this:
$statement->execute (Array (1 => ' Cake ', 2 => true));
$statement 2->execute (Array (': Name ' => ' Pie ', ': Healthy ' => false));
Transaction
Before we've described what a transaction is:
A transaction is the execution of a set of queries, but does not save their impact to the database. The advantage of doing this is that if you execute 4 interdependent inserts, you can roll back after one fails so that other data cannot be inserted into the database, ensuring that the fields that depend on each other are properly inserted. You need to make sure that you use the database engine to support transactions.
Open Transaction
You can simply use the BeginTransaction () method to open a transaction:
$db->begintransaction ();
$db->intransaction (); true!
You can then proceed to execute your database operation statement and commit the transaction at the end:
There is also a rollback () method in Mysqli, but it is not a rollback of all types (such as using Drop TABLE in MySQL), and this method is not really reliable, and I recommend that you avoid relying on this method as much as possible.
Other useful options
There are several options you can consider using. These can be input as the fourth parameter of your object initialization.
$options = Array ($option 1 => $value 1, $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, and return an anonymous object so you can 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
-All read modes
We have explained this in the above, but those who like Trycatch need to use: pdo::errmode_exception. If you want to throw PHP warnings for whatever reason, use pdo::errmode_warning.
Pdo::attr_timeout
When you are worried about loading time, you can use this property to specify a timeout time for your query in seconds. Note that if more than you set the time, the provincial capital throws e_warning exceptions unless the pdo::attr_errmode is changed.
More property information can be seen in the PHP website's property settings.
the last thought
PDO is a great way to access your database in PHP, which can be considered the best way. There is no reason not to use PDO unless you reject the object-oriented approach or the Mysqli method name.
It's better to switch completely to using only preprocessing statements, which will ultimately make your life easier!