Common codes for Php connection and reading and writing mysql database

  • 2021-07-10 19:08:05
  • OfStack

Now that you have seen this article, which shows that you must know what PHP and MySQL are all about, I won't talk about it. But why do you keep reading this article? It may be that you used to copy and paste 1 code before, and didn't really understand the meaning of the code; It is also possible that you have understood it before, but like me, I have no contact for a period of time and am unfamiliar; Or, someone asks you a similar simple question, and you have disdained to answer it. You search directly on the Internet and just find this article, so you recommend it to that person...

Anyway, here I summarize the commonly used PHP connection to MySQL database and the methods of reading and writing to the database, hoping to help you, of course, as my own review summary.

1. In order to better set up the data connection, 1 generally defines the values involved in the data connection as variables.


$mysql_server_name='localhost'; // Change to your own mysql Database server 

$mysql_username='root'; // Change to your own mysql Database user name 

$mysql_password='123456'; // Change to your own mysql Database password 

$mysql_database='Mydb'; // Change to your own mysql Database name 

You can also put the above variables in one file, which can be called by other files at any time.

For example, put the above content in: db_config. php, and then call it directly on other pages that need to use the database.

Calling code: require ("db_config. php");

2. Connecting to the database


$conn=mysql_connect($mysql_server_name,$mysql_username,$mysql_password) or die("error connecting") ; // Connect to a database 

mysql_query("set names 'utf8'"); // Database output coding   Should be kept with your database code 1 To . Nanchang website construction company Baiheng network PHP Engineer's suggestion is to use UTF-8  International standard code .

mysql_select_db($mysql_database); // Open the database 

$sql ="select * from news "; //SQL Statement 

$result = mysql_query($sql,$conn); // Query 

3. Read the contents of the table. Here we use while, and we can use for or something else according to the specific situation.


while($row = mysql_fetch_array($result))

{

echo "<div style=\"height:24px; line-height:24px; font-weight:bold;\">"; // Typesetting code 

echo $row['Topic'] . "<br/>";

echo "</div>"; // Typesetting code 

}

4. Write php to database and write Mysql data


$conn=mysql_connect($mysql_server_name,$mysql_username,$mysql_password); // Connect to a database 

mysql_query("set names 'utf8'"); // Database output coding 

mysql_select_db($mysql_database); // Open the database 

$sql = "insert into messageboard (Topic,Content,Enabled,Date) values ('$Topic','$Content','1','2011-01-12')";

mysql_query($sql);

mysql_close(); // Shut down MySQL Connect 


Related articles: