Using PHP to Access databases built by MySQL
Connecting to a database
1. Build Connection Object $db = new mysqli ("localhost", "root", "123", "text"),//2. Determine if the connection is wrong if (Mysqli_connect_error ()) {die ("Connection failed! ");}
Preparing SQL statements
$sql = "SELECT * from Info";
Executes the SQL statement, returning the result set object
$result = $db->query ($sql); Execute Query statement
Fetching data from the result set
$attr = $result->fetch_all (); Returns all data and exists as a two-dimensional array
Three optional parameters: Mysqli_assoc Returns an associative array, Mysqli_num returns an indexed array, Mysqli_both returns indexes and associations, and does not need double quotes when used
Var_dump ($attr); Output results
The result returns a two-dimensional array:
Other FETCH data statements:
$attr = $result->fetch_array ();//Returns the current data, returns a one-dimensional array, by default the index association has//$attr = $result->fetch_assoc (); Returns the current data, returns a one-dimensional associative array//$attr = $result->fetch_object (); Returns the object of the current data//$attr = $result->fetch_row (); Returns the current data, returning an indexed array
Output the results in the page:
$attr = $result->fetch_all (), foreach ($attr as $v) {echo "<div>{$v [0]}--{$v [1]}--{$v [2]}--{$v [3]}--{$v [4]} </div> ";}
Use the While statement:
1. Build Connection Object $db = new mysqli ("localhost", "root", "" "," 12345 "),//2. Determine if the connection is wrong if (Mysqli_connect_error ()) {die (" Connection failed! ");} $sql = "SELECT * from Info", $result = $db->query ($sql), while ($attr = $result->fetch_row ()) {echo "<div>{$attr [0]} --{$attr [1]}--{$attr [2]}--{$attr [3]}--{$attr [4]}</div> ";}
Use for loop:
$de = new Mysqli ("localhost", "root", "" "," 12345 "), $e =" SELECT * from info "; $result = $de->query ($e); $atter = $result- >fetch_all (); for ($i =0; $i <count ($atter); $i + +) {for ($j =0; $j <count ($atter [$i]); $j + +) {if ($j ==4) {echo $atter [$i] [$j]. " <br> ";} Else{echo $atter [$i] [$j]. " --";}}}
1. Build Connection Object $db = new mysqli ("localhost", "root", "" "," 12345 "),//2. Determine if the connection is wrong if (Mysqli_connect_error ()) {die (" Connection failed! ");} $sql = "SELECT * from Info", $result = $db->query ($sql), for (; $attr = $result->fetch_row ();) {echo "<div>{$attr [0]} --{$attr [1]}--{$attr [2]}--{$attr [3]}--{$attr [4]}</div> ";}
The result is the same as above.
Data additions and deletions:
1. Build Connection Object $db = new mysqli ("localhost", "root", "123", "text"),//2. Prepare a SQL statement $sql = "INSERT into nation values (' n099 ', ' people ') ";//3. Execute SQL statement $result = $db->query ($sql);//Execute successfully returns TRUE, execution failure returns false
After execution, the data is written in MySQL, and execution returns false.
PHP database access and deletion and modification