MySQL data query read operation

SELECT statement is used to select data from the database

 

Select data from database table

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

SELECT column_name(s) FROM table_name

NOTE: SQL statements are not case sensitive. SELECT is equivalent to select.

In order for PHP to execute the above statement, we must use the mysql_query() function. This function is used to send a query or command to MySQL.

example

 

The following example selects all data stored in the "Persons" table (the * 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);
?>

     Note: The statement I marked in red must be in while, otherwise it will loop infinitely

    The above example 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 from the recordset as an array. Each subsequent call to the mysql_fetch_array() function returns the next row in the recordset. The while loop statement loops through all the records in the recordset. To output the value of each row, we use PHP's $row variable ($row['FirstName'] and $row['LastName']).

   Output of the above code:

   Peter Griffin

   Glenn Quagmire

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326171566&siteId=291194637