Introduction to Database PDO

Introduction php, php history, php backend engineer career prospects, php technical direction, php backend system introduced professional engineers.

php is the world's most widely used web development language, Hypertext Preprocessor, is a versatile open source scripting language, syntax absorb the c language, Java, and Perl's features, conducive to learning, widely used, mainly for in web development, PHP dynamic pages to do it compared to other programming languages, PHP is embedded into HTML documents continue to execute, execute efficient than completely CGI generated HTML markup is much higher, PHP can also perform post-compilation the code, the compiler can achieve the purpose of encryption and optimized code, make the code run faster.

PHP is started just a simple program written in Perl language created in 1994 by Rasmus Lerdorf, used to count visitors to his site, and later rewritten by the c language, you can access the database, started in 1995 released the first version, name Personal Home Page Tools, and then released php version 1.0.

In 1995, php2.0 released. In 1997, php3 released in 2004, PHP5.0 released.

PHP is used more widely, web3.0 warming, PHP is an excellent web development languages, linux, apache, mysql gold portfolio.

backend web technology, with web technology PHP language front end, linux operating system, mysql database, various php development framework, and massive data caching optimization techniques, system tuning and load balancing.

Getting Started with HTML, JavaScript entry, PHP language foundation, source code management, mysql database.

Linux operating system, PHP object-oriented, high-level language development techniques, commonly used PHP development framework, PHP and public api interface development, PHP testing tools.

Depth study http protocol, PHP advanced configuration environment, mysql database optimization techniques, static and caching technology, website security technology.

Depth analysis of the PHP source code framework, in-depth study of the PHP core, noSQL database, clustering and load balancing technology.

Depth study of the Linux operating system, multi-level caching technology, massive data optimization technology, disaster recovery technology, large-scale system design methodology framework.

PDO Database Description:

pdo introduction, installation and configuration, pdo link database, presentation and use pdo object methods, pdostatement introduction and use of object methods, pdo error handling, pretreatment with pdo parameter binding, pdo transaction, pdo combat.

pdo is a database access abstraction layer, unified interface to access a variety of databases.

pdo characteristics, encoding consistency, flexibility, performance, object-oriented features.

image.png

Open pdo:

extension = php_pdo.dll
extension = php_pdo_mysql.dll

Connection parameter form, in the form of uri connection, connecting to the database through a configuration file.

<?php
// 通过参数形式连接数据库
try {
 $dsn = 'mysql:host=localhost; dbname=dashucoding'; $username=‘root’; $passwd='root'; $pdo=new PDO($dsn, $username, $passwd); var_dump($pdo); }catch(PDOException $e){ echo $e -> getMessage(); }

image.png

<?php
// 通过uri的形式连接数据库
try {
 $dsn='uri:file//文件路径\dsn.txt'; $username='root'; $passwd='root'; $pdo = new PDO($dsn, $username, $password); var_dump($pdo); }catch(PDOException $e){ echo $e->getMessage(); }
mysql:dbname=dashucoding; host=localhost

image.png

Inserting the recording operation

<?php
try{
$pdo = new PDO('mysql:host=localhost;dbname='dashucoding','root','root'); // exec对select没有作用 // exec()执行一条语句并返回其受影响的记录条数 $sql = <<<EOF CREATE TABLE IF NOT EXISTS user( id INT UNSIGNED AUT_INCREMENT key, username varchar(20) not null unique, password CHAR(32) not null, email varchar(30) not null ); EOF;  $res = $pdo -> exec($sql);  var_dump($res);  $sql='insert user(username,password,email) values ('dashu',"'.md5('dashu').'","[email protected]")')); }catch(PDOException $e){ echo $e -> getMessage(); }

errorCode () and errorInfo () method to see the error message

<?php
header('content-type:text/html; charset=utf-8');

try{
$pdo = new PDO('mysql:host=localhost; dbname=dashucoding', 'root', 'root'); $res = $pdo->exec($sql); var_dump($res); if($res === false){ echo $pdo -> errorCode(); echo '<br/>'; echo $pdo -> errorInfo(); print_r($errInfo); } }catch(PDOException $e){ echo $e->getMessage(); }

query () method performs the query

<?php
header('content-type:text/html; charset=utf-8');
try{
 $pdo = new PDO('mysql:host=localhost; dbname=dashucoding', 'root', 'root'); $sql = 'select * from user where id = 3'; $stmt = $pdo -> query($sql); var_dump($stmt); foreach($stmt as $row){ } }catch(PDOException $e){ echo $e -> getMessage(); }

image.png

Learn pdo, the database connection method, the method of execution in pdo sql statement, pdo get the results set of methods, how to get the pdo sql statement error, error handling method, transaction processing, pdo stored procedure.

pdo is PHP Data Objects.

pdo is a database access abstraction layer, can be unified interface to access a variety of databases.

Install pdo, linux environment, to use the configure command mysql database:

--with-pdo-mysql=/path/to/mysql/installation

pdo connect to the database:

<?php
$dbms = 'mysql';
$dbName = 'db_database';
$user = 'root'; $pwd = 'root'; $host = 'localhost'; $dsn = "$dbms:host=$host; dbname=$dbName"; try{ $pdo = new PDO($dsn, $user, $pwd); echo "pdo连接mysql成功"; }catch(Exception $e){ echo $e -> getMessage()."<br>"; } ?>

dsn: Data Source Name
username: connect to the database username
password: password to connect to the database
driver_options: Other options for connecting to the database

<?php
header('Content-Type:text/html; charset=utf-8");
$dbms='mysql';
$dbName='db_database'; $user='root'; $pwd='root'; $host='localhost'; $dsn="$dbms:host=$host;dbname=$dbName"; try{  $pdo=new PDO($dsn, $uer, $pwd); echo "PDO连接Mysql成功"; }catch(Exception $e){ echo $e->getMessage()."<br>"; } ?>

dsn is a data source, connection information required for the database.

pdo execute sql statement:

exec()方法
exec 方法返回执行sql语句后受影响的行数
int PDO::exec(string statement)
参数statement要执行的sql语句

Universal insert, delete and update

<?php
$dbms = 'mysql';
$dbName='db_database';
$user='root'; $pwd='root'; $host='localhost'; $dsn = "$dbms:host=$host; dbname=$dbName"; $query="delete from tb_da where id=2"; // sql语句 try{ $pdo = new PDO($dsn, $user, $pwd); $affCount=$pdo -> exec($query); echo "删除条数".$affCount; }catch(Exception $e){ echo "".$e->getMessage()."<br>"; } ?>

query () method

query () method is commonly used query returns a result set after execution

PDOStatement PDO::query(string statement)
<table width="200" border="0" bgcolor="#FF3377"> <tr> <td></td> </tr> </table> <?php $dbms = 'mysql'; $dbName='db_database'; $user='root' $pwd='root'; $dsn="$dbms:host=$host; dbname=$dbName"; $query = "select * from tb_da"; try{ $pdo = new PDO($dsn, $user, $pwd); $result=$pdo->query($query); // 输出结果集中的数据 foreach($result as $row){ // 输出结果集中的数据 }catch(Exception $e){ echo $e->getMessage()."<br>"; } ?>

Prepared Statements: prepare () and execute ()
PREPARE () method to do query preparations, execute () method to execute a query, bindParam () method to bind a parameter to execute () method

PDOStatement PDO::prepare(string statement [, array driver_options])
bool PDOStatement::execute([array input_parameters])

prepare () and execute () method:

<?php
$dbms = 'mysql';
$host = 'localhost'; $dbName = 'db_da'; $user='root'; $pass='root'; $dsn="$dbms:host=$host;dbname=$dbName"; try{ $pdo=new PDO($dsn, $user, $pass); $query = "select * from tb_mysql"; $result = $pdo->prepare($query); $result->execute(); while($res = $result->fetch(PDO::FETCH_ASSOC)){ }catch(PDOException $e){ die($e->getMessage()."<br/>"); } ?>

php method of obtaining the result set

fetch()方法获取结果集中的下一行数据
fetchAll()方法获取结果集中的所有行
fetchColumn()方法获取结果集中下一行指定的列的值

fetch()方法:参数

mixed PDOStatement::fetch( fetch_style, cursor_orientation, int_cursor_offset)

PDO::FETCH_ASSOC关联数组形式
PDO::FETCH_NUM数字索引数组形式
PDO::FETCH_BOTH两者数组形式都有
PDO::FETCH_OBJ按照对象的形式
PDO::FETCH_BOUND以布尔值的形式返回结果
PDO::FETCH_LAZY 以关联数组,数字索引,和对象三种形式返回

cursor_orientation:PDOStatement对象的一个滚动游标
cursor_offset:游标的偏移量

<?php
$dbms = 'mysql';
$host='localhost';
$dbName='db_database'; $user='root'; $pass='root'; $dsn = "$dbms:host=$host;dbname=$dbName"; try{ $pdo = new PDO($dsn, $user, $pass); $query = "select * from tb_pdo_mysql"; $result = $pdo->prepare($query); $result->execute(); while($res=$result->fetch(PDO::FETCH_ASSOC)){ }catch(PDOException $e){ die( $e->getMessage()."<br/>"); } ?>
<?php
$dbms='mysql'; // 数据库类型,对于开发者来说,使用不同的数据库,只要该这个就行
$host='localhost'; $dbName='db_database'; $user = 'root'; $pass = 'root'; $dsn = "$dbms:host=$host; dbname=$dbName"; try{ $pdo = new PDO($dsn,$user,$pass); $query = "select * from tb_pdo_mysql"; $result=$pdo->prepare($query); $result->execute(); while($res=$result->fetch(PDO::FETCH_ASSOC){ }catch(PDOException $e){ die( $e -> getMessage() ); } ?>

fetchAll()方法获取结果集中的所有行

array PDOStatement::fetchAll();
参数fetch_style:控制结果集中数据的返回方式
参数column_index:字段的索引
返回的是包含结果集中所有数据的二维数组
<?php
$dbms = 'mysql';
$host = 'localhost';
$dbName = 'db_database'; $user = 'root'; $pass = 'root'; $dsn = "$dbmms:host=$host; dbname = $dbName"; try{ $pdo = new PDO($dsn, $user, $pass); $query = "select * from tb_pdo_mysql"; $result=$pdo -> prepare($query); $result->execute(); $res=$result->fetchAll(PDO::FETCH_ASSOC); for($i=0;$i<count($res);$i++){ ?> <tr> <td height="22" align="center" valign="middle"><?php echo $res[$i]['id'];?></td> <td align="center" valign="middle"><?php echo $res[$i]['pdo_type'];?</td> </tr> <?php } }catch(PDOException $e){ die("Error!:".$e->getMessage()."<br/>"); } ?>

fetchColumn()方法

获取结果集中下一行指定列的值:

string PDOStatement::fetchColumn()

参数column_number设置行中列到的索引值,该值从0开始,省略该参数将从第1列开始取值。

<?php
$dbms = 'mysql';
$host = 'localhost';
$dbName = 'db_database'; $user = 'root'; $pass = 'root'; $dsn = "$dbms:host=$host;dbname=$dbName"; try{ $pdo = new PDO($dsn, $user, $pass); $query = " select * from tb_pdo_mysql"; $result = $pdo -> prepare($query); // 准备查询语句 $result -> execute(); // 执行查询语句 ?> <tr> <td><?php echo $result->fetchColumn(0);?></td> <td><?php echo $result->fetchColumn(0);?></td> <td><?php echo $result->fetchColumn(0);?></td> <td><?php echo $result->fetchColumn(0);?></td> </tr> <?php }catch(PDOException $e) { die("Error!:".$e->getMessae()."<br/>"); } ?>

pdo中捕获sql语句中的错误

使用默认模式
PDO::ERRMODE_SILENT
pdo::errmode_silent

使用警告模式
PDO::ERROMODE_WARNING
pdo::erromode_warning

使用异常模式
PDO::ERRMODE_EXCEPTION
pdo::errmode_exception

// pdo连接数据库mysql,通过预处理prepare()和execute()方法执行insert添加操作
<?php
if($_POST['Submit']=="提交"&&$_POST['pdo']!=""){ $dbms = 'mysql';// 数据库类型 $host = 'localhost'; // 数据库主机名 $dbName = 'db_database'; // 使用的数据库 $user = 'root'; // 数据库的连接用户名 $pass = 'root'; // 对应的密码 $dsn = "$dbms:host=$host; dbname=$dbName"; $pdo = new PDO($dsn, $user, $pass); $query = "insert into tb_pdo_mysql(pdo_type, database_name,dates) values ("", $_POST['pdo'].", ".$_POST['databases'].",".$_POST['dates'].")"; $result = $pdo->prepare($query); $result -> execute(); $code = $result->errorCode(); if(empty($code)){ echo "数据添加成功!"' }else{ echo "数据添加错误:<br/>"; echo 'sql query:'.$query; echo '<pre>'; var dump($result->errorInfo()); echo '</pre>'; }} ?>
// 设置警告模式,通过prepare()和execute()方法读取数据库中数据
// setAttribute()方法设置为警告模式
<?php
$dbms = 'mysql'; // 数据库类型
$host = 'localhost'; // 数据库主机名 $dbName = 'db_database'; // 数据库连接用户名 $user = 'root'; $pass = 'root'; $dsn="$dbms:host=$host; dbname=$dbName"; try{ $pdo = new PDO($dsn, $user, $pass); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); // 设置为警告模式 $query = "select * from tb_pdo_mysqls"; // 定义sql语句 $result = $pdo -> prepare($query); // 准备查询语句 $result->execute(); // 执行查询语句,并返回结果集 while($res=$result->fetch(PDO::FETCH_ASSOC)){ ?> <tr> <td><?php echo $res['id'];?></td> <td><?php echo $res['date'];?></td> </tr> <?php } }catch(PDOException $e){ die("Error!:".$e->getMessage()."<br/>"); } ?>
// 异常模式
<?php
heder("Content-type: text/html; charset="utf-8"); // 设置文件编码格式
if($_GET['conn_id']!=""){
 $dbms = 'mysql';//数据库类型  $host = 'localhost';  $dbName='db_database';  $user='root';  $pass='root';  $dsn = "$dbms:host=$host; dbname=$dbName"; try {  $pdo = new PDO($dsn, $user, $pass);  $pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);  $query="delete from tb_pdo_mysqls where Id=:id";  $result = $pdo->prepare($query); // 预准备语句  $result = bindParam(':id', $_GET['conn_id']); // 绑定更新的数据  $result -> execute(); }catch(PDOException $e) { echo 'PDO Exception Caught.'; echo 'Error with the database:<br/>'; echo 'SQL Query:'.$query; echo '<pre>'; echo "Erro:".$e->getMessage()."<br/>"; echo "File:".$e->getCode()."<br/>"; echo "Line:".$e->getFile()."<br/>"; echo "Trace:".$e->getTranceAsString()."<br/>"; echo '</pre>'; }} ?>

pdo中错误处理:
errorCode()方法和errorInfo()方法

errorCode () method for obtaining an error code when the operating handle is a database occurred.

int PDOStatement::errorCode(void)

errorCode () method returns a sqlstate code.

<?php
$dbms='mysql'; // 数据库类型
$host='localhost'; // 数据库主机名 $dbName = 'db_database'; // 使用的数据库 $user = 'root'; // 数据库连接用户名 $pass = 'root' 对应的密码 $dsn = "dbms:host = $host; dbname = $dbName"; try{ $pdo = new PDO($dsn, $user, $pass); $query = "select * from tb_pdo_mysqls"; // 定义sql语句 $result = $pdo -> query($query); // 执行查询语句,并返回结果集 echo "errorCode为: ".$pdo->errorCode(); foreach($result as $items){ ?> <tr> <td><?php echo $items['id'];?></td> </tr> <?php } }catch(PDOException $e){ die("Error!:" . $e->getMessage()."<br/>"); } ?>

the errorInfo () method for error occurs when the information acquiring operation database handle.

array PDOStatement::errorInfo(void)
<?php
$dbms = 'mysql';
$host = 'localhost';
$dbName = 'db_database'; $user = 'root'; $pass = 'root'; $dsn = "$dbms:host=$host; dbname=$dbName"; try{ $pdo = new PDO($dsn, $user, $pass); // 初始化一个pdo对象,创建数据库连接对象$pdo $query = "select * from tb_pdo_mysqls"; // 定义sql语句 $result = $pdo -> query($query); // 执行查询语句 print_r($pdo->errorInfo()); foreach($result as $items){ ?> <tr> <td><?php echo $items['id'];?></td> <td><?php echo $items['pdo_type'];?></td> </tr> <?php } }catch(PDOException $e){ die("Error!:".$e->getMessage()."<br/>"); } ?>

pdo in the transaction:

Open transaction: beginTransaction () method
beginTransaction () method will close automatically submit autocommit mode, only to resume until after the transaction is committed or rolled back

Commit the transaction: commit () method
to submit commit () method to complete the transaction operation, returns true if successful, false otherwise

Rollback transaction: rollBack () method of
the prepare and execute () method to add data to the database, and by transaction mechanisms ensure that data can be correctly added to the database

Open transaction beginTransaction () method
by $ _POST [] The method of obtaining the data submitted in the form of
added data via prepare () and execute () method to the database
commit operation to complete the transaction by the commit () method
rollBack () method of executing a transaction rollback

<?php
if($_POST['Submit']=="提交" && $_POST['pdo']!=""){  $dbms = 'mysql'; //数据库类型  $host = 'localhost'; // 数据库主机名  $dbName = 'db_database''; // 数据库  $user='root';  $pass='root';  $dsn = "$dbms:host=$host; dbname=$dbName"; try{  $pdo=new PDO($dsn, $user, $pass);  $pdo -> beginTransaction(); // 开启事务  $query="insert into tb_pdo_mysql(pdo_type, database_name, dates) values ("", $_POST['pdo'].",".$_POST['databases'].",".$_POST['dates'].")";  $result = $pdo->prepare($query);  if($result->execute()){ echo "数据添加成功"; }else{ echo "数据添加失败"; }  $pdo->commit(); // 执行事务的提交操作 }catch(PDOException $e){ die("Error!:".$e->getMessage()."<br/>");  $pdo->rollBack(); } } ?>

pdo stored procedure

pdo call a stored procedure:

drop procedure if exists pro_reg; delimiter // create procedure pro_reg(in nc varchar(80), in pwd varchar(80), in email varchar(80), in address varchar(50)) begin insert into ... end; // 

Register: Nickname, registration password, e-mail, home address.

<title>用户注册</title>
<form name="form1" method="post" action="index.php" onsubmit="return chkinput(this)"> </form> <?php if($_POST['submit']!=""){ $dbms='mysql'; //数据库类型 $host='localhost'; //数据库主机名 $dbName='db_database'; //使用的数据库 $user='root'; //数据库连接用户名 $pass='root'; //对应的密码 $dsn="$dbms:host=$host;dbname=$dbName"; try { $pdo = new PDO($dsn, $user, $pass); //初始化一个PDO对象 $pdo->query("set names utf8"); //设置数据库编码格式 $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); $nc=$_POST['nc']; $pwd=md5($_POST['pwd']); $email=$_POST['email']; $address=$_POST['address']; $query="call pro_reg('$nc','$pwd','$email','$address')";//call调用存储过程 $result=$pdo->prepare($query); if($result->execute()){ echo "数据添加成功!"; }else{ echo "数据添加失败!"; } } catch (PDOException $e) { echo 'PDO Exception Caught.'; echo 'Error with the database:<br/>'; echo 'SQL Query: '.$query; echo '<pre>'; echo "Error: " . $e->getMessage(). "<br/>"; echo "Code: " . $e->getCode(). "<br/>"; echo "File: " . $e->getFile(). "<br/>"; echo "Line: " . $e->getLine(). "<br/>"; echo "Trace: " . $e->getTraceAsString(). "<br/>"; echo '</pre>'; } } ?> <script language="javascript"> function chkinput(form){ if(form.nc.value==""){ alert("请输入用户昵称!"); form.nc.select(); return(false); } if(form.pwd.value==""){ alert("请输入注册密码!"); form.pwd.select(); return(false); } if(form.email.value==""){ alert("请输入E-mail地址!"); form.email.select(); return(false); } if(form.address.value==""){ alert("请输入家庭地址!"); form.address.select(); return(false); } return(true); } </script>
<?php 
    header("Content-Type:text/html;charset=utf-8");
    $dbms='mysql';
    $dbName='db_database'; $user='root'; $pwd='root'; $host='localhost'; $dsn="$dbms:host=$host;dbname=$dbName"; ?> <form action="" method="post"> <div> <span>PDO插入数据</span><br> 用户名:<input class="one" type="text" name="text" ><br> 密&nbsp;&nbsp;码:<input class="one"type="password" name="pwd"><br> <input class="two" type="submit" name="sub" value="确定"> <input class="two" type="reset" name="res" value="重置"> <?php if(isset($_POST[sub])){ if($_POST[text]==""&&$_POST[pwd]==""){ echo "文本框内容不能为空"; }else{ try { $pdo=new PDO($dsn,$user,$pwd); $sql="insert into tb_pdo values('','$_POST[text]','$_POST[pwd]',now())"; $result=$pdo->exec($sql); echo "插入数据成功,影响条数为".$result; } catch (Exception $e) { echo "ERROR!!".$e->getMessage()."<br>"; } } } ?> </div> </form> 
<form action=''method="post"> <?php } if(isset($_GET[id])){ $sql1="select * from tb_pdo where id='$_GET[id]'"; $resul=$pdo->query($sql1); foreach ($resul as $value){ ?> <tr> <td class="one"><input readonly type='text' name='id' value='<?php echo $value[id];?>'></td> <td class="one"><input type='text' name='user' value='<?php echo $value[1];?>'></td> <td class="one"><input type='password' name='pwd' value='<?php echo $value[2];?>'></td> <td class="one"><input type='text' name='date' value='<?php echo $value[3];?>'></td> <td class="one"><input class="two" type='submit' name='sub1' value='确定'></td> </tr> <?php } } ?> </form> <?php if($_POST[sub1]=="确定"){ $sql2="update tb_pdo set username='$_POST[user]',userpwd='$_POST[pwd]',date='$_POST[date]' where id='$_POST[id]'"; $resu=$pdo->exec($sql2); if($resu==1){ echo "<script>alert('更新数据成功');window.location.href='index.php'</script>"; } } } catch (Exception $e) { echo "ERROR!!!".$e->getMessage()."<br>"; } ?>

 

Guess you like

Origin www.cnblogs.com/daofaziran/p/11571876.html