Home > Article > Backend Development > PHP basic learning database operation
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(); }The above code is a PHP script for creating a new database. The mysql_query() function is used to execute SQL statements in PHP. This function has Two parameters: the first is the SQL statement, and the second is the database connection object, which is the $conn we got above
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);Inserting data is also very simple. Just use the mysql_query() function to execute the SQL statement.
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 above code uses the mysql_fetch_array() function to traverse the records from the database select result set, using $ row["id"] takes out the id of the record, and uses $row["name"] to take out the name value of the record
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 "fills in the name value and clicks the insert button, the following page will appear:"; 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.