Here I summarize the common PHP connection MySQL database and read Write database method, I hope to help you, of course, as a review of my own summary.
1. To better set up a data connection, the values involved in the data connection are typically defined as variables.
?
|
$mysql_server_name=‘localhost‘; //改成自己的mysql数据库服务器 $mysql_username=‘root‘; //改成自己的mysql数据库用户名 $mysql_password=‘123456‘; //改成自己的mysql数据库密码 $mysql_database=‘Mydb‘; //改成自己的mysql数据库名 |
You can also put the above variables in a file, you can make other file calls at any time.
For example, put the above in the following: Db_config.php is called directly on other pages that need to use the database.
Calling code: Require ("db_config.php");
2. Connect to the database
$conn
=mysql_connect(
$mysql_server_name
,
$mysql_username
,
$mysql_password
)
or
die
(
"error connecting"
) ;
//连接数据库
mysql_query(
"set names ‘utf8‘"
);
//数据库输出编码 应该与你的数据库编码保持一致.南昌网站建设公司百恒网络PHP工程师建议用UTF-8 国际标准编码.
mysql_select_db(
$mysql_database
);
//打开数据库
$sql
=
"select * from news "
;
//SQL语句
$result
= mysql_query(
$sql
,
$conn
);
//查询
3. Read the contents of the table, here we use the while, you can use for or other depending on the situation.
?
|
while($row = mysql_fetch_array($result)) { echo "<div style=\"height:24px; line-height:24px; font-weight:bold;\">"; //排版代码 echo $row[‘Topic‘] . "<br/>"; echo "</div>"; //排版代码 } |
4.php write database, MySQL data write
?
|
$conn=mysql_connect($mysql_server_name,$mysql_username,$mysql_password); //连接数据库 mysql_query("set names ‘utf8‘"); //数据库输出编码 mysql_select_db($mysql_database); //打开数据库 $sql = "insert into messageboard (Topic,Content,Enabled,Date) values (‘$Topic‘,‘$Content‘,‘1‘,‘2011-01-12‘)"; mysql_query($sql); mysql_close(); //关闭MySQL连接 |
Common code for PHP connections and reading and writing to MySQL databases