Home >php教程 >php手册 >php基础教程5数据库总结

php基础教程5数据库总结

WBOY
WBOYOriginal
2016-06-13 09:15:331700browse

php基础教程——5数据库总结

1.数据库的连接

$dbc = mysql_connect(hosetname, username, password);

2.Mysql错误处理

mysql_error();显示错误的详实报告

3.创建和选择数据库

创建:mysql_query(‘CREATE DATABASE somedb’);

选中:mysql_select_db('somedb'); //每次运行查询前都要选中数据库

4.创建表

$query = 'CREATE TABLE my_table(id INT PRIMARY KEY, information TEXT);将创建语句先赋予一个变量

mysql_query($query);//再将变量放入mysql_query()函数

5.插入数据

同创建表,每个查询都赋予一个变量,然后再将变量传递给mysql_query()函数:

$query = " INSERT INTO entries(entry_id, title, entry, data_entered) VALUES(0, 'title', '$entry', NOW())";

mysql_query($query);

6.安全查询数据

对于用户输入的一段查询,用mysql_real_escape_string($var)对可能危险的字符如单引号,进行转义(将在其前加一个反斜线)

7.从数据库中进行检索数据

需要将查询的结果复制给一个变量:
$query = 'SELECT * FROM users WHERE ( name = myname)';

$result = mysql($query);

8.删除数据

$query = 'DELETE FROM users WHERE name = myname LIMIT 1';

$result = mysql($query);

9.更新

$query = UPDATE tablename SET column1 = value, colunmn2 = value WHERE some_column = value';

$result = mysql($query);

编码测试: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(&#39;localhost&#39;, &#39;root&#39;, &#39;&#39;)){
	if (@mysql_select_db(&#39;mydata&#39;)){
		print &#39;<p>selected!</p>&#39;;
	}else{
		print &#39;<p>can not select error: &#39;. mysql_error().&#39;</p>&#39;;
	}
}else{
	print &#39;<p>can not connect. error: &#39;. mysql_error().&#39;</p>&#39;;
}
//创建表
/*
$create = &#39;CREATE TABLE myTable(
		id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
		name VARCHAR(100) NOT NULL
	)&#39;;print "<p>create……</p>";
	
	if (@mysql_query($create)){
		print &#39;<p>created!</p>&#39;;
	}else {
		print &#39;<p>can not create error: &#39;. mysql_error().&#39;</p>&#39;;
	}mysql_close();*/
//插入数据
$insert = &#39;INSERT INTO myTable (id, name) VALUES (12345, "charles")&#39;;
if (@mysql_query($insert)){
		print &#39;<p>inserted!</p>&#39;;
	}else {
		print &#39;<p>can not insert error: &#39;. mysql_error().&#39;</p>&#39;;
	}mysql_close();

?>
	

<p><p>This is the foot of the document</p></p>
</body> 
</html> 

结果显示:


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn