时间:2021-07-01 10:21:17 帮助过:25人阅读
连接MySQLi有两种风格:
面向对象风格(推荐) (推荐学习:PHP视频教程)
<?php $serve = 'localhost:3306'; $username = 'root'; $password = 'admin123'; $dbname = 'examples'; $mysqli = new Mysqli($serve,$username,$password,$dbname); if($mysqli->connect_error){ die('connect error:'.$mysqli->connect_errno); } $mysqli->set_charset('UTF-8'); // 设置数据库字符集 $result = $mysqli->query('select * from customers'); $data = $result->fetch_all(); // 从结果集中获取所有数据 print_r($data); ?>
过程化风格
<?php $serve = 'localhost:3306'; $username = 'root'; $password = 'admin123'; $dbname = 'examples'; $link = mysqli_connect($serve,$username,$password,$dbname); mysqli_set_charset($link,'UTF-8'); // 设置数据库字符集 $result = mysqli_query($link,'select * from customers'); $data = mysqli_fetch_all($result); // 从结果集中获取所有数据 print_r($data); ?>
PDO连接数据库
<?php $serve = 'mysql:host=localhost:3306;dbname=examples;charset=utf8'; $username = 'root'; $password = 'admin123'; try{ // PDO连接数据库若错误则会抛出一个PDOException异常 $PDO = new PDO($serve,$username,$password); $result = $PDO->query('select * from customers'); $data = $result->fetchAll(PDO::FETCH_ASSOC); // PDO::FETCH_ASSOC表示将对应结果集中的每一行作为一个由列名索引的数组返回 print_r($data); } catch (PDOException $error){ echo 'connect failed:'.$error->getMessage(); } ?>
以上就是php7如何连接数据库的详细内容,更多请关注Gxl网其它相关文章!