pdo方式连接数据库
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()方式增删改,不推荐
$sql = "insert into test (username,password) values ('liming',123456)";
$res = $db->excu($sql);
echo $res //返回受影响的行数 1
2.PDOStatement类,增删改(推荐用这种方式,速度快,可以防止sql注入)
方式1-推荐
$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
方式2,增删改一样
$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类查询所有数据
$sql = "select * from user";
$stmt = $db->prepare($sql);
$stmt->execute();
$res = $stmt->fetchAll(PDO::FATCH_ASSOC);
//查询一条
$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));
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。