While loop and mysql_fetch_assoc on one query? - php

I have a webpage that does a MySQL query on a table. I have it to echo it out in a table and that works as it should, example:
$query = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_array($query){
// my table and db stuff echos out here
}
Now using the same mysql query $query I am trying to echo it out again on the same page using the same query underneath but my problem is it does not seem to work.
Now you maybe thinking what I'm doing is odd, but the reason why is the first code above echoes data out in a table, but also checkboxes next to the stuff echoed out as it is for a form. All that works fine but it seems I cannot do another while loop above on the same query. The second one is exactly the same as above; only difference is it's not a form.
Can I only do a while() and mysql_fetch_assoc once on a single query?
UPDATE:
I'm sorry I still don't understand properly.
Here's my code; could anyone edit it for me?
(I could not put php tags in the code to split up the HTML from the PHP code. Sorry for any inconvenience).
$q = mysql_query("SELECT * FROM table");
<h1> Vote for your favourite extension </h1>
<form method="post" action="<?php echo basename(__file__); ?>">
<table>
<tbody>
<tr class="odd">
<td colspan="3" class="cellfeat" style="text-align: center;">Vote for your favourite extension</td>
</tr>
<?php
if(!$q){
// query failed etc
} else { // query ok so display form
while($row = mysql_fetch_array($q)){
echo '<tr class="odd">';
echo '<td class="cellfeat"><img src="images/statimages/extensions.gif" alt="Extension Vote Image" /></td>';
echo '<td class="cellfeat">'.$row['checkbox'].'</td>';
echo '<td class="cellfeat"><input type="checkbox" name="'.$row['id'].'" value="'.$row['id'].'" /></td>';
echo '</tr>';
}
}
?>
</tbody>
</table>
<input type="submit" class="submitcontact" value="Vote" />
</form>
<h1>Extension Statistics</h1>
<table>
<tbody>
<tr class="odd">
<td colspan="3" class="cellfeat" style="text-align: center;">Voting Statistics</td>
</tr>
while($row = mysql_fetch_array($q)){
echo '<tr class="odd">';
echo '<td class="cellfeat"><img src="images/statimages/extensions.gif" alt="Extension Vote Image" /></td>';
echo '<td class="cellfeat">'.$row['checkbox'].'</td>';
echo '<td class="cellfeat">'.$row['count'].'</td>';
echo '</tr>';
}
?>
</tbody>
</table>

The only proper way as follows:
first, collect your data into array
$data = array();
while($row = mysql_fetch_array($query){
$data[] = $row;
}
then, call a template
and use your data as many times as you wish:
<table>
<? foreach ($data as $row): ?>
<tr>
<td><?=$row['id']?></td>
<td><?=$row['name']?></td>
<? endforeach ?>
</table?>

If I understand you need to use this function
http://php.net/manual/en/function.mysql-data-seek.php
to move your pointer

Related

Display data from SQL query in an HTML table in PHP

I retrieved a list of data from an SQL database and now I would like to display it in a neat table rather than in a list. I managed to find a way to do this (probably not very elegant, though), but the column headers seem to be offset and I have not idea how to fix this.
I'm completely new to PHP, so any hints on how to solve this will be much appreciated!
echo '<table>';
echo '<tr>';
echo '<th>';
echo '<td>Word</td>';
echo '<td>Frequency</td>';
echo '</th>';
echo '</tr>';
$response = $db->query("SELECT * FROM frequencies WHERE freq BETWEEN 900 AND 910 ORDER BY freq");
while ($row = $response->fetch())
{
echo '<tr>';
echo '<td>'.$row['word'].'</td>';
echo '<td>'.$row['freq'].'</td>';
echo '</tr>';
}
echo '</table>';
$response->closeCursor();
A <th> element is a table header element and should be used instead of <td> (table data) element in your header row - it should never be a wrapper around <td> elements.
echo '<table>';
echo '<tr>';
echo '<th>Word</th>';
echo '<th>Frequency</th>';
echo '</tr>';
I prefer combining php and html
<table >
<thead>
<tr>
<th >Word</th>
<th >Frequency</th>
</tr>
</thead>
<?php
$response = $db->query("SELECT * FROM frequencies WHERE freq
BETWEEN 900 AND 910 ORDER BY freq");
?>
<tbody>
<?php
while ( $row = $response->fetch()) {
?>
<tr>
<td><?php echo $row['word']; ?></td>
<td><?php echo $row['freq']; ?></td>
</tr>
<?php }
$response->closeCursor();
?>
</tbody>
</table>

Creating a table in HTML to display the result of a query in MySQL

I want to create a PHP page to display the results of a query in a MySQL database under the format of a table. By spending quite some time on different forums, I ended with something that is somehow satisfying me but that is strongly affecting the design and the layout of my webpage. Due to the fact that I wrote the code by a test-fail strategy, it is far from being straightforward and I am sure it is possible to shorten and simplify it and, therefore, make it more compatible with the format of my webpage. Could anybody have a look at it and give some suggestions of general interest about how to solve this kind of issues?
<div id="main">
<?php
require_once('../mysqli_connect.php');
$response = $db->query("SELECT * FROM metabolite");
echo '<table align="center" cellspacing="2" cellpadding="5" border = "1">
<tr><td align="center"><b>Metabolites</b></td>
<td align="center"><b>KEGG Id</b></td>
<td align="center"><b>Synonyms</b></td></tr>';
while ($data = $response->fetch())
{
?>
<tr><td align="left">
<?php echo $data['Metabolite_name']; ?></td>
<td align="left">
KEGG: <?php echo $data['Synonyms']; ?></td>
<td align="left">
<?php echo $data['Synonyms']; ?></td>
</tr>
<?php
}
$response->closeCursor();
?>
</div>
I thank you in advance for all your effort and your help.
Tom.
There's no way we can improve the design and layout of your webpage with the code you've given us. What I can do is write 'better' readable code.
<?php
function tableCell($content)
{
echo '<td align="left">'.$content.'</td>';
}
// database access
require_once('../mysqli_connect.php');
// get all records from the metabolite table
$response = $db->query("SELECT * FROM metabolite");
// start main division
echo '<div id="main">';
// start the table
echo '<table align="center" cellspacing="2" cellpadding="5" border = "1">';
// walk through all the metabolite records
while ($data = $response->fetch())
{
// start a row
echo '<tr>';
// create the cells
tableCell($data['Metabolite_name']);
tableCell('KEGG: '.$data['Synonyms']);
tableCell($data['Synonyms']);
// finish a row
echo '</tr>';
}
// close the table
echo '</table>';
// close main division
echo '</div>';
// close query
$response->closeCursor();
But this is not worth much, the output should remain the same.
if ($response->num_rows > 0) {
while($data = $response->fetch_assoc()) {
echo "<tr><td>" . $data["Metabolite_name"]. "</td></tr>" . ;
}
}
else {
echo "0 results";
}

How to echo a table in two piece separated code in PHP?

Now I wish to construct a list of tables under nested while loop and if-else condition with PHP, the format of the code is as below:
while(){
if (){
..... // extract the data
while(){
construct a table using the data extracted above
}
}
elseif (){
..... // extract the data
while(){
construct a table using the data extracted above
}
}
}
Specifically, in the inner while loop the code is:
while ( $chat = mysqli_fetch_assoc($chatQ))
{
echo
"<table class='table table-hover' >"
."<td>"
.$conver['sender_name']."\t".$chat['sender']."\t".$chat['send_time']."\t".$chat['content']
."</td>"
."<td>"
."<form id='join' action='group_chat.php' method ='POST' accept-charset='UTF-8'>"
// post the group id
."<input type='hidden' name='group_id' id='group_id' value=".$conver['sender_id']."/>"
."<button class='btn btn-default' type='submit'>Enter</button>"
."</form>"
."</td>"
."</table>";
}
But the result is very ugly:
The problem is that the Enter button is associated with each message. But what I want is that after displaying all the messages, there is a Enter button which can direct to the specific group. But I don't know how to separate the code. Could you please do me a favor? Thanks in advance!
You can do something like this:
<?php
$counter = 0;
echo '
<form>
<table>';
while ( $chat = mysqli_fetch_assoc($chatQ)){
$counter++;
echo '
<tr>
<td>
group_id_'.$counter.'
</td>
<td>
<input name="group_id_'.$counter.'" value="'.$conver['sender_id'].'">
</td>
</tr>';
}
echo '
<tr>
<td colspan="2">
<button type="submit">Enter</button>
</td>
</tr>
</table>
</form>';
?>
Also you dont have to limit yourself to echo everything in order by setting variables. See example below:
<?php
$counter = 0;
$data = NULL;
while ( $chat = mysqli_fetch_assoc($chatQ)){
$counter++;
$data .='
<tr>
<td>
group_id_'.$counter.'
</td>
<td>
<input name="group_id_'.$counter.'" value="'.$conver['sender_id'].'">
</td>
</tr>';
}
echo '
<form>
<table>'.$data.'
<tr>
<td colspan="2">
<button type="submit">Enter</button>
</td>
</tr>
</table>
</form>';
?>

Updating a row of SQL with html table

I have the following code:
$sql = "SELECT * FROM Tickets WHERE stat='Open'";
$result = mysql_query($sql);
mysql_close($con);
?>
<!DOCTYPE>
<html>
<body>
<table class="striped">
<tr class="header">
<td>Username</td>
<td>Title</td>
<td>Description</td>
<td>Admin Name</td>
<td>Category</td>
<td>Status</td>
<td>Urgency</td>
<td>Time In</td>
<td> </td>
</tr>
<?php
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>".$row[username]."</td>";
echo "<td>".$row[title]."</td>";
echo "<td>".$row[description]."</td>";?>
<td><select>
<?php
echo "<option value'".$row[admin_name]."'>".$row[admin_name]."</option>";
$sql = mysql_query("SELECT username FROM Users WHERE user_type='admin'");
while ($u = mysql_fetch_array($sql)){
echo "<option value='".$u['username']."'>".$u['username']."</option>";
}
?>
</select></td>
<?php
echo "<td>".$row[category]."</td>";
echo "<td>".$row[stat]."</td>";
echo "<td>".$row[urgency]."</td>";
echo "<td>".$row[time_in]."</td>";
echo "<td><a href='close.php'>Close Ticket</a></td>";
echo "</tr>";
}
?>
</table>
<a href='update.php'>Update</a>
</body>
</html>
I have two links on this page. Both of them need to update a SQL database. The Close ticket link needs to just update the single row, while the update link should update all of them. I am not sure how to get the info from one php to the next. It seems like you can put the individual row information into a Post array for the close ticket link, but I am not sure how. For the update link it needs to take the value of the dropdown in the table and change the admin_name field to that value.

multiple arrays value fetching with session

Insert Is Fine But if I select this value from database All Values are fine but single values fetch array problem I don't know how to solve this task. Please Update this code asap.
This Is Insert Code .....
<?php
if(isset($_POST['sendmessage'])){
$entermessage = $_POST['teachermessage'];
$checkbox_user = $_POST['usernameallcheckbx'];
$arr = implode(',',$checkbox_user);
//$arr2 = explode(',',$arr);
$insert = mysql_query("INSERT into usermessages(fromteacher,toparent,messages) VALUES('".$_SESSION['username']."','$arr','$entermessage')");
if($insert == 1){
echo "<h1>successful</h1>";
}
else{
echo mysql_error();
}
}
?>
<form method="post">
<div style="float:left; width:450px;"><br/><br/>Message: <br/>
<textarea style="width:400px; height:300px;" name="teachermessage"></textarea><br/>
<input type="submit" value="Send" name="sendmessage" /></div>
<div style="float:left; with:200px; padding-top:55px;">
<table>
<tr>
<?php
$select_query1 = mysql_query("SELECT * FROM register_user WHERE teacher='$teachername'");
while($chckbx=mysql_fetch_array($select_query1))
{
?>
<td><?php echo "<input type='checkbox' name='usernameallcheckbx[]' value=". $chckbx['userid']." />"; ?></td>
</tr>
<tr>
<td><?php echo $chckbx['parent_fname']." ".$chckbx['parent_lname']; ?></td>
</tr>
<?php
}
?>
</table>
</div>
</form>
And This Is Select Code....
<h2>Messages</h2>
<?php
$select_query3 = mysql_query("SELECT * FROM usermessages");
$fetch= mysql_fetch_array($select_query3);
$data=$fetch['toparent'];
$arr=explode(',',$data);
//$userids=explode(',',$data);
$sessionshow=$_SESSION['userid'];
$userids=in_array("$sessionshow",$arr);
$select_query2 = mysql_query("SELECT * FROM usermessages WHERE toparent in ('$userids')='".$_SESSION['userid']."'");
?>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<th>Teacher Name</th>
<th>Message</th>
</tr>
<?php
while($fetch_name2=mysql_fetch_array($select_query2))
{
echo "<tr>";
echo "<td>".$fetch_data=$fetch_name2['fromteacher']."</td>";
echo "<td>".$fetch_data=$fetch_name2['messages']."</td>";
echo "</tr>";
}
?>
</table>
I have only put this as an answer to show some incorrect code - remove fetch data from your loop as it doesn't do anything
while($fetch_name2=mysql_fetch_array($select_query2))
{
echo "<tr>";
echo "<td>".$fetch_name2['fromteacher']."</td>";
echo "<td>".$fetch_name2['messages']."</td>";
echo "</tr>";
}
even better is use of a HEREDOC:
while($fetch_name2=mysql_fetch_array($select_query2))
{
echo <<<EOF
<tr>
<td>{$fetch_name2['fromteacher']}</td>
<td>{$fetch_name2['messages']}</td>
</tr>
EOF;
}
I really can't figure out what you're trying to do, but maybe this is the query you want:
SELECT * FROM usermessages WHERE FIND_IN_SET('$sessionshow', toparent)
FIND_IN_SET(str, strlist) searches the comma-separated list in strlist for an element that equals str, and returns the position in the list; if it's not found it returns 0, which counts as false.
I can't see any purpose to any of the code that uses $select_query3.

Categories