PHP connects to the database:
Use the mysql_connect() function to connect to the database. This function has three parameters, namely url, username, and password. The usage is as follows:
$conn = mysql_connect("localhost", "root", "root");
PHP New Database:
$sql = "CREATE DATABASE $db_name"; if(mysql_query($sql, $conn)){ mysql_select_db($db_name); echo "create db ok, use db $db_name<br/>"; }else{ echo mysql_error(); }
PHP new table:
$sql = "create table test ( id int primary key auto_increment, name varchar(20) )"; if(mysql_query($sql, $conn)){ echo "create table ok<br/>"; }else{ echo mysql_error(); }
PHP inserts data into the database:
$sql = "insert into test(name) values('$name')"; mysql_query($sql, $conn);
PHP database SELECT statement:
$cursor = mysql_query("select * from test order by name"); while($row = mysql_fetch_array($cursor)){ $id = $row["id"]; $name = $row["name"]; }
The following is an example of PHP manipulation of the database. In this example, there are two PHP files: index.php and result. php, where index.php is used to enter a name value, result.php inserts the name value entered by the user into the database, queries all records from the database, and then displays them on the page. It is assumed that the database "db_test" has been created currently, and The table "test" is created under the database. The code of index.php is as follows:
<form action="result.php" method="post"> input name:<br/> <input type="text" name="name"> <input type="submit" value="insert"> </form>
"; echo ""; while($row = mysql_fetch_array($cursor)){ $id = $row["id"]; $name = $row["name"]; echo " ID NAME "; } echo ""; }else{ echo mysql_error(); } mysql_close($conn); } ?> $id $name
The above introduces the database operation of basic PHP learning, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.