To access the database steps:
1. Create a Connection object
1 $db = new mysqli ("localhost", "root", "123", "MyDB");
2. Determine if the connection is wrong
1 ! Mysqli_connect_error () or die ("Connection failed! ");
3. Write SQL statements
1 $sql = "SELECT * from Info";
4. Execute SQL statement, query statement if execution succeeds return result set object, if execution fails return false
1 $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 ();//return all data (two-dimensional array) Var_dump($result->fetch_object ());//returns a row of data (objects)}
Example: Show the National column in the Nation table in the form of a drop-down list
//1. Making Connection Objects$db=NewMysqli ("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 Dataif($result){ $attr=$result-Fetch_all (); Echo"<select>"; foreach($attr as $v) { Echo"<option value= ' {$v[0]} ' >{$v[1]} </option> "; } Echo"</select>";}
PHP Access database