返回PDO预处理与......登陆

PDO预处理与参数绑定

瓶子2018-11-29 11:29:10240
//1、连接数据库,创建pdo对象
$type = 'mysql';//数据库类型
$host = '127.0.0.1';//主机名
$dbname = 'test';//数据库名
$charset = 'utf8';//字符集
//$port = 3306;//端口
$dsn = $type . ':host=' . $host . ';dbname=' . $dbname . ';charset=' . $charset;
$user = 'root';//用户名
$pass = '123456';//密码
try{
    //连接数据库
    $pdo = new \PDO($dsn,$user,$pass);
    //关闭数据库。默认在代码执行完毕后会自动关闭。
//    $pdo = null;
//    unset($pdo);
//    var_dump($pdo);
}catch (PDOException $e){
    exit($e->getMessage());
}
//2、创建预处理对象
$sql = 'select `id`,`name`,`email` from `user` where `id` > :id';
//$stmt 是PDOStatement类的对象
$stmt = $pdo->prepare($sql);
$stmt->setFetchMode(\PDO::FETCH_ASSOC);
//3、执行sql语句
if($stmt->execute([':id' => 2])){
//4、解析结果集
    $res = $stmt->fetchAll(\PDO::FETCH_ASSOC);
}else{
    print_r($stmt->errorInfo());die;
}
//5、遍历结果集
print_r($res);
//获取结果数
$stmt->rowCount();//返回受影响记录数,一般用到写操作中(增、删、改)
//获取所有记录数量
$stmt = $pdo->prepare('select count(id) num from user ');
$stmt->execute();
$num = $stmt->fetchColumn(0);
echo '记录数:'.$num;

//查询结果绑定
$stmt->bindColumn('num',$num);
$stmt->fetch(\PDO::FETCH_BOUND);
echo '记录数:'.$num;






/**
 * 参数绑定     bindParam()     bindValue()
 * 列绑定      bindColumn()
 * 结果集遍历    fetch()     while()
 **/
//1、连接数据库,创建PDO对象
$pdo = new \PDO('mysql:host=127.0.0.1;dbname=test','root','123456');
//2、创建预处理对象
$sql = 'select `id`,`name`,`email`,`create_time` from `user` where `status` = :status';
$stmt = $pdo->prepare($sql);
//3、执行查询
$stmt->execute([':status' => 1]);
//4、遍历结果
while($row = $stmt->fetch(\PDO::FETCH_ASSOC)){
    $arr[] = $row;
}
$stmt = null;//释放结果集
$pdo = null;//
//print_r($arr);

echo <<<EOT
<table class="table table-hover">
    <caption>信息表</caption>
    <tr>
        <td>ID</td>
        <td>NAME</td>
        <td>E-MAIL</td>
        <td>TIME</td>
    </tr>
EOT;
foreach ($arr as $item) {
    $time = date('Y-m-d',$item['create_time']);
echo <<<EOT
    <tr>
        <td>{$item['id']}</td>
        <td>{$item['name']}</td>
        <td>{$item['email']}</td>
        <td>{$time}</td>
    </tr>
EOT;
}
echo <<<EOT
</table>
EOT;





//参数绑定
//1、连接数据库,创建PDO对象
$pdo = new \PDO('mysql:host=127.0.0.1;dbname=test','root','123456');
//2、创建预处理对象
$sql = 'select `id`,`name`,`email`,`create_time` from `user` where `status` = :status';
$stmt = $pdo->prepare($sql);
//3、执行查询
$status = 1;
//$stmt->bindParam(':status',$status,\PDO::FETCH_ASSOC);//只支持参数模式
$stmt->bindValue(':status',1,\PDO::FETCH_ASSOC);//可以支持直接传入字面量
$stmt->execute();
//4、遍历结果
$stmt->bindColumn(1,$id,\PDO::PARAM_INT);
$stmt->bindColumn(2,$name,\PDO::PARAM_STR,200);
$stmt->bindColumn(3,$email,\PDO::PARAM_STR,100);
$stmt->bindColumn(4,$createTime,\PDO::PARAM_STR,100);

while($stmt->fetch(\PDO::FETCH_BOUND)){
//    echo $id,$name,$email,$createTime,'<br>';
    //将变量转为数组
    $arr1[] = compact('id','name','email','createTime');
}
echo '<pre>',print_r($arr1);


最新手记推荐

• 用composer安装thinkphp框架的步骤• 省市区接口说明• 用thinkphp,后台新增栏目• 管理员添加编辑删除• 管理员添加编辑删除

全部回复(0)我要回复

暂无评论~
  • 取消回复发送