Payne's SQL Note #5

Back to Payne's SQL Notebook


Select Columns

Syntax:

// Select columns
SELECT column_name_1, column_name_2, ...
FROM table_name

// Select one row from the result.
// Access the value by $row->property.

$row = mysql_fetch_object($result);

// Access the value by $row["Name"].
$row = mysql_fetct_array($result);

CodeResult
<html>
<body>
<h1>Display All Records</h1>

<?php

// Create a connection to a MySQL RDBMS.
$con = mysql_connect("localhost", "username", "password");

// If the connection fails, display error message.
if (!$con)
{
    die('Error connecting to MySQL: ' . mysql_error());
}

// Select a database
mysql_select_db("ReferenceDB", $con);

// Select columns
$sql="SELECT * FROM ReferenceTB";

$result=mysql_query($sql, $con);

// Display result
echo "<table border='1' style='border-collapse:collapse;'>;
<tr><th>Field</th><th>Information</th></tr>";
echo "<tr><td colspan='2' style='background-color:#bbbbbb;'></td></tr>";

while($row = mysql_fetch_array($result))
{
    echo "<tr><td>PMID</td><td>" . $row['PMID'] . "</td></tr>";
    echo "<tr><td>First Author</td><td>" . $row['Author'] . "</td></tr>";
    echo "<tr><td>Title</td><td>" . $row['Title'] . "</td></tr>";
    echo "<tr><td>Journal</td><td>" . $row['Journal'] . "</td></tr>";
    echo "<tr><td>Year</td><td>" . $row['Year'] . "</td></tr>";
    echo "<tr><td colspan='2' style='background-color:#bbbbbb;'></td></tr>";
}

echo "</table>";

// Close the connection.
mysql_close($con);

?>

</body>;
</html>
display_all_records.php