SQL has many statements to manipulate the database. But the common and comparative needs are so few statements. The SELECT statement is used to select data from the database.
So let's introduce the first SELECT statement first.
Statement 1:select * FROM table_name
To read the entire table table_name the data in it shows
Statement 1:select * FROM table_name Where x = 1
Explanation: The meaning is to read the table table_name inside the key name: X value is: 1 data show
Examples of Select query statements
Copy Code code as follows:
<?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
Copy code code as follows:
<?php
Define (' HOSTNAME ', ' localhost '); Database host Name
Define (' USERNAME ', ' USERNAME '); Database user Name
Define (' PASSWORD ', ' PASSWORD '); Database User Login Password
Define (' database_name ', ' testdb '); Databases that need to be queried
$db = mysql_connect (HOSTNAME, USERNAME, PASSWORD) or
Die (Mysql_error ());
If you do not connect, you will see the reason for MySQL error.
mysql_select_db (database_name);
Switch to TestDB www.jb51.net
$query =
"Select Uri,title from TestDB WHERE 1 order by rand () LIMIT 1";
The above sentence means to randomly extract a piece of data from the TestDB.
$result = mysql_query ($query);
Inquire
while ($row = Mysql_fetch_array ($result)) {echo "<p id=" title ">",
($row [' title ']), "</p><p id=" uri ">–", NL2BR ($row [' URI '])
, "</p>"; }
Show results
Mysql_free_result ($result);
Release results
Mysql_close ();
Close connection
?>
MySQL Chinese data appears garbled
The database uses the UTF8 code, but the page affirms the code is GB2312, this is the most common produces the garbled reason. At this time in the PHP script directly select data out is garbled, need to use before the query:
Copy Code code as follows:
mysql_query ("Set NAMES GBK") or mysql_query ("set NAMES GB2312");
To set the MySQL connection code to ensure that the page declaration code is consistent with the connection code set here (GBK is an extension of GB2312). If the page is UTF-8 encoded, you can use:
mysql_query ("SET NAMES UTF8"); Attention is UTF8 rather than general UTF-8. If the code of the page declaration is consistent with the internal encoding of the database, the connection code can be set.
The code is as follows:
Copy Code code as follows:
$mysql _mylink = mysql_connect ($mysql _host, $mysql _user, $mysql _pass);
mysql_query ("SET NAMES ' GBK '");