PHP MySQL Select

The SELECT statement is used to select data from a database.

Selecting data from a database table

The SELECT statement is used to select data from a database.

Syntax

SELECT column_name(s) FROM table_name

Note:SQL statements are case-insensitive. SELECT is equivalent to select.

To make PHP execute the above statements, we must use the mysql_query() function. This function is used to send queries or commands to MySQL.

Example

The following example selects all data stored in the "Persons" table (* character selects all data in the table):

<?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);
?>

An example above stores the data returned by the mysql_query() function in the $result variable. Next, we use the mysql_fetch_array() function to return the first row in the record set as an array. Each subsequent call to mysql_fetch_array() returns the next row in the record set. The while loop statement will iterate through all the records in the record set. To output the values of each row, we use the PHP $row variable ($row['FirstName'] and $row['LastName']).

الخروج من الكود أعلاه هو:

Peter Griffin
Glenn Quagmire

عرض النتائج في جدول HTML

في المثال التالي، يتم اختيار نفس البيانات كما في المثال السابق، ولكن سيتم عرض البيانات في جدول HTML:

<?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");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "</tr>";
  }
echo "</table>";
mysql_close($con);
?>

الخروج من الكود أعلاه هو:

Firstname Lastname
Glenn Quagmire
Peter Griffin