【PHP PDO】純PHP(不使用架構)下 Mysql PDO 使用方法小記

來源:互聯網
上載者:User

標籤:

1 配置資訊

$config = array('db'=> array('host'=> '127.0.0.1','user'=> 'root','pass'=> '','db'=> 'test_db','dns'       => 'mysql:dbname=test_db;host=127.0.0.1;charset=utf8'))

分別設定資料庫連結,使用者名稱,密碼,庫,dns資訊(包括資料庫名,資料庫連結ip,以及字元集)

注意:如果不設定字元集,即使資料庫已經設定了utf8,存入資料庫的中文資料仍可能為亂碼(需要保持代碼、資料庫設定、連結資料庫時的字元集都保持為utf8)


2 連結資料庫

try {    $db = new PDO($config['db']['dns'], $config['db']['user'], $config['db']['pass']);} catch (PDOException $e) {    echo 'Connection failed: ' . $e->getMessage();exit;}

3.1 查詢

// 查詢  $sql1 = "SELECT * FROM tbl_test1 WHERE condition1 = :condition1 and condition2 = :condition2";  $sql_data1 = Array(  ":condition1" => 1,  ":condition2" => "abc"  );  $sth1 = $db->prepare($sql1);  $sth1->execute($sql_data1); // 擷取一條  $result1 = $sth1->fetch(PDO::FETCH_ASSOC);  // 擷取所有  // $result1 = $sth1->fetchAll(PDO::FETCH_ASSOC);    // 判斷是否成功  if($result1){  // 查詢成功  }else{  // 查詢失敗  }

3.2 更新

// 更新  $sql2 = "UPDATE tbl_test1 SET `key1` = :val1, `key2` = :val2 WHERE  condition1 = :condition1 and condition2 = :condition2";  $sql_data2 = Array(  ":val1" => 1,  ":val2" => "hello",  ":condition1" => 1,  ":condition2" => "abc"  );  $sth2 = $db->prepare($sql2);  $sth2->execute($sql_data2);    // 判斷是否成功  if($sth2->rowCount() >0){  // 更新成功  }else{  // 更新失敗  }  

3.3 插入

// 插入  $sql3 = "INSERT INTO tbl_test1 (`key1`,`key2`,`key3`,`key4`,`key5`) VALUES ( :val1 , :val2 , :val3 , :val4 , :val5 )";  $sql_data3 = Array(  "val1" => 1,  "val2" => "hello",  "val3" => 100.25,  "val4" => "隨便寫寫"  "val5" => "2015-10-30"  );  $sth3 = $db->prepare($sql3);  $result3 = $sth3->execute($sql_data3);    // 判斷是否成功  if($result3){  // 插入成功  // 最新插入的資料的自增長id  // $db->lastInsertId();  }else{  // 插入失敗  }  


【PHP PDO】純PHP(不使用架構)下 Mysql PDO 使用方法小記

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.