This article mainly introduces the method steps of PHP connection MySQL database. Have a good reference value, follow the small series together to see it
To connect to a database:
Use an object-oriented approach;
1. Create a Mysqli object, create a Connection object
2. Prepare an SQL statement
3. Execute the SQL statement, if it is a query statement. Successful return of results and objects
4. Find the data from the result set object;
Query Property Code:
<?php//build a Mysqli object, make the Connection object $db=new mysqli ("localhost", "root", "12345678", "Heiheihei");//parentheses fill in the IP address domain name, user name, password, Database name //prepare an SQL statement $sql = "SELECT * from student";//Execute SQL statement, if it is a query statement. Successful return of the result and object $reslut = $db->query ($sql);//Determine if the return has content, execution succeeds if ($reslut) {//If successful, data is found from the result set object; $attr = $reslut Fetch_all ();//Returns an indexed array: $attr = $reslut->fetch_row ()//Returns an associative array: Tch_assoc ();//return object: $attr = $reslut->fetch_object () ;//returns both Index and association: $ARRT = $reslut->fetch_array (); Var_dump ($attr);? >
The last return value is a set object, we use Fetch_all (), Fetch_row () in order to see the results clearly. Fetch_object ();
Adding and Deleting statements:
Add a piece of information:
Build Connection Object $db = new mysqli ("localhost", "root", "12345678", "Heiheihei");//Prepare SQL statement $sql = "INSERT into cou values (' 3-111 ', ' Hehe ', ' 803 '); Execute SQL Statement "= $db->query ($sql), if ($r)//If" ture{ echo "was executed successfully;} else { echo "failed to execute";}
Changing a message:
<?php//Connect Object $db = new mysqli ("localhost", "root", "12345678", "Heiheihei");//Prepare SQL statement $sql = "Update cou set cname= ' haha ' where tno= ' 803 '; Execute SQL statement = $db->query ($sql), if ($r) { echo "execute successfully";} else { echo "failed to execute";}? >
Delete:
<?php//Connect Object $db = new mysqli ("localhost", "root", "12345678", "Heiheihei");//Prepare SQL statement $sql = "Delete from cou where tno= ' 803 ' "; Execute SQL statement = $db->query ($sql), if ($r) { echo "execute successfully";} else { echo "failed to execute";}? >