While loop within a while loop logically not working in PHP - php

I have this while loop within another while loop in my PHP:
$selecty = mysql_query("SELECT * FROM followers WHERE userid='".$_SESSION['id']."'");
$rowsy = mysql_num_rows($selecty);
echo '<td>'. $table["username"]. '</td>';
echo '<td>';
while ($tables = mysql_fetch_assoc($selecty)) {
if($tables['followerid']!=$table['id']) {
echo ''.'';
} else {
echo ''.'';
}
}
echo '</td>';
echo "<tr>";
This is more of a logic question and whether or not a nested while loop is the right way to do it. What I'm trying to say is if the 'followerid' from 'user followers table' is not the same as the 'id' from users table (which is from the previous loop) - echo the follow button, else echo the following button.
This is working file while I have data in the followers table but If I don't nothing shows (as there are no rows) - How could I implement this in my PHP? So also if there are no rows in 'followers table' echo follow button?

you can try do it like that
$selecty = mysql_query("SELECT * FROM followers WHERE userid='".$_SESSION['id']."'");
$rowsy = mysql_num_rows($selecty);
echo '<td>'. $table["username"]. '</td>';
echo '<td>';
while ($tables = mysql_fetch_assoc($selecty)) {
if($tables['followerid']!=$table['id'] and $tables['followerid'] != '') {
echo '';
} else if($tables['followerid'] =$table['id'] and $tables['followerid'] !='') {
echo '';
} else {
echo what you like here when $tables['followerid'] = ''
}
}
echo '</td>';
echo "<tr>";
edit
class="follow">'.'</a>'
^------------you dont have to make point and single quotes here
$selecty = mysql_query("SELECT * FROM followers WHERE userid='".$_SESSION['id']."'");
$rowsy = mysql_num_rows($selecty);
echo '<table><tr>';
echo '<td>'. $table["username"]. '</td></tr>';
if ($tables['followerid'] !== ''){
while ($tables = mysql_fetch_assoc($selecty)) {
echo '<tr><td>';
if($tables['followerid']!=$table['id'] and $tables['followerid'] != '') {
echo '</td></tr>';
} else if($tables['followerid'] =$table['id'] and $tables['followerid'] !='') {
echo '</td></tr>';
} else {
echo "what you like here </td></tr>";
}
}
}
else {
echo "do your code here " ;
}
echo "</table>";

Put a boolean (FALSE) at the start of the 'followers' loop such that if it gets crossed make it TRUE. If you get outside the loop and it's still FALSE then add the button anyway.
$trip = FALSE;
while ($tables = mysql_fetch_assoc($selecty)) {
if($tables['followerid']!=$table['id']) {
echo ''.'';
} else {
$trip = TRUE;
echo ''.'';
}
}
if( !$trip ) echo '<a href="#" data-userid="'.$_SESSION['id'].'" class="follow">'.'</a

Related

how to correctly accommodate the values?

I would like how to put the second result of the second query. the value is shows under row and I want that value is in front of the first result query.
The result should be shown where it is marked in red
$resultados=$reporte->facturaCompleto();
while($fila = mysqli_fetch_array($resultados))
{
$bandera=0;
echo "<tr style=''>";
echo '<td>'.utf8_encode($fila["factura"]).'</td>';
echo '<td>'.utf8_encode($fila["rfc_emisor"]).'</td>';
echo '<td></td>';
echo '<td></td>';
echo '</tr>';
//
$id_documento=$fila["id_documento"];
$reporte->set('id_documento',$id_documento);
$reporte->contador();
$contador=$reporte->get('contador');
$id_documento=$fila["id_documento"];
$reporte2->set('id_documento',$id_documento);
$resultadosmov = $reporte2->movimientos();
while($fila2 = mysqli_fetch_array($resultadosmov))
{
echo'<tr>';
echo '<td></td>';
echo '<td></td>';
echo '<td>'.utf8_encode($fila2["no_parcialidad"]).'</td>';
echo '<td>'.utf8_encode($fila2["importe_total"]).'</td>';
echo '</tr>';
}
}
echo '</table>';
echo "</td></tr></table>";
Echo all the columns when processing the second query.
$resultados=$reporte->facturaCompleto();
while($fila = mysqli_fetch_array($resultados))
{
$bandera=0;
//
$id_documento=$fila["id_documento"];
$reporte->set('id_documento',$id_documento);
$reporte->contador();
$contador=$reporte->get('contador');
$id_documento=$fila["id_documento"];
$reporte2->set('id_documento',$id_documento);
$resultadosmov = $reporte2->movimientos();
if ($resultadosmov->num_rows > 0) {
while($fila2 = mysqli_fetch_array($resultadosmov))
{
echo "<tr>";
echo '<td>'.utf8_encode($fila["factura"]).'</td>';
echo '<td>'.utf8_encode($fila["rfc_emisor"]).'</td>';
echo '<td>'.utf8_encode($fila2["no_parcialidad"]).'</td>';
echo '<td>'.utf8_encode($fila2["importe_total"]).'</td>';
echo '</tr>';
// Make 1st two columns blank in additional rows
$fila["factura"] = "";
$file["rfc_emisor"] = "";
}
} else {
echo "<tr style=''>";
echo '<td>'.utf8_encode($fila["factura"]).'</td>';
echo '<td>'.utf8_encode($fila["rfc_emisor"]).'</td>';
echo '<td></td>';
echo '<td></td>';
echo '</tr>';
}
}
BTW, what is the $bandera variable for? It's set but never used.
It would probably be even better if you could join the two queries, instead of doing queries in a loop.

how to group the data having similar values in php?

I have a table in the database named 'transactions'. I want to list out the values from this table. The result should be displayed in HTML table format. The rows in the resulted table should be grouped as per the amount.There is a column named 'amount' in the 'transactions' table.
Here is my code:
$s1 = DB::table('transactions')
->select(DB::raw("GROUP_CONCAT(selected_seats SEPARATOR '') as selected_seats"),'userid','amount','show_id')
->where("show_id","=",$s)
->groupBy('userid')
->groupBy('amount')
->orderBy('userid','ASC')
->orderBy('amount', 'DESC')
->get();
I am retrieving the values from $s1 variable through loop.
Following is the output:
and i want the result like this:
Please click on the links given above. I am new to this forum so its not allowing me to add images in the question. Kindly help.
Here is the entire code:
if($s1 != null)
{
echo "<div class='panel-body'>";
echo "<table class='table table-responsive'>"; $c = 1;
echo "<th>Drama Title</th>";
echo "<th>Show Date</th>";
echo "<th>Seat booked</th>";
echo "<th>Amount</th>";
echo "<th>User</th>";
for($i=0;$i<count($s1);$i++)
{
echo "<tr><td>".$shows1[0]->show_title."</td>";
echo "<td>".$shows[0]->show_date."</td>";
echo "<td>";
echo $s1[$i]->selected_seats;
echo "</td>";
/*echo $s1[$i]->userid."<br/>";
echo $s1[$i]->amount."<br/>";*/
$transactions = DB::table('transactions')->where('userid',$s1[$i]->userid)->where('show_id',$s1[$i]->show_id)->get();
//var_dump($transactions);
$total_amount = 0;
//echo "<pre>Users<br/>"; var_dump($transactions);
foreach ($transactions as $transaction)
{
//echo "userid ".$s1[$i]->userid." "."show id: ".$transaction->show_id." "."<br/>";
// echo "amount: ".$transaction->amount." ";
$amount = $transaction->amount;
$total_amount = $total_amount + $amount; //echo $amount."<br/>";
$c = $c+1;
//echo "no. of seats:".$c;
$users = DB::table('users')->where('id',$s1[$i]->userid)->get();
}
echo "<td>".$total_amount."</td>";
//echo $s1[$i]->userid."<br/>";
//echo "<td>".$users[0]->name."</td>";
//echo "<pre>"; var_dump($users);
echo "</td>";
if(isset($users[0]))
{
//echo "values are set";
echo "<td>".$users[0]->name."</td></tr>";
}
else
{
//echo "null value";
continue;
}
}
/*echo $shows[0]->show_date."<br/>";
echo $shows[0]->show_title;*/
//echo "<pre>"; var_dump($s1);
//echo "<td>".$users[0]->name."</td>";
//echo "</tr>";
echo "</table>";
echo "</div>";
?>
}
else
{
echo "No records found";
}
Easiest way I think is calculate amounts in the loop you are printing data or readying data to send to a view. Since your data sorted by user_id, you always can change amount variable in the loop when user_id is changing. You can use count(explode($seat_variable)) to get number of seats in a single run of the loop. Look at the example code below.
$num_seat = 0; $amount = 0; $running_user_id = -1;
foreach ($row as $entry) {
...
if ($running_user_id != $entry['user_id']) { // check if the same user
$running_user_id = $entry['user_id'];
$num_seat = 0; $amount = 0; // resetting variable values for seperate user.
}
$num_seat += count(explode($entry['selected_seats']));
$amount += $entry['amount'];
...
}
And I assume you have missing data like emails in the query.
Code update after questioner added his code.
if($s1 != null) {
echo "<div class='panel-body'>";
echo "<table class='table table-responsive'>"; $c = 1;
echo "<tr>";
echo "<th>Drama Title</th>";
echo "<th>Show Date</th>";
echo "<th>Seat booked</th>";
echo "<th>Amount</th>";
// echo "<th>User</th>";
echo "</tr>";
$category = ""; $num_seats = 0;
for ($i=0; $i<count($s1); $i++) {
if ($category != $amount) {
if ($i > 0) { // print totals
echo "<tr>
<td colspan='3' align='right'>Total</td>
<td>".$num_seats."</td>
<td>".($num_seats * $amount)."</td>
</tr>";
echo "<tr><td colspan='5'> </td></tr>"; // empty row after totals printed
$num_seats = 0; //resetting number of seats per category
}
echo "<tr><td colspan='5'><h2>Category : ".$amount."</h2></td></tr>"; // printing category line in the given table
$category = $amount; // this logic is to prevent category line printing for each row
}
$transactions = DB::table('transactions')->where('userid',$s1[$i]->userid)->where('show_id',$s1[$i]->show_id)->get();
echo "<tr>";
$users = DB::table('users')->where('id', $s1[$i]->userid)->get();
// Check below values are correct or not
echo "<td>".$users[0]->name."</td>";
echo "<td>".$s1[$i]->userid."</td>";
echo "<td>".$s1[$i]->email."</td>"; // get user's email property here
echo "<td>".$s1[$i]->selected_seats."</td>";
$num_seats += count(explode(',', $s1[$i]->selected_seats));
echo "<td> </td></tr>"; // empty colomn for amount and the row end
}
echo "</table>";
echo "</div>";
}

format when column has specific name,

the roblem is where there is the punch commentator
i need when the column has INTER name or OUTER name to format the content of the $cell
with $cell=number_format($cell,2,',','.')
i'm just starting using php so don be too specific thanks
<?php
// printing table rows
$rigapadi = 1 ;
while($row = mysql_fetch_row($result))
{
echo "<tr>";
$rigapadi=$rigapadi+1;
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
if ($rigapadi % 2 == 0) {
# if column name = 'INTER' or 'OUTER' $cell = number_format($cell, 2, ',', '.');
echo "<td align=\"center\">$cell</td>";
} else {
echo "<td bgcolor=\"#E9EEF5\" align=\"center\">$cell</td>";
}
echo "</tr>\n";
}
mysql_free_result($result);
echo "</table>";
echo "<p/>";
?>
The mysql_ are obsoltes. You must not use them. And please indent your code properly when you ask for help.
<?php
$rigapadi = 1;
while($row = mysql_fetch_assoc($result)) {
echo '<tr>';
$rigapadi++;
foreach($row as $name => $cell) {
if($rigapadi % 2 === 0) {
if($name === 'INTER' || $name === 'OUTER') {
echo '<td align="center">' . number_format($cell, 2, ',', '.') . '</td>';
} else {
echo '<td align="center">' . $cell . '</td>';
}
} else {
echo '<td align="center" bgcolor="#E9EEF5">' . $cell . '</td>';
}
}
echo "</tr>\n";
}
mysql_free_result($result);
echo "</table>";
?>
Note that I use fetch_assoc to get the $name.
PS: <p/> does not exists and align and bgcolor and not valids but acceptable if this is a HTML code for an e-mail.

PHP Ranking function with TIES

So I have a function that takes a number and outputs it as a placement. How do I go about making the function take in consideration ties. I have a ranking database and this php code echos out rankings on a table. right now it ranks but it doesn't consider ties. How do i go about doing this
<?php
function addOrdinalNumberSuffix($num) {
if (!in_array(($num % 100),array(11,12,13))){
switch ($num % 10) {
// Handle 1st, 2nd, 3rd
case 1: return $num.'st';
case 2: return $num.'nd';
case 3: return $num.'rd';
}
}
return $num.'th';
}
?>
<?php
$link = mysqli_connect("localhost", "citricide", "321213123Lol", "juneausmashbros");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM rankings ORDER BY points DESC";
$result = mysqli_query($link, $query);
echo '<article class="content grid_6 push_3">';
echo '<h1>';
echo 'Project M Summer Ranbat Rankings';
echo '</h1>';
echo '<section>';
echo '<center>';
echo '<table style="width:400px" class="rankslist">';
echo '<tr>';
echo '<th width="15%"><b>Rank</b></th>';
echo '<th width="45%"><b>Name</b></th>';
echo '<th width="45%"><b>Alias</b></th>';
echo '<th width="15%"><b>Points</b></th>';
echo '</tr>';
$ass = 0;
while($row = $result->fetch_array()) {
$ass++;
echo '<tr>';
if ($ass == 1) {
echo ' <center><td><B><font color=#FFD700>';
} else if ($ass == 2) {
echo ' <center><td><B><font color=#CCCCCC>';
} else if ($ass == 3) {
echo ' <center><td><B><font color=#cd7f32>';
} else {
echo '<td>';
}
echo addOrdinalNumberSuffix($ass);
echo ' </font></B</td></center>';
echo ' <td>'.$row['name'].'</td>';
echo '<td>'.$row['alias'].'</td>' ;
echo '<td>'.$row['points'].'</td>';
echo '</tr>';
}
echo '</table>';
echo '</center>';
echo '</section>';
echo '</article>';
?>
It seems like you need additional variables to track the rank and the previous value. By doing so, you can handle ties.
For example:
$ass = 0; // current record count
$rank = 0; // rank
$last_points = NULL; // variable to store last ranked value
while($row = $result->fetch_array()) {
$ass++;
// check if value changes and reset rank if it does
if ($row['points'] !== $last_points) {
$rank = $ass;
$last_points = $row['points'];
}
echo '<tr>';
if ($rank == 1) {
echo ' <center><td><B><font color=#FFD700>';
} else if ($rank == 2) {
echo ' <center><td><B><font color=#CCCCCC>';
} else if ($rank == 3) {
echo ' <center><td><B><font color=#cd7f32>';
} else {
echo '<td>';
}
echo addOrdinalNumberSuffix($rank);
echo ' </font></B</td></center>';
echo ' <td>'.$row['name'].'</td>';
echo '<td>'.$row['alias'].'</td>' ;
echo '<td>'.$row['points'].'</td>';
echo '</tr>';
}
So say your points looked like this:
100
100
90
80
The $rank value would be:
1
1
3
4

Populate an html table columwise with mysql data

I have a MySQL query that returns data using PHP.
My problem is that I need to populate my html table (with 3 columns) with the data returned by the query but the data should be populated Columnwise.
Like first the first column should be populated .. then the second and finally the third one.
Also I would like to know that is it possible to do so for an unlimited set of data?
Following the screen shot of the desired layout
you can use while.
<table>
$sql=mysql_query("select * from table");
while($s=mysql_fetch_array($sql))
{
$x=$s["x"];
<tr>
<td ><?php echo $x; ?></td>
<td ><?php echo $y; ?></td>
<td ><?php echo $z; ?></td>
</tr>
}
</table>
guybennet's answer is correct but if you want it to work for an unlimited amount of columns you could do this: (I also threw in some column headers for readability)
echo '<table>';
$counter = 0;
$result = mysql_query("select * from table");
while($row = mysql_fetch_array($result)) {
$counter++;
if($counter == 1) {
echo '<tr>';
foreach($row as $key => $val) {
echo "<th>$key</th>";
}
echo '</tr>';
}
echo '<tr>';
foreach($row as $key => $val) {
echo "<td>$val</td>";
}
echo '</tr>';
}
echo '</table>';
Also of course you should use mysqli or PDO I'm just showing a quick example.
If you don't care about how it's organized, you can try something like this:
echo "<table><tr>";
$i=0;
while($row = mysql_fetch_array($sql))
{
echo "<td>".$row[0]."</td>\n";
$i++;
if($i==3)
{
echo "</tr>\n<tr>";
$i=0;
}
}
echo "</tr></table>";
Otherwise, I'd suggest putting it all into an array and then putting it into the table.
$data = array();
$result = mysql_query("SELECT * FROM your_table");
while ($row = mysql_fetch_array($result)) {
$data[] = $row;
}
$itemsAmount = count($data);
$ceilAmount = ($itemsAmount - $itemsAmount % 3) / 3;
$lastAmount = $itemsAmount % 3;
$firstArray = array_slice($data, 0, $itemsAmount);
$secondArray = array_slice($data, 0, $itemsAmount*2);
$thirdArray = array_slice($data, 0, $lastAmount);
$output = "<table>";
foreach ($data as $key => $value) {
$output .= "<tr>";
$output .= "<td>" . $firstArray[$key][0] . "</td>";
$output .= "<td>" . $secondArray[$key][0] . "</td>";
if (empty($thirdArray[$key])) {
$str = '';
} else {
$str = $thirdArray[$key][0];
}
$output .= "<td>" . $str . "</td>";
$output .= "</tr>";
}
$output .= "</table>";
echo $output;
You need to check all the results returned, then print them as you won't print in order:
First get an array with all the results
<?php
$sql= mysql_query('SELECT * FROM table');
$num= mysql_affected_rows($sql);
$items = array();
$i=0;
while($item=mysql_fetch_array($sql)){
$items[++$i]=$item['data'];
}
Now start printing
int $num_rows;
$num_rows=$num%3;
echo '<table>';
for ($i=0;$i<$num_rows;$i++){
echo '<tr>';
for ($j=0;$j<2,$j++){
$n=$i+1+($j*$num_rows);
if($items[$n]!==null)
echo '<td>'.$items[$n].'</td>';
else
echo '<td></td>';
}echo '</tr>';
}echo'</table>';
?>

Categories