Blogger Information
Blog 16
fans 0
comment 0
visits 12371
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PDO操作练习-11月21号作业
wenbin0209
Original
835 people have browsed it

实例

PDO链接数据库:
<?php
$db = [
    'type' => 'mysql',
    'host' => 'localhost',
    'dbname' => 'localhost',
    'username' => 'wenbin0209',
    'password' => 'a384309596',
    'port' => 3306
];
$dsn = "{$db['type']}:host={$db['host']};dbname={$db['dbname']}";
try {
    $pdo = new PDO($dsn,$db['username'],$db['password']);
} catch(PDOException $e){
    die('错误信息:'.$e->getMessage());
}
// echo '请求成功';
PDO增删查改操作:
<?php
    // 连接数据库
    require('db.php');
    // ------------增加数据--------------
    // 创建语句模板
    $sql = 'INSERT INTO `ls_addressbook` SET `province`=:province, `tel`=:tel ';
    //创建sql语句
    $stmt =  $pdo->prepare($sql);
    // 预处理语句中进行绑定数据
    $province = '山东';
    $tel = 13964328052;
    $stmt->bindParam('province',$province,PDO::PARAM_STR);
    $stmt->bindParam('tel',$tel,PDO::PARAM_INT);
    // print_r($stmt);
    // PDOStatement类  进行增删查改操作
    $add = $stmt ->execute();
    print_r($add);
    //--------- 删除数据------------
    // 删除指定id的数据
    $sql = 'DELETE from `ls_addressbook` where id = :id';
    // 创建语句
    $stmt = $pdo->prepare($sql);
    $id = 40;
    $stmt ->bindParam('id',$id);
    // 执行删除
    $delete = $stmt ->execute();
    //影响行数
    print_r($stmt->rowCount());
    //-----------查询数据----------
    //查询全部数据
    $sql = 'SELECT * from `ls_addressbook`';
    $stmt = $pdo->prepare($sql);
    $select = $stmt->execute();
    print_r($stmt->fetchAll());
    // 更新数据
    $sql = 'UPDATE `ls_addressbook` set name = :name where id = :id';
    $stmt = $pdo->prepare($sql);
    // 绑定数据
    $name = '老王';
    $id = 42;
    $stmt ->bindParam('name',$name);
    $stmt ->bindParam('id',$id);
    $update = $stmt->execute();
    print_r($update);

运行实例 »

点击 "运行实例" 按钮查看在线实例

手写:

image.png

image.png


Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:数据库的操作, 还是要多多练习
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!