php PDO预处理

PDO预处理操作数据库,直接上代码

<?php
try{
    $pdo = new PDO("mysql:host=localhost;dbname=test","root","");    
}catch(PDOException $e){
    echo $e->getMessage();    
}
$pdo->query("set names utf8");

/*查找数据*/
$result = $pdo->query("select * from article");
while($row = $result->fetch()){
    echo $row['article_title'].'<br />';    
}
/*插入数据 插入与更新类似*/
$stmt = $pdo->prepare("insert into article(article_class_id,article_title) values(?,?)");
//$stmt = $pdo->prepare("insert into article(article_class_id,article_title) values(:class_id,title)");
$stmt->bindParam(1,$article_class_id);
$stmt->bindParam(2,$article_title);
//$stmt->bindParam(":class_id",$article_class_id);
//$stmt->bindParam(":title",$article_title);
$article_class_id = 100;
$article_title = "测试title";
if($stmt->execute()){
    echo '插入成功';
    echo $pdo->lastInsertId();
}else{
    echo '插入失败';    
}
?>
If the copyright belongs to the longfei, please indicate the source!!!
原文地址:https://www.cnblogs.com/longfeiPHP/p/5407262.html