Common code for PHP connections and reading and writing to MySQL databases

Source: Internet
Author: User
Tags php write

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.