Blogger Information
Blog 2
fans 1
comment 0
visits 4170
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PDO操作数据库的基本步骤
杨敏的博客
Original
1612 people have browsed it

1、连接数据库

return[
    'type' => 'mysql',
    'host' => '127.0.0.1',
    'port' => '3306',
    'dbname' => 'student',
    'username' => 'root',
    'passwd' => 'root'
];
$db = require 'database.php';

$dns = "{$db['type']}:host={$db['host']};port={$db['port']};dbname={$db['dbname']}";

try {
    $pdo = new PDO($dns, $db['username'], $db['passwd']);
} catch (PDOException $e) {
    die("Error!: " . $e->getMessage() . "<br/>");
}
require 'inc/connect.php';

2、 创建sql语句模板

$sql = 'INSERT INTO `user` SET `name` = :name, `abbreviations` = :abbreviations';

3、 创建sql语句对象(预处理对象)

$stmt = $pdo->prepare($sql);

4、 将变量绑定给sql语句模板上

$name = '赵六';
$abbreviations = 'zl';
$stmt->bindParam('name', $name, PDO::PARAM_STR);
$stmt->bindParam('abbreviations', $abbreviations, PDO::PARAM_STR);

5、执行SQL语句

if ($stmt->execute()) {
    if ($stmt->rowCount() > 0) {  //返回受影响的记录数
        echo '成功添加了' . $stmt->rowCount() . '记录,主键是:' . $pdo->lastInsertId();

    } else {
        die('<pre>' . print_r($stmt->errorInfo(), true));
    }
}

6、关闭数据库

$pdo = null;



二、修改

<?php
//1、连接数据库
require 'inc/connect.php';


//2、 创建sql语句模板
$sql = 'UPDATE  `user` SET `name` = :name, `abbreviations` = :abbreviations WHERE  `id` = :id';




//3.pdo预处理
$stmt = $pdo->prepare($sql);


//4.将变量绑定给sql语句模板上
$name = '张伟';
$abbreviations='zw';
$id = 2;
$stmt->bindParam('name', $name, PDO::PARAM_STR);
$stmt->bindParam('abbreviations', $abbreviations, PDO::PARAM_STR);
$stmt->bindParam('id', $id, PDO::PARAM_INT);


//5、执行SQL语句
if ($stmt->execute()) {
    echo '成功执行';
} else {
    echo '执行失败';
}


//6、关闭链接
$pdo = null;


三、删除

<?php
//1、连接数据库
require 'inc/connect.php';


//2、 创建sql语句模板

$sql='DELETE FROM `user` WHERE `id` = :id';


//3.pdo预处理
$stmt = $pdo->prepare($sql);


//4.将变量绑定给sql语句模板上
$id = 2;
$stmt->bindParam('id', $id, PDO::PARAM_INT);


//5、执行SQL语句
if ($stmt->execute()) {
    echo '成功执行';
} else {
    echo '执行失败';
}


//6、关闭链接
$pdo = null;


Correction status:Uncorrected

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!