PDO预处理之参数绑定与列绑定小结

原创 2019-01-08 10:04:42 318
摘要: $type = 'mysql'; $host = '127.0.0.1'; //windows: 127.0.0.1 $dbName = 'crm'; $charset = 'utf8'; $port = 3306
$type = 'mysql';
$host = '127.0.0.1'; //windows: 127.0.0.1
$dbName = 'crm';
$charset = 'utf8';
$port = 3306;  //可选,默认为3306

// dsn = mysql:host=localhost;dbname=userDB;charset=utf8;
$dsn = $type.':host='.$host.';dbname='.$dbName.';charset='.$charset.';port='.$port;

$user = 'root';
$pass = 'root123';

try {
$pdo = new PDO($dsn, $user, $pass);


//sql语句
$sql = "SELECT `id`,`uname`,`create_time` FROM `tp_admin` WHERE `status` = :status ;";

//验证sql语句并生成预处理对象
$stmt = $pdo->prepare($sql);

//$status = 1;
//$stmt->bindParam(':status',$status, PDO::PARAM_INT);

//2.bindValue():
//$stmt->bindValue(':status',$status, PDO::PARAM_INT);
//$stmt->bindValue(':status',1);
//执行
$stmt->execute([':status'=>2]);

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

    $rows[] = $row;
}

//释放结果集
$stmt = null;

//关闭连接
$pdo = null;
echo '<pre>';
print_r($rows);
echo '<hr>';
} catch (PDOException $e) {
    exit($e->getMessage());
}

参数绑定到变量

 * 参数绑定到变量或值的三种方式

 * 1. bindParam(':占位符', 变量, 类型常量),类型常量默认为字符串

 * 2. bindValue(':点位符', 值或变量,类型常量),如果直接传值,可省略类型常量

 * 3. execute([':占位符'=>值/变量]): 将参数以数组方式与SQL语句的占位符绑定


批改老师:查无此人批改时间:2019-01-08 10:21:33
老师总结:做的不错,多熟悉数据库查询,php的作用,就是对数据处理。加油

发布手记

热门词条