- 不使用参数绑定:
<?php
try {
$pdo = new PDO('mysql:host=localhost;dbname=laravel;charset:utf8', 'root', 'root');
$pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'database established successfully!' . '<br>';
$sql1 = 'insert into colors set en = "asdf", zh_cn = "qwer"';
$affectRows = $pdo -> exec($sql1);
echo "successfully affect ${affectRows} line(s)" . '<br>';
$sql2 = 'select * from colors;';
$result = $pdo->query($sql2);
$result_array = $result -> fetchAll();
$count = count($result_array);
echo "total ${count} rows " . PHP_EOL;
foreach ($result_array as $item)
print_r($item);
} catch (PDOException $e) {
echo $e -> getMessage();
}
- 使用参数绑定:
<?php
try {
$pdo = new PDO('mysql:host=localhost;dbname=laravel;charset:utf8', 'root', 'root');
$pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'database established successfully!' . PHP_EOL;
$sql1 = 'insert into colors set en = :en, zh_cn = :zh_cn';
$stmt1 = $pdo -> prepare($sql1);
$stmt1 -> execute(['en' => 'zzz', 'zh_cn' => 'aaa']);
$insert_rows = $stmt1 -> rowCount();
echo $insert_rows . ' rows are created.' . PHP_EOL;
$sql2 = "delete from colors where id >= :id";
$stmt2 = $pdo->prepare($sql2);
$stmt2 -> execute(['id' => 20]);
$deleted_rows = $stmt2 -> rowCount();
echo $deleted_rows . ' rows are deleted.' . PHP_EOL;
$sql3 = "select * from colors where id < :id";
$stmt3 = $pdo->prepare($sql3);
$stmt3 -> execute(['id' => 3]);
$queried_rows = $stmt3 -> rowCount();
echo $queried_rows . ' rows are queried.' . PHP_EOL;
foreach ($stmt3 as $row)
print_r($row) . '<br>';
} catch (PDOException $e) {
echo $e -> getMessage();
}
网友评论