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,以及字符集) 注意:如果
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' ) )
注意:如果不设置字符集,即使数据库已经设置了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{ // 插入失败 }