Use of the PHP PDO

Source: Internet
Author: User

PDO Mode Connection Database

try{        $db = new PDO(‘mysql:host=127.0.0.1;dbname=test;port=3306;charset=utf8‘,‘root‘,‘123456‘);}catch(PDOException $e){        echo ‘mysql error: ‘.$e->getMessage();}

1.EXCU () mode additions and deletions, not recommended

$sql = "insert into test (username,password) values (‘liming‘,123456)";$res = $db->excu($sql);echo $res //返回受影响的行数 1

2.PDOStatement class, add and delete changes (recommended in this way, fast, can prevent SQL injection)
Mode 1-Recommended

$sql = "insert into test (username,password) values (:name,:password)";$data = [‘:name‘=>‘liming‘,‘:password‘=>123456];$stmt = $db->prepare($sql);$res  = $stmt->execute($data);echo $res //返回受影响的行数 1

Mode 2, adding and deleting the same

$name=‘maoxiaoming‘;//要插入的数据一定要先用变量定义,不然会报错$password= md5(123456);$sql = $sql = "insert into test (username,password) values (:name,:password)";$stmt = $db->prepare($sql);$stmt->bindParam(‘:name‘,$name);$stmt->bindParam(‘:password‘,$password);$res = $stmt->execute();echo $res //返回受影响的行数 1

3.PDOStatement class query all data

$sql  = "select * from user";$stmt = $db->prepare($sql);$stmt->execute();$res = $stmt->fetchAll(PDO::FATCH_ASSOC);

Query A

$sql = "select * from user where id=:id";$data = [‘:id‘=>3];$stmt = $db->prepare($sql);$stmt->execute($data);echo ‘<pre>‘;print_r($stmt->fetch(PDO::FETCH_ASSOC));

Use of the PHP PDO

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.