: This article describes how to use php to connect to a database for simple queries. For more information about PHP tutorials, see. Hey, I just learned, record it ~
1. first create a database, create a data table test in it, and insert two records at will.
2. create a php file.
Database Connection code:
$ Conn = mysql_connect ("localhost", "root", ""); // connect to the database server if (! $ Conn) {die ('could not connect :'. mysql_error ();} mysql_select_db ("mytest", $ conn); // select the database mytetstmysql_query ("set names utf8"); // set the encoding format
Mysql_connect (servername, username, password );
Servername |
Optional. Specifies the server to be connected. The default value is localhost: 3306 ". |
Username |
Optional. Specifies the username used for logon. The default value is the name of the user who owns the server process. |
Password |
Optional. Specifies the password used for logon. The default value is "". |
3. execute database statements, such as query statements
$arr=mysql_query("select * from test",$conn);
Output query results
while($row = mysql_fetch_array($arr)){echo $row['id'] . " " . $row['num'];echo "
";}
----------------------------------------
Implementation result:
When you click "search all", it is displayed as follows:
When searching by id, enter 1 to display:
Complete code:
"; Echo"IdNumNameSexBithday"; If (isset ($ _ POST ['Select _ all']) {$ arr = mysql_query (" select * from test ", $ conn ); while ($ row = mysql_fetch_array ($ arr) {echo"{$ Row ['id']}{$ Row ['num']}{$ Row ['name']}{$ Row ['sex']}{$ Row ['birthday']}"; // Echo $ row ['id']." ". $ row ['num']; // echo"
";}} Else if (isset ($ _ POST ['Select _ sure ']) {$ id = $ _ POST ['Select _ INDEX']; $ arr = mysql_query ("select * from test where id = $ id", $ conn); if ($ row = mysql_fetch_assoc ($ arr )) {// if the queried echo"{$ Id}{$ Row ['num']}{$ Row ['name']}{$ Row ['sex']}{$ Row ['birthday']}";}} Echo""; Mysql_close ($ conn);?>
The above describes how to use php to connect to a database for simple queries, including some content, and hope to be helpful to friends who are interested in PHP tutorials.