Php basic tutorial-5 database summary, php basic tutorial Database
1. Database Connection
$ Dbc = mysql_connect (hosetname, username, password );
2. Mysql error handling
Mysql_error (); displays detailed reports of errors
3. Create and select a database
CREATE: mysql_query ('create DATABASE somedb ');
Select: mysql_select_db ('somedb'); // select the database before each query.
4. Create a table
$ Query = 'create TABLE my_table (id int primary key, information TEXT); assign a variable to the creation statement first
Mysql_query ($ query); // put the variable into the mysql_query () function
5. Insert data
When creating a table, each query assigns a variable, and then passes the variable to the mysql_query () function:
$ Query = "insert into entries (entry_id, title, entry, data_entered) VALUES (0, 'title', '$ entry', NOW ())";
Mysql_query ($ query );
6. Securely query data
For a user-input query, use mysql_real_escape_string ($ var) to escape potentially dangerous characters such as single quotes (a backslash will be added before it)
7. retrieve data from the database
Copy the query result 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, colunfe2 = value WHERE some_column = value ';
$ Result = mysql ($ query );
Code test: ws. php
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
// Connect to the database and select 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 a TABLE/* $ 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 data $ 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>
Result: