How to echo a table in two piece separated code in PHP? - 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>';
?>

Related

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.

How do I display a query in PHP table

My code
<?php
include('ConnectToDb.php');
$query = "SELECT * FROM News WHERE NewsFlag = 1 ORDER BY PostDate DESC";
$arrCount = -1;
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$ID=$row['ID'];
$PostDate = $row['PostDate'];
$NewsHeader = stripslashes($row['NewsHeader'])
;
$NewsStart = stripslashes($row['NewsStart'])
;
echo "<hr>";
echo "<div>". date('j F Y',strtotime($PostDate)). "</div>";
echo "<p>";
$news_id = strval(sprintf("%1$04d",$ID));
$array = scanImageFolder("newsImages/newsThumbs",$news_id);
if(count($array)>0) {
echo "<img src='". $array[0]. "' alt='' />";
}
echo "<h2 style='text-align:center'><u><a href='latestnews_full.php?ID=$ID'>". $NewsHeader. "</a></u></h2>";
echo "<div style='text-align:left'><h3>";
echo $NewsStart. " ......<a href='latestnews_full.php?ID=$ID'>(more)</a><br />";
echo "<div style='text-align:center'>";
echo "</div>";
echo "</h3></div>";
}
?>
displays my data nicely on four lines with date at the top, then a picture, title and then description.
However, I want to display the data as a table like this
<table style="width: 100%">
<tr>
<td colspan="2">postDate here</td>
</tr>
<tr>
<td rowspan="2">picture here</td>
<td>newsHeader here</td>
</tr>
<tr>
<td>newsStart here</td>
</tr>
</table>
I'm not sure how to echo the table cells correctly and all of my attempts so far have resulted in a white page. Could anyone please enlighten me?
I'd suggest you to make your logic separated from your presentable part. Close the PHP tag once you are ready fetching the results, assigning var's etc, then:
<table style="width: 100%">
<?php
//yourcode
//...
//...
$NewsStart = stripslashes($row['NewsStart']);
$news_id = strval(sprintf("%1$04d",$ID));
$array = scanImageFolder("newsImages/newsThumbs",$news_id);
?>
<tr>
<td colspan="2"><?= date('j F Y',strtotime($PostDate)) ?></td>
</tr>
<tr>
<?php
if(count($array)>0) {
?>
<td rowspan="2"><img src='<?= $array[0] ?>' alt='' /></td>
<?php } ?>
<td><?= $NewsHeader ?></td>
</tr>
<tr>
<td><?= $NewsStart ?> </td>
</tr>
<?php } ?>
</table>
However, it's again not so clear, and I would suggest using a template engine. If you want I can post a code with assigning vars to Smarty and output your presentation in Smarty template

While loop and mysql_fetch_assoc on one query?

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

Getting the value from first cell in a row to submit using Javascript

I create a table using PHP from a database, meaning the size of the table and values vary.
The table creation:
<table>
<thead>
<tr>
<th>Ticket</th>
<th>Empresa</th>
<th>Requerente</th>
<th>Motivo</th>
<th>Data</th>
<th>Hora</th>
</tr>
</thead>
<tbody>
<form name="goTicket" action="resolver.php" method="POST" >
<?php
$sql = "QUERY";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<tr onmouseover=\"this.style.background='#EFF5FB';this.style.cursor='pointer'\"
onmouseout=\"this.style.background='white';\" onclick=\"javascript: submitform()\">";
echo "<td>$row[Ticket]</td>";
echo "<input type='hidden' name='_ticket' value='$row[Ticket]' />";
echo "<td>$row[Empresa]</td>";
echo "<td>$row[Requerente]</td>";
echo "<td>$row[Motivo]</td>";
echo "<td>$row[Data]</td>";
echo "<td>$row[Hora]</td>";
echo "</tr>";
}
echo "</form>";
echo "<tr><td colspan='6' style='text-align: center;'><form action='adminmenu.php' ><br /><input type='submit' name='woot' value='Main Menu' /></form></td></tr>";
echo "<tbody>";
echo "</table>";
?>
The Javacript function used to submit is this one:
<script type="text/javascript">
function submitform()
{
document.forms["goTicket"].submit();
}
</script>
Now whenever I click on a row it takes to the appropriate page "resolver.php" but always sends the most recent data, from last time the while was executed.
I need the value from the first cell, or the hidden input tag, that contains what I need, from the row I click.
Thank you.
Full suggestion
<script type="text/javascript">
function submitform(ticket) {
document.goTicket.elements["_ticket"].value=ticket;
document.goTicket.submit();
}
</script>
<table>
<thead>
<tr>
<th>Ticket</th>
<th>Empresa</th>
<th>Requerente</th>
<th>Motivo</th>
<th>Data</th>
<th>Hora</th>
</tr>
</thead>
<tbody>
<form name="goTicket" action="resolver.php" method="POST" >
<input type="hidden" name="_ticket" value="" />
<?php
$sql = "QUERY";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
?>
<tr onmouseover="this.style.background='#EFF5FB';this.style.cursor='pointer'"
onmouseout="this.style.background='white';"
onclick="submitform('<?php echo $row[Ticket]; ?>')">
<td><?php echo $row[Ticket]; ?></td>
<td><?php echo $row[Empresa]; ?></td>
<td><?php echo $row[Requerente]; ?></td>
<td><?php echo $row[Motivo]; ?></td>
<td><?php echo $row[Data]; ?></td>
<td><?php echo $row[Hora]; ?></td>
</tr>
<?php } ?>
</form><!-- not really nice -->
<tr><td colspan="6" style="text-align: center;"><form action="adminmenu.php" >
<br /><input type="submit" name="woot" value="Main Menu" /></form></td></tr>
</tbody>
</table>
Your problem is that you're just submitting the form without any reference to what was clicked. All the hidden inputs have the same name so the form just sends the last one.
Try the following:
echo "<tr onmouseover=\"this.style.background='#EFF5FB';this.style.cursor='pointer'\" onmouseout=\"this.style.background='white';\" onclick=\"javascript: submitform('$row[Ticket]')\">";
// delete this from while:
// echo "<input type='hidden' name='_ticket' value='$row[Ticket]'/>";
// and instead add before </form> with value=""
Then change your javascript to change the value before submitting:
function submitform(val) {
document.forms["goTicket"].elements["_ticket"].value = val;
document.forms["goTicket"].submit();
}
Kudos to mplungjan also got this as I was typing!
If I see good ... Yo set form with many of hidden inputs with same name ... what you want with this... of course it return last value ...
you have to changing names in loop and then call exact name of input

Unexpected output when comparing database column to variable

I have code which retrieves information about players from a MySQL database. I want to apply a special case to the HTML output if their ranking changes. I want it to look like this: http://i27.tinypic.com/f406tz.png
But i cant get it to be like i want, instead it prints the rank on every row:
$old_rank = '';
while ($g = mysql_fetch_object($q)) {
if ($g->rankname != $old_rank) {
echo "<tr><td>$g->rankname</td>\n";
$old_rank = "<tr><td> </td>\n";
}
echo " <td>$g->name</td></tr>\n";
}
What I want:
<tr>
<td>One</td>
<td>Kraven the Hunter</td>
</tr>
<tr>
<td> </td>
<td>Kull the Conqueror</td>
</tr>
<tr>
<td> </td>
<td>Zazi The Beast</td>
</tr>
<tr>
<td>Vice-leader</td>
<td>Igos du Ikana</td>
</tr>
<tr>
<td> </td>
<td>Saint Sinner</td>
</tr>
<tr>
<td> </td>
<td>Midvalley the Hornfreak</td>
</tr>.......................
What I get:
<tr><td>One</td>
<td>Tester</td></tr>
<tr><td>One</td>
<td>Kraven the Hunter</td></tr>
<tr><td>One</td>
<td>Kull the Conqueror</td></tr>
<tr><td>One</td>
<td>Zazi The Beast</td></tr>
<tr><td>Vice-Leader</td>
<td>Midvalley the Hornfreak</td></tr>
<tr><td>Vice-Leader</td>
<td>Saint Sinner
</td></tr>
<tr><td>Vice-Leader</td>
<td>Igos du Ikana</td></tr>
$old_rank is never equal to $g->rankname because the way you are setting $old_rank, it will contain HTML tags, and the $g->rankname that you get from the DB will never have HTML tags.
Try changing your if statement to something like this:
if ($g->rankname != $old_rank) {
echo "<tr><td>$g->rankname</td>\n";
$old_rank = $g->rankname;
} else {
echo "<tr><td> </td>\n";
}
It prints the rank name if it's a new rank name, else it prints empty space.
The following (notwithstanding typos) separates out the display logic from the database loop. This has the advantages:
- You don't need to depend on the order of the results returned
- You don't need to maintain dodgy logic (like 'old_rank')
- You can display them more nicely (with a rowspan for repeated ranks
I believe the total code is more compact too.
// fill ranks array
$ranks = array();
while ( $g = mysql_fetch_object($q) ) {
if ( !in_array($g->rankname, $ranks) ) {
$ranks[htmlentities($g->rankname)] = array();
}
$ranks[$g->rankname][] = htmlentities($g->name);
}
// do other program logic here
// end of program
?>
<!-- display the page -->
<table>
<tr>
<th>Rank</th><th>Users</th>
</tr>
<?php foreach($ranks as $rankName => $userList): ?>
<tr>
<td rowspan="<?php echo (string)sizeof($userList); ?>">
<?php echo $rankName; ?>
</td>
<td> <?php echo implode('</td></tr><tr><td>', $userList); ?> </td>
</tr>
<?php endforeach; ?>
</table>
I prefer breaking things up a bit more than that. Keeping things separate makes it easier to modify. This should work.
$old_rank = '';
while ($g = mysql_fetch_object($q)) {
echo '<tr>' . "\n";
echo '<td>';
if ($g->rankname != $old_rank) {
$old_rank = $g->rankname;
echo $old_rank;
} else {
echo ' ';
}
echo '</td>';
echo '<td>' . $g->name . '</td>' . "\n";
echo '</tr>' . "\n";
}

Categories