[PHP] 纯文本查看 复制代码 <?php
$host = 'localhost';
$username = 'root';
$password = 'root';
$dbname = 'test';
$mysql = new Mysqli($host, $username, $password, $dbname);
if($mysql -> connect_errno){
die('数据库连接失败:'.$mysql->connect_errno);
}else{
$mysql -> set_charset('UTF-8'); // 设置数据库字符集
$sql = 'select * from user'; // SQL 语句
$result = $mysql -> query($sql);
$data = $result -> fetch_all();
$mysql -> close();
}
echo '<pre>';
print_r($data);
?>
运行结果如下:
Array
(
[0] => Array
(
[0] => 1
[1] => 张三
)
)
【示例】使用 mysqli_select_db() 函数选择默认数据库
1) 面向对象风格的写法:
<?php
$host = 'localhost';
$username = 'root';
$password = 'root';
$dbname = 'test';
$mysql = new Mysqli($host, $username, $password);
if($mysql -> connect_errno){
die('数据库连接失败:'.$mysql->connect_errno);
}else{
$mysql -> select_db($dbname); // 选择名为 test 的数据库
$sql = 'select name,sex,age from user'; // SQL 语句
$result = $mysql -> query($sql); // 执行上面的 SQL 语句
$data = $result -> fetch_all();
$mysql -> close();
}
echo '<pre>';
print_r($data);
?>
|