<?php define('DB_DATABASE', 'name_db'); define('DB_USERNAME', 'dbuser'); define('DB_PASSWORD', 'xxxx'); define('PDO_DSN', 'mysql:dbhost=localhost;dbname=' . DB_DATABASE); try { $db = new PDO(PDO_DSN, DB_USERNAME, DB_PASSWORD); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // $stmt = $db->prepare("select score from users where score > ?"); // $stmt->execute([60]); //$stmt = $db->prepare("select name from users where name like ?"); //$stmt->execute(['%t%']); $stmt = $db->prepare("select score from users order by score desc limit ?"); $stmt->bindValue(1, 1, PDO::PARAM_INT); $stmt->execute(); $users = $stmt->fetchAll(PDO::FETCH_ASSOC); foreach($users as $user){ var_dump($user); } echo $stmt->rowCount() . "records found."; /* (1) exec(): 結果を返さない、安全なsql (2) query(): 結果を返す、安全、何回も実行されない (3) prepare(): 結果を返す、安全対策が必要、複数回実行 */ // $stmt = $db->prepare("insert into users(name, score) values(?, ?)"); // $stmt->execute(['tagu', 44]); // $stmt = $db->prepare("insert into users(name, score) values(:name, :score)"); // $stmt->execute(['name'=>'nishikawa', ':score'=>76]); // echo "inserted: " . $db->lastInsertId(); // bindValue 値をbind // bindParam 変数への参照をbindValue // $stmt = $db->prepare("insert into users(name, score) values(?, ?)"); // $name = 'tagu'; // $stmt->bindValue(1, $name, PDO::PARAM_STR); // $score= 23; // $stmt->bindValue(2, $score, PDO::PARAM_INT); // $stmt->execute(); // $score= 44; // $stmt->bindValue(2, $score, PDO::PARAM_INT); // $stmt->execute(); //$stmt->bindParam(2, $score, PDO::PARAM_INT); // $score = 52; // $stmt->execute(); // $score = 44; // $stmt->execute(); // $score = 2; // $stmt->execute(); } catch (PDOException $e){ echo $e->getMessage(); exit; }