赞
踩
1、建立PHP工程
2、分别定义MYSQL数据库的IP地址、用户名、用户密码、数据库名
$servername = “localhost”;
$username = "username ";
$password = "password ";
$dbname = “mysql”;
3、用方法mysqli_connect实例化mysqli
4、用mysqli的query方法查询数据集
5、用数据集的fetch_assoc()方法遍历数据集
<?php $servername = "localhost"; $username = "username "; $password = "password "; $dbname = "mysql"; try { // 对mysqli类进行实例化 $conn = mysqli_connect($servername, $username, $password, $dbname); if (mysqli_connect_errno()) { // 判断是否成功连接上MySQL数据库 throw new Exception('数据库连接错误!'); // 如果连接错误,则抛出异常 } else { echo '数据库连接成功!'; // 打印连接成功的提示 echo "<br>"; } } catch (Exception $e) { // 捕获异常 echo $e->getMessage(); // 打印异常信息 } $sql = "SELECT host, user FROM user"; $result = $conn->query($sql); if ($result->num_rows > 0) { // 输出数据 while ($row = $result->fetch_assoc()) { echo "host: " . $row["host"] . " - user: " . $row["user"]; echo "<br>"; } } else { echo "0 结果"; } $conn->close(); ?>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。