PHP Data Access
1. Making Connection objects
$db = new Mysqli ("localhost", "root", "123", "test_123");
2. Write SQL statements
$sql = "SELECT * from student";
3. Execute SQL statement, return result set object
$result = $db->query ($sql);
if ($result->num_rows)
{
}
$arr = $result->fetch_row ();
Var_dump ($arr);
Data collection (5 methods)
(1). $arr = $result->fetch_all (mysqli_both);; (Common)
Var_dump ($arr);
//default output Index array (two-dimensional array), Mysqli_num output index array; mysqli_assoc output associative array; mysqli_ Both output index and associative array;
(2). $arr = $result->fetch_array (); // Returns the first data (index and associative array) by default
If all data is output, a while () loop is used:
while ($arr = $result->fetch_array ())
{
Var_dump ($arr);
}
(3). $arr = $result->fetch_assoc (); //Return First data by default, return associative array
Var_dump ($arr);
(4). $arr = $result->fetch_object (); //Returns the first data by default, returns the object
Var_dump ($arr);
(5). $arr = $result->fetch_row (); //Returns the first data by default, returning an indexed array (Common)
Var_dump ($arr);
If you execute the Delete and modify statement, return ture successfully, the failure returns false
Examples
I. Drop-down list read data
Method 1:
<?php
echo "<select>";
$db = new Mysqli ("localhost", "root", "123", "test_123");
$sql = "SELECT * from teacher";
$result = $db->query ($sql);
$arr = $result->fetch_all (); //Returns a two-dimensional array
foreach ($arr as $v)
{
echo "<option value= ' {$v [0]} ' >{$v [1]}</option>";
}
echo "</select>";
?>
Method 2:
<body>
<select>
<option> Please select </option>
<?php
$db = new Mysqli ("localhost", "root", "123", "test_123");
$sql = "SELECT * from student";
$result = $db->query ($sql);
while ($arr = $result->fetch_row ()) //Returns a one-dimensional array
{
echo "<option value= ' {$arr [0]} ' >{$arr [1]}</option>";
}
?>
</select>
</body>
two. read data in tables <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 Data Access