一、mysqli方式连接数据库
$mysql_conf = array( ‘host‘ => ‘localhost:3306‘, ‘db‘ => ‘ssql‘, ‘db_user‘ => ‘root‘, ‘db_pwd‘ => ‘‘, ); $mysqli = mysqli_connect($mysql_conf[‘host‘], $mysql_conf[‘db_user‘], $mysql_conf[‘db_pwd‘]); if ($mysqli->connect_errno) { die("could not connect to the database:\n" . $mysqli->connect_error);//诊断连接错误 } $mysqli->query("set names ‘utf8‘;");//编码转化 $select_db = $mysqli->select_db($mysql_conf[‘db‘]); if (!$select_db) { die("could not connect to the db:\n" . $mysqli->error); } $sql = "select * from users where name = ‘lisi‘;"; $res = $mysqli->query($sql); if (!$res) { die("sql error:\n" . $mysqli->error); } while ($row = $res->fetch_assoc()) { var_dump($row); } $res->free(); $mysqli->close();
二、PDO方式连接数据库
$mysql_conf = array( ‘host‘ => ‘localhost:3306‘, ‘db‘ => ‘ssql‘, ‘db_user‘ => ‘root‘, ‘db_pwd‘ => ‘‘, ); $pdo = new PDO("mysql:host=" . $mysql_conf[‘host‘] . ";dbname=" . $mysql_conf[‘db‘], $mysql_conf[‘db_user‘], $mysql_conf[‘db_pwd‘]);//创建一个pdo对象 $pdo->exec("set names ‘utf8‘"); $sql = "select * from user where name = ?"; $stmt = $pdo->prepare($sql); $stmt->bindValue(1, ‘joshua‘, PDO::PARAM_STR); $rs = $stmt->execute(); if ($rs) { // PDO::FETCH_ASSOC 关联数组形式 // PDO::FETCH_NUM 数字索引数组形式 while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { var_dump($row); } } $pdo = null;//关闭连接
原文:https://www.cnblogs.com/wawjandcsws/p/10419453.html