PHP MySQL Select

Posted by tutor | Posted in PHP Tutorial | Posted on 18-12-2009-05-2008

0

The SELECT statement is used to select data from a database, based on some conditions or all of the data.

Syntax

    SELECT column_name(s)
    FROM table_name

The following example selects all the data stored in the “Country” table.A * character selects all the data in the table.

    For eg:

    <?php
    $conn = mysql_connect(”localhost”,”tutor”,”tutor123″);
    if (!$conn)
    {
    die(’Could not connect: ‘ . mysql_error());
    }
    mysql_select_db(”my_db”, $conn);
    $result = mysql_query(”SELECT * FROM Persons”);
    while($row = mysql_fetch_array($result))
    {
    echo $row['Country'] . ” ” . $row['Capital'];
    echo “<br />”;
    }
    mysql_close($conn);
    ?>

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.

    Output:

    Zimbabwe Harare
    Poland Warsaw

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
    $conn= mysql_connect(”localhost”,”tutor”,”tutor123″);
    if (!$con)
    {
    die(’Could not connect: ‘ . mysql_error());
    }
    mysql_select_db(”my_db”, $conn);
    $result = mysql_query(”SELECT * FROM Country”);
    echo “<table border=’1′>
    <tr>
    <th>Country</th>
    <th>Capital</th>
    </tr>”;
    while($row = mysql_fetch_array($result))
    {
    echo “<tr>”;
    echo “<td>” . $row['Country'] . “</td>”;
    echo “<td>” . $row['Capital'] . “</td>”;
    echo “</tr>”;
    }
    echo “</table>”;
    mysql_close($con);
    ?>
    Output:

    Firstname Lastname
    Zimbabwe Harare
    Poland Warsaw

Write a comment

Twitter Users
Enter your personal information in the form or sign in with your Twitter account by clicking the button below.