I am not sure how to go about doing this, but I have an SQL Database where I query for info. I would like to display the query results in a list on a webpage with a check-box at the beginning so the user can select which they record of info they would like to modify.
My database has over 20+ columns but I only want to display probably 5 columns of data pertaining to the query that I searched for. Currently I have the data being repopulated in text fields. But I would like to go a step further and get the data displayed in a horizontal list.
Basically something like this:
Client searches for an order in the database. Say there are 2 different orders matching the search criteria in the DB. I would like say 5 columns of data from the DB for those 2 orders displayed on a page with a check-box next to each, so the client can then select which order they want to modify.
I am not sure of the code used to display the sql data in a list with a check-box. Thanks!
The code below demonstrates how to:
Beware of some parameters that you may need to modify, e.g. database name, username, password, name of the primary key ("id").
# connect to mysql
$db_link = mysql_connect('localhost', 'root', '');
if (!$db_link)
die('Cannot connect : ' . mysql_error());
# select database
$db_selected = mysql_select_db('test_db', $db_link);
if (!$db_selected)
die ('Cannot select database : ' . mysql_error());
# execute search query
$sql = 'SELECT * FROM `test_table` LIMIT 20';
$result = mysql_query($sql);
# check result
if (!$result)
die('Could not successfully run query: ' . mysql_error());
# display returned data
if (mysql_num_rows($result) > 0)
{
?>
<form action="" method="post">
<table style="border: 1px solid black">
<?php
while ($row = mysql_fetch_assoc($result))
{
echo '<tr><td>';
echo '<input type="checkbox" name="selected[]" value="'.$row['id'].'"/>';
echo '</td>';
foreach ($row as $key => $value)
echo '<td>'.htmlspecialchars($value).'</td>';
echo '</tr>';
}
?>
</table>
<input type="submit"/>
</form>
<?php
}
else
echo '<p>No data</p>';
# free resources
mysql_free_result($result);
# display posted data
echo '<pre>';
print_r($_POST);
echo '</pre>';
?>
Basically, something like this:
$sql = "select primaryKey, field1, field2, ... FROM table"
$result = mysql_query($sql) or die(mysql_error());
echo <<<EOL;
<form ...>
<table>
<tr>
<th></th>
<th>Field 1</th>
<th>Field 2</th>
...
</tr>
EOL;
while ($row = mysql_fetch_asssoc($result)) {
echo <<<EOL
<tr>
<td><input type="checkbox" name="primaryKey[]" value="{$row['primaryKey']}" /></td>
<td>{$row['field1']}</td>
<td>{$row['field2']}</td>
...
</tr>
EOL;
}
echo <<<EOL
</table>
<input type="submit" />
</form>
EOL;
If you mean list as in <select>
, then the basic logic works the same, just adjust the html to output a <select>
and a series of <option>
's as desired.