Way one: already obsolete
1. Making a connection (establishing a channel)
$db = mysql_connect ("localhost", "root", "123");
2. Select which database to manipulate
mysql_select_db ("MyDB", $db);
3. Write SQL statements
$sql = "SELECT * from Info";
4. Execute the SQL statement and return the result set
$result = mysql_query ($sql);
5. Fetching data from the result set
while ($row = Mysql_fetch_row ($result))
{
Var_dump ($row);
}
Way two: object-oriented approach
1. Create a Connection object
$db = new Mysqli ("localhost", "root", "123", "MyDB");
2. Determine if the connection is wrong
if (Mysqli_connect_error ())
{
echo "Connection Failed";
Exit (); Exit program
}
!mysqli_connect_error () or Die ("Connection failed! ");
3. Write SQL statements
$sql = "SELECT count (*) from Info";
$sql = "INSERT into Info values (' p001 ', ' ', ' ', ', ')";
4. Execute SQL statement, query statement if execution succeeds return result set object, if execution fails return false
$result = $db->query ($sql);
5. Reading data from the result set
if ($result)
{
Var_dump ($result->fetch_row ()); Returns an array of rows of data (indexed array)
while ($row = $result->fetch_row ())
{
Var_dump ($row);
}
Var_dump ($result->fetch_assoc ());//Returns a row of data (associative array)
$shuju = $result->fetch_all ();//Returns all data (two-dimensional array)
Var_dump ($result->fetch_object ());//Returns a row of data (object)
echo $shuju [0][0];
}
1. Making Connection objects
$db = new Mysqli ("localhost", "root", "123", "MyDB");
2. Determine if there is an error
!mysqli_connect_error () or Die ("Connection failed! ");
3. Write SQL statements
$sql = "SELECT * from Nation";
4. Execute SQL statements
$result = $db->query ($sql);
5. Fetching data
if ($result)
{
$attr = $result->fetch_all ();
echo "<select>";
foreach ($attr as $v)
{
echo "<option value= ' {$v [0]} ' >{$v [1]}</option>";
}
echo "</select>";
}
?>
MySQL data access