php数据访问(一)
php数据访问
1.造连接对象
$db = new MySQLi("localhost","root","123","test_123"); //("本地主机名","用户名","密码","数据库名")
2.写SQL语句
$sql="select * from student";
3.执行SQL语句,返回结果集对象
$result = $db->query($sql);
if($result->num_rows)
{
}
$arr = $result->fetch_row();
var_dump($arr);
取数据(5种方法)
(1). $arr=$result->fetch_all(MYSQLI_BOTH);;(常用)
var_dump($arr);
//默认输出索引数组(二维数组),MYSQLI_NUM输出索引数组; MYSQLI_ASSOC输出关联数组;MYSQLI_BOTH输出索引和关联数组;
(2). $arr=$result->fetch_array(); //默认返回第一条数据(索引和关联数组)
//如果输出全部数据,则采用while()循环:
while($arr=$result->fetch_array())
{
var_dump($arr);
}
(3). $arr=$result->fetch_assoc(); //默认返回第一条数据,返回关联数组
var_dump($arr);
(4). $arr=$result->fetch_object(); //默认返回第一条数据,返回对象
var_dump($arr);
(5). $arr=$result->fetch_row(); //默认返回第一条数据,返回索引数组(常用)
var_dump($arr);
如果执行增删改语句,成功返回ture,失败返回false
例题
一.下拉列表读数据
方法1:
<?php
echo "<select>";
$db = new MySQLi("localhost","root","123","test_123");
$sql = "select * from teacher";
$result = $db->query($sql);
$arr = $result->fetch_all(); //返回的是二维数组
foreach($arr as $v)
{
echo "<option value='{$v[0]}'>{$v[1]}</option>";
}
echo "</select>";
?>
方法2:
<body>
<select>
<option>请选择</option>
<?php
$db = new MySQLi("localhost","root","123","test_123");
$sql = "select * from student";
$result = $db->query($sql);
while($arr = $result->fetch_row()) //返回的是一维数组
{
echo "<option value='{$arr[0]}'>{$arr[1]}</option>";
}
?>
</select>
</body>
二.用表格读取数据<body>
<table border="1px" cellpadding="0px" cellspacing="0px">
<?php
$db = new MySQLi("localhost","root","123","test_123");
$sql = "select * from student";
$result = $db->query($sql);
while($arr = $result->fetch_row())
{
echo "<tr>";
foreach($arr as $v)
{
echo "<td>$v</td>";
}
echo "</tr>";
}
?>
</table>
</body>