標籤:ble row bsp mysql log color obj from sel
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>
php資料訪問