php接続MySQLの2つの方法の比較

2382 ワード

PHP接続MySQLの2つの方法を記録します.
まずデータをmockして、sqlを実行することができます.

/*     */
CREATE DATABASE IF NOT EXISTS `test`;
/*     */
USE `test`;
/*   */
CREATE TABLE IF NOT EXISTS `user` (
  name varchar(50),
  age int
);
/*      */
INSERT INTO `user` (name, age) VALUES('harry', 20), ('tony', 23), ('harry', 24);


1つ目はPHPオリジナル方式でデータベースに接続することです.コードは次のとおりです.

" . mysql_error());//      
}
$selectedDb = mysql_select_db($database);//     
if (!$selectedDb) {
  die("could not to the database
" . mysql_error()); } $selectName = mysql_real_escape_string($selectName);// SQL $query = "select * from user where name = '$selectName'";// $result = mysql_query($query);// if (!$result) { die("could not to the database
" . mysql_error()); } while ($row = mysql_fetch_row($result)) { // $name = $row[0]; $age = $row[1]; echo "Name: $name "; echo "Age: $age "; echo "
"; }

以下のように動作します.
Name:harry Age:20 Name:tony Age:23 2つ目はPDOを使用してデータベースに接続することです.コードは次のとおりです.

exec("set names 'utf8'");
$sql = "select * from user where name = ?";
$stmt = $pdo->prepare($sql);
$rs = $stmt->execute(array($selectName));
if ($rs) {
  // PDO::FETCH_ASSOC       
  // PDO::FETCH_NUM         
  while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $name = $row['name'];
    $age = $row['age'];
    echo "Name: $name ";
    echo "Age: $age ";
    echo "
"; } } $pdo = null;//

その結果は第1種と同じであった.
以上が本文のすべてですが、mysqlをマスターするのに役立つことを願っています.