Pdo
Use for different database connections
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<title> Untitled Document </title>
<body>
<?php
Create DSN: Driver name: dbname= database name; host= server address
$DSN = "Mysql:dbname=mydb;host=localhost";
Making PDO objects
$pdo = new PDO ($DSN, "root", "123");
Write SQL statements
$sql = "SELECT * from Info";
Execute SQL statement
$v = $pdo->query ($sql);
The returned objects are special and can be traversed directly with loops
/*foreach ($v as $a)
{
echo $a [0];
}*/
Preprocessing, first put the SQL statement on the server waiting for us to give him instructions to execute
Prepare an SQL statement
$stm = $pdo->prepare ($sql);
Executes the prepared SQL statement, returns true successfully, fails to return false
if ($stm->execute ())
{
1. Progressive data fetching
Var_dump ($stm->fetch ());
2. Take all
Var_dump ($stm->fetchall (pdo::fetch_obj));
3. Take a column
Var_dump ($stm->fetchcolumn (1));
4. Returning objects
Var_dump ($stm->fetchobject ());
}
Else
{
echo "Failed to execute!" ";
}
?>
</body>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<title> Untitled Document </title>
<body>
<?php
Created objects
$DSN = "Mysql:dbname=mydb;host=localhost";
$pdo = new PDO ($DSN, "root", "123");
Write the SQL statement, the parameter is replaced by the
$sql = "INSERT into Nation values (?,?)";
$sql = "INSERT INTO Nation values (: Code,:name)";
Pretreatment
$stm = $pdo->prepare ($sql);
Binding a value to a parameter
/* $stm->bindparam (1, $code);
$stm->bindparam (2, $name);
$code = "P100";
$name = "Home"; */
/* $stm->bindparam ("code", $code, PDO::P aram_str);
$stm->bindparam ("name", $name, PDO::P aram_str);
$code = "p102";
$name = "Home"; */
Build arrays
$attr = Array ("p101", "soon");
$attr = Array ("Code" = "p103", "name" = "Shj");
Perform
if ($stm->execute ($_post))
{
echo "Add success";
}
Else
{
echo "Add failed";
}
?>
</body>
Self-hitting Configuration tool
<?php
Class Pdoa
{
Public $host = "localhost";//Database address
Public $uid = "root";//database user name,
Public $pwd = "";//Database Password
A method that executes an SQL statement that returns a corresponding result
Arguments: $sql represents the SQL statement to execute, $type is the SQL statement type 0 for query 1 on behalf of the other, $db represents the database to be manipulated
Public Function Prepare ($sql, $db = "BCS")
{
$DSN = "Mysql:dbname= $db; host= $this->host";
$pdo = new PDO ($DSN, $this->uid, $this->pwd);
3. Execute SQL statements
$stm = $pdo->prepare ($sql);
if ($stm->execute ())
{
return $stm->fetchall ();
}
Else
{
echo "Connection Failed";
}
}
}
PHP 18th Session