Go Back   Wiki NewForum | Latest Entertainment News > Career Forum & Tips > Tech Forum & Tutorial > PHP Forum & Tutorial


PHP MySQL Select


Reply
Views: 3031  
Thread Tools Rate Thread
  #1  
Old 05-04-2009, 05:49 PM
welcomewiki welcomewiki is offline
Member
 
Join Date: Dec 2008
Location: India
Posts: 80,566
Default PHP MySQL Select

The SELECT statement is used to select data from a database.
Select Data From a Database Table

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



SELECT column_name(s)
FROM table_name



To learn more about SQL, please visit our SQL tutorial.


To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection.
Example

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




$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 "
";
} mysql_close($con);
?>



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


The output of the code above will be:
Peter Griffin
Glenn Quagmire

Reply With Quote
  #2  
Old 05-04-2009, 05:50 PM
welcomewiki welcomewiki is offline
Member
 
Join Date: Dec 2008
Location: India
Posts: 80,566
Display the Result in an HTML Table

The following example selects the same data as the example above, but will display the data in an HTML table:




$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 "
<
tr>


"; while($row = mysql_fetch_array($result))
{
echo "";
echo "";
echo "";
echo "";
}
echo "
Firstname Lastname
" . $row['FirstName'] . "" . $row['LastName'] . "
"; mysql_close($con);
?>



The output of the code above will be:




Firstname Lastname Glenn Quagmire Peter Griffin
Reply With Quote
Reply

New topics in PHP Forum & Tutorial





Powered by vBulletin® Version 3.8.10
Copyright ©2000 - 2024, vBulletin Solutions, Inc.
WikiNewForum)