An instance of an Select query statement used in Php

  • 2021-01-14 05:43:22
  • OfStack

sql has a number of statements for database operations. But there are a few common and relatively needed statements. The SELECT statement is used to select data from the database.

So let's start with the first SELECT statement
Statement 1:SELECT * FROM table_name
Explanation: means to read the entire table table_name according to data from the inside out
SELECT * FROM table_name Where x = 1
Select * from table table_name where key: x = 1

An example of an Select query


<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons");
while($row = mysql_fetch_array($result))
  {
  echo $row['FirstName'] . " " . $row['LastName'];
  echo "<br />";
  }
mysql_close($con);
?> 

example


<?php 
define ('HOSTNAME', 'localhost'); // Database host name  
define ('USERNAME', 'username'); // Database user name  
define ('PASSWORD', 'password'); // Database user login password  
define ('DATABASE_NAME', 'testdb'); // The database to query  
$db = mysql_connect(HOSTNAME, USERNAME, PASSWORD) or
         die (mysql_error()); 
// If the connection fails, it will be displayed mysql The cause of the error.  
mysql_select_db(DATABASE_NAME); 
// Switch to the testdb www.ofstack.com
$query = 
"SELECT uri,title FROM testdb WHERE 1 ORDER by rand() LIMIT 1"; 
// The above sentence means from testdb Medium random extraction 1 The data.  
$result = mysql_query($query); 
// The query  
while ($row = mysql_fetch_array($result)) { echo "<p id="title">" , 
($row['title']) , "</p><p id="uri">&ndash;" , nl2br($row['uri']) 
, "</p>"; } 
// According to the results  
mysql_free_result($result); 
// Release of the results  
mysql_close(); 
// Close the connection  
?>

The mysql Chinese data is garbled
The most common cause of garbled code is the database encoding UTF8 and the page claim encoding GB2312. At this time in PHP script directly SELECT data is garbled, need to use before the query:


mysql_query("SET NAMES GBK"); or mysql_query("SET NAMES GB2312");

To set the MYSQL connection code, make sure the page declaration code matches the connection code set here (GBK is an extension of GB2312). If the page is UTF-8, you can use:
mysql_query("SET NAMES UTF8"); Note that it is UTF8, not UTF-8. If the page claims the encoding and the database internal encoding 1 can not set the connection encoding.
The code is as follows:


$mysql_mylink = mysql_connect($mysql_host, $mysql_user, $mysql_pass);
mysql_query("SET NAMES 'GBK'");


Related articles: