online tutorilas

Select Records using PHP MySQL Select Statement

You can use SELECT statement to select data from a database.

Syntax

SELECT column_name(s)

FROM table_name

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.

For Example:

The following example selects all the data stored in the “student” table (The * character selects all the data in the table):

<?php

$con = mysql_connect(“localhost”,”username”,”password”);

if (!$con)

{

die(‘Could not connect: ‘ . mysql_error());

}

mysql_select_db(“schooldatabase”, $con);

$result = mysql_query(“SELECT * FROM student”);

while($row = mysql_fetch_array($result))

{

echo $row[‘FirstName’] . ” ” . $row[‘LastName’];

echo “<br />”;

}

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:

Fisrtname   Lastname

Garry                 Kristen

Jhon                   Don

 

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:

<?php

$con = mysql_connect(“localhost”,”username”,”password”);

if (!$con)

{

die(‘Could not connect: ‘ . mysql_error());

}

mysql_select_db(“schooldatabase”, $con);

$result = mysql_query(“SELECT * FROM student”);

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

?>

The output of the code above will be:

Firstname     Lastname

Garry                   Kristen

Jhon                      Don

Related Posts


Leave a Reply

Your email address will not be published. Required fields are marked *


*