测试用PDO方式进行预处理语句插入数据,发现选定了数据库名,但是不生效的BUG(无效的数据库名),原来是前后有关系,在设定$dsn时,一定要把
dbname=XXX放在第一个参数,即紧挨着$dsn = "mysql:
正确写法:
$dsn = "mysql:dbname=echarts;host=localhost;port:3306;charset=utf8";
<?php
try {
$dsn = "mysql:dbname=echarts;host=localhost;port:3306;charset=utf8";
$username = "root";
$password = "root";
$attr = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
$pdo = new PDO($dsn,$username,$password,$attr);
var_dump($pdo);
$sql = 'insert into prirule(id,info) values(:id,:info)';
$stmt = $pdo->prepare($sql);
$data = [
':id' => 10,
':info' => '大象'
];
$stmt->execute($data);
$rows = $stmt->rowCount();//返回受上一个 SQL 语句影响的行数
if ($rows) {
exit('添加成功');
}else{
exit('添加失败');
}
} catch (PDOException $e) {
echo $e->getMessage();
}