Data access is divided into three types
1. Use the function to discard the new version
2. Object-oriented approach Mysqli class
The way of 3.PDO
Example
<table width= "100%" border= "1" >
<tr>
<td> Code </td>
<td> name </td>
<td> Sex </td>
<td> ethnic </td>
<td> Birthdays </td>
</tr>
Use the Mysqli class to access the database:
1. The object in Mysqli, which is equivalent to establishing a channel between PHP and MySQL database
$db = new Mysqli ("localhost", "root", "123", "MyDB");
2. Determine if the connection is wrong
if (Mysqli_connect_error ()) {
echo "Connection failed! ";
Exit If the connection goes wrong, end the program directly
}
3. Write SQL statements
$sql = "SELECT * from Info";
4. Execute the prepared SQL statement
$result = $db->query ($sql);
Returns the result set object if a query statement is executed, or true or false if other statements are executed
5. Reading data from the result set object
$arr 1 = $result->fetch_row (); Read one at a time, return an array
You can use the while loop to read all data
while ($arr = $result->fetch_row ()) {
Var_dump ($arr);
}
$arr = $result->fetch_all (); Read all, return two-dimensional array
Var_dump ($arr);
$arr = $result->fetch_assoc (); Reads a bar, returns an associative array
Var_dump ($arr);
$arr = $result->fetch_object (); Reads a bar, returns the object
Var_dump ($arr);
$arr = $result->fetch_all ();
foreach ($arr as $v) {
Dealing with gender
$sex = $v [2]? " Male ":" Female ";
Ethnic processing
$sql = "SELECT name from Nation where code= ' {$v [3]} '";
$re = $db->query ($sql);
$a = $re->fetch_row ();
echo "<tr>
<td>{$v [0]}</td>
<td>{$v [1]}</td>
<td>{$sex}</td>
<td>{$a [0]}</td>
<td>{$v [4]}</td>
</tr> ";
}
Then connect to the new PHP file, as follows
$db = new Mysqli ("localhost", "root", "123", "MyDB");
if (Mysqli_connect_error ()) {
Die ("Connection failed! ");
}
$sql = "INSERT into Xuanxiang values (0, ' 111111 ', ' a ', 1)";
if ($db->query ($sql)) {
echo "added successfully! ";
Echo $db->insert_id; Take the added primary key value
}else{
echo "Add failed! ";
}
Data access, accessing data using the MySQL class