Home >Backend Development >PHP Tutorial >PHP basic tutorial - 5 database summary_PHP tutorial
1. Database connection
$dbc = mysql_connect(hosetname, username, password);
2.Mysql error handling
mysql_error(); displays a detailed report of the error
3. Create and select database
Create: mysql_query(‘CREATE DATABASE somedb’);
Select: mysql_select_db('somedb'); //The database must be selected before each query is run
4. Create table
$query = 'CREATE TABLE my_table(id INT PRIMARY KEY, information TEXT); assign the create statement to a variable first
mysql_query($query);//Put the variable into the mysql_query() function
5. Insert data
Same as creating a table, each query is assigned a variable, and then the variable is passed to the mysql_query() function:
$query = " INSERT INTO entries(entry_id, title, entry, data_entered) VALUES(0, 'title', '$entry', NOW())";
mysql_query($query);
6. Secure data query
For a query entered by the user, use mysql_real_escape_string($var) to escape potentially dangerous characters such as single quotes (a backslash will be added in front of them)
7. Retrieve data from the database
You need to copy the query results to a variable:
$query = 'SELECT * FROM users WHERE ( name = myname)';
$result = mysql($query);
8. Delete data
$query = 'DELETE FROM users WHERE name = myname LIMIT 1';
$result = mysql($query);
9.Update
$query = UPDATE tablename SET column1 = value, colunmn2 = value WHERE some_column = value';
$result = mysql($query);
Coding test: ws.php
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>test</title><base> </head> <body> <?php
//连接数据库,并选中 if ($dbc = @mysql_connect('localhost', 'root', '')){ if (@mysql_select_db('mydata')){ print '<p>selected!</p>'; }else{ print '<p>can not select error: '. mysql_error().'</p>'; } }else{ print '<p>can not connect. error: '. mysql_error().'</p>'; }
//创建表 /* $create = 'CREATE TABLE myTable( id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL )';print "<p>create……</p>"; if (@mysql_query($create)){ print '<p>created!</p>'; }else { print '<p>can not create error: '. mysql_error().'</p>'; }mysql_close();*/
//插入数据 $insert = 'INSERT INTO myTable (id, name) VALUES (12345, "charles")'; if (@mysql_query($insert)){ print '<p>inserted!</p>'; }else { print '<p>can not insert error: '. mysql_error().'</p>'; }mysql_close(); ?> <div><p>This is the foot of the document</p></div> </body> </html>