PDO操作mysql数据库(二)

从 MySQL 数据库读取数据

<?php

$server = "localhost";

$user = "root";

$pwd = "123456";

$db = "mydb";

try{

    $conn = new PDO("mysql:host=$server;dbname=$db",$user,$pwd);

    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $conn->prepare("select * from myfriend");

    $stmt->execute();

    //设置结果集为数组

    $stmt->setFetchMode(PDO::FETCH_ASSOC);

    $result = $stmt->fetchAll();

 

    for ($x=0; $x<count($result); $x++){

        foreach ($result[$x] as $k=>$v){

            echo $k."-->".$v;

            echo "<br>";

        }

    }

}catch (PDOException $exception){

    echo $exception->getMessage();

}

$conn = null;

 

MySQL Where 子句

sql语句:select * from myfriend where `id` = 3;

php语句相同,使用where可以过滤记录。

 

MySQL Order By 关键词

sql语句:select * from myfriend order by `name`;

php语句相同,使用order by关键词可以对结果集进行排序。

 

Update更新数据库中的数据

sql语句:update myfriend set `email` = 'simon@qq.com' WHERE `id` = 1;

php语句相同。

 

Delete删除数据库中的数据

sql语句:delete from myfriend where `id` = 3;

php语句相同。

 

posted @ 2016-09-20 08:58  _Simon  阅读(348)  评论(0编辑  收藏  举报