Home >Backend Development >PHP Tutorial >Simple how to use PDO in PHP5.2, how to use php5.2pdo_PHP tutorial
The example in this article describes the simple way to use PDO in PHP5.2. Share it with everyone for your reference, the details are as follows:
1. PDO configuration
1. Make sure the PHP version is 5.2.5 or above
2. Find the Dynamic Extensions extension section in php.ini and remove the semicolon
in front of extension=php_pdo.dll
3. Remove the semicolon in front of the corresponding database PDO extension, such as: extension=php_pdo_mysql.dll
2. Database in the example
CREATE TABLE tablename ( id mediumint(8) UNSIGNED NOT NULL AUTO_INCREMENT, str varchar(50) NOT NULL DEFAULT '''', PRIMARY KEY (id) );
3. Program Example
<?php $dsn = "mysql:host=localhost;dbname=test"; $user = ''root''; $passwd = ''123456''; try{ $db = new PDO($dsn, $user, $passwd); }catch (PDOException $e) { echo "链接数据库失败!"; print "异常信息: ". $e->getMessage() . "<br/>"; print "异常文件: " . $e->getFile() . "<br/>"; print "异常行号: " . $e->getLine() . "<br/>"; exit(); } //$sql = "INSERT INTO tablename SET str = ''Hello''"; //$count = $db->exec($sql); //返回值为影响的行数 //$sql = "DELETE FROM tablename WHERE str = ''Hello'' LIMIT 1"; //$count = $db->exec($sql); //返回值为影响的行数 //预处理需要查询的SQL语句 //$db->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL); //列名按照原始的方式(字段) $sql = "SELECT * FROM tablename WHERE id < :id AND str = :string"; //sql语句(参数绑定方式) $query = $db->prepare($sql); //预处理 //用一组绑定参数执行一遍查询 $query->execute(array('':id''=>1, '':string''=>''Hello'')); //处理语句(参数绑定方式) //$query->setFetchMode(PDO::FETCH_ASSOC); 关联数组形式(只通过字段名下标访问数组内容) while($item = $query->fetch(PDO::FETCH_ASSOC)) //循环获取数据 { echo $item[''id''].":".$item[''str'']."<br/>"; //print_r ($item); } //用另一组绑定参数,再执行一遍查询 $query->execute(array('':id''<=10, '':string''=>''HelloWorld'')); //处理语句(参数绑定方式) //$query->setFetchMode(PDO::FETCH_ASSOC); 关联数组形式(只通过字段名下标访问数组内容) while($item = $query->fetch(PDO::FETCH_ASSOC)) //循环获取数据 { echo $item[''id''].":".$item[''str'']."<br/>"; //print_r ($item); } $db = null; //释放数据库链接 ?>
Readers who are interested in more PHP-related content can check out the special topics of this site: "Summary of PHP office document operation skills (including word, excel, access, ppt)", "Summary of PHP date and time usage", "php-oriented "Introduction Tutorial on Object Programming", "Summary of PHP String Usage", "Introduction Tutorial on PHP MySQL Database Operation" and "Summary of Common PHP Database Operation Skills"
I hope this article will be helpful to everyone in PHP programming.