Looping problems in php - php

So I'm making this system where you can reserve a seat but when I'm doing a check if the seat is already reserved it screws up(Means that I'm too bad with loops). I have 3 test users in my database and it echoes the seats as many times as there are users. And it even gets the reserved seats correctly coloured.
$sql = "SELECT * FROM users";
$result = mysql_query($sql);
$list = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$reserved = $row["seat"];
$list[] = $reserved;
}
echo '<div id="top-section">';
for($i = 0; $i < 44; $i++) {
$seatCount++;
foreach($list as $obj) {
if($seatCount == $obj) {
echo '<div id="seat_'.$seatCount.'" class="seat reserved">'.$seatCount.'</div>';
}
else {
echo '<div id="seat_'.$seatCount.'" class="seat available" onclick="selectSeat('.$seatCount.');">'.$seatCount.'</div>';
}
}
}
echo '</div>';
And the result is this: http://i.gyazo.com/d10e787cea7028b46c716ac41766456a.png (I have three divs of seats and only done the loop on the top part so don't mind the 45 - 68 since they are correct). How do I make it so it only posts the seats once?

You don't need to have that inner foreach statement, if I think I know what you're going for.
There's two things wrong with your code, though.
Firstly, this statement is a little redundant
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$reserved = $row["seat"];
$list[] = $reserved;
}
Change it to this, you know, for simplicity:
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$list[] = $row["seat"];
}
Then, the loop can look a little something like this (which uses in_array instead of another loop):
for($i = 0; $i < 44; $i++) {
$seatCount++;
if(in_array($seatCount, $list)) {
echo '<div id="seat_'.$seatCount.'" class="seat reserved">'.$seatCount.'</div>';
} else {
echo '<div id="seat_'.$seatCount.'" class="seat available" onclick="selectSeat('.$seatCount.');">'.$seatCount.'</div>';
}
}
Then, this way, the $seatCount variable will be looked for in the user seats and if it is, it will show the reserved seat and if not will just show a selectable seat.

Your foreach ($list as $obj) is inside the loop. You have three reservations, so it's printing the seat three times. You need to move this outside the loop.

Use in_array():
for ($i = 0; $i < 44; $i++) {
if (in_array($i, $list)) {
echo '<div id="seat_'.$seatCount.'" class="seat reserved">'.$seatCount.'</div>';
}
else {
echo '<div id="seat_'.$seatCount.'" class="seat available" onclick="selectSeat('.$seatCount.');">'.$seatCount.'</div>';
}
}
Even better would be to make $list use the reserved seats as keys, not values:
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$reserved = $row["seat"];
$list[$reserved] = true;
}
Then your second loop could use:
if (isset($list[$i]))

You could make something like this:
$sql = "SELECT * FROM users";
$result = mysql_query($sql);
$list = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$reserved = $row["seat"];
$list[$reserved] = 1;
}
echo '<div id="top-section">';
for($i = 0; $i < 44; $i++) {
$seatCount++;
if(isset($list[$seatCount]) AND $list[$seatCount] == 1) {
echo '<div id="seat_'.$seatCount.'" class="seat reserved">'.$seatCount.'</div>';
}
else {
echo '<div id="seat_'.$seatCount.'" class="seat available" onclick="selectSeat('.$seatCount.');">'.$seatCount.'</div>';
}
}
echo '</div>';

You should use in_array() and remove one foreach loop.
<?php
$list = array(1,2,5);
echo '<div id="top-section">';
for($i = 0; $i < 44; $i++) {
if(in_array($i,$list)) {
echo '<div id="seat_'.($i+1).'" class="seat reserved">'.($i+1).'</div>';
}
else {
echo '<div id="seat_'.($i+1).'" class="seat available" onclick="selectSeat('.($i+1).');">'.($i+1).'</div>';
}
}
echo '</div>';
?>
Demo: https://eval.in/201702

Related

Warp two row with a class after query

I want to warp every two row with a class. So I saw some guideline from here and googling and found foreach array_chunk to do this. And I tried as below which can't display any result. Without foreach its work well. Were is my wrong here please?
In the above picture that I want to do; my every two category warp with a class. And add a divider after each top category.
Here is my tried:
echo '<ul class="dropdown-menu dropdown-menu-large row">';
$sql = "SELECT id,name FROM main_cata ORDER BY id ASC";
$execute = $dbh->query("$sql");
$rowcount = $execute->num_rows ;
$row = $dbh->query($sql) ;
while ($row = $execute->fetch_assoc()) {
foreach (array_chunk($row, 2, true) as $array){
echo'<li class="col-sm-3">';
foreach($array as $rows){
echo '<ul><li class="dropdown-header">'.$rows->name.'</li>';
$sql2 = "SELECT id,name,page FROM catagory WHERE m_cata = '".$rows->id."' ORDER BY id ASC";
$execute2 = $dbh->query("$sql2");
$rowcount2 = $execute2->num_rows ;
$row = $dbh->query($sql) ;
while ($row = $execute2->fetch_assoc()) {
$cid = $row['id'];
$cname = $row['name'];
$page = $row['page'];
echo '<li>'.$cname.'</li>';
}
echo '<li class="divider"></li></ul>';
}
echo '</li>';
}
}
echo '</ul>';
while ($row = $execute->fetch_assoc()) {
fetch_assoc returns 1 row (id, name) from the query, then you are using the result and spliting in 2 (https://secure.php.net/manual/pt_BR/mysqli-result.fetch-assoc.php), What you can do is, make a counter instead of the array chunk that resets every time it reachs 2.
foreach (array_chunk($row, 2, true) as $array){
The content of $row is, for example, array('id' => 1, 'name' => 'Category 1').
foreach($array as $rows){
You are iterating again without needing to.
A simple version:
counter = 0;
echo "<ul>";
while (row = execute->fetch_assoc()) {
if (counter == 0) {
echo "init li";
}
echo "subinit li";
get subcategories
while (row2 = execute2->fetch_assoc()) {
print content
}
echo "subend li";
if (counter == 2) {
counter == 0;
echo "end li";
} else {
counter++;
echo "divider";
}
}
echo "</ul>";

It won't loop in a foreach or while

I'm trying to make this take 6 times, and then roll over into another row. I'm sure there's a better way of going about this, and that's probably why mine doesn't work.
However, when I use the foreach() it displays nothing, and when I use the while() the page breaks completely. The headers don't send, and php_error doesn't catch it.
All the queries work just fine, it's the display that's causing issues.
Perhaps you guys can help?
public static function DisplayInv($user) {
$user = users::lookup($user);
$sql = mysql_query("SELECT * from `inventory` where `userid`='{$user['id']}'");
$limit = 6;
$count = 0;
$fetch = mysql_fetch_array($sql) or die('Error: '.mysql_error());
while($count <= 7) {
print "<div class='row-fluid show-grid'>";
foreach($fetch as $items) {
$getItem = self::ItemInfo($items['itemid']);
print "<span class='span2'><b>{$getItem['name']}</b><br />{$getItem['description']}<br /><b>Power: {$getItem['power']}</b></span>";
$count++;
}
/* while($items = mysql_fetch_array($sql)) {
$getItem = self::ItemInfo($items['itemid']);
print "<span class='span2'><b>{$getItem['name']}</b><br />{$getItem['description']}<br /><b>Power: {$getItem['power']}</b></span>";
$count++;
}*/
print "</div>";
if($count == 6) {
$count = 0;
}
}
}
I guess you are looking for something like this?
public static function DisplayInv($user) {
$user = users::lookup($user);
$sql = mysql_query("SELECT * from `inventory` where `userid`='{$user['id']}'");
$limit = 6;
$count = 0;
print "<div class='row-fluid show-grid'>";
while($items = mysql_fetch_array($sql)) {
$getItem = self::ItemInfo($items['itemid']);
print "<span class='span2'><b>{$getItem['name']}</b><br />{$getItem['description']}<br /><b>Power: {$getItem['power']}</b></span>";
if($count == $limit){
print "</div><div class='row-fluid show-grid'>";
$count = 0;
}else{
$count++;
}
}
print "</div>";
}

How can I check the value of the Next Row while looping using PHP/MYSQL?

I got previousRow of record using this code
<?php
$previousRow = array();
while ($temp = mysql_fetch_row($res2))
{
echo "<br>currentRow:".$temp[1];
echo "previousRow:".$previousRow[1];
$previousRow = $temp;
}
?>
oupout
currentRow:1previousRow:
currentRow:5previousRow:1
currentRow:6previousRow:5
currentRow:7previousRow:6
currentRow:8previousRow:7
How can I check the value of the next row replaced by Previous Row ?
Any help would be grateful.
If I get you correctly, then something like this would help?
$previousRow = array();
$currentRow = mysql_fetch_row($res2);
while ($currentRow) {
$nextRow = mysql_fetch_row($res2);
echo "<br>currentRow:".$currentRow[1];
echo "previousRow:".$previousRow[1];
echo "nextRow:".$nextRow[1];
$previousRow = $currentRow;
$currentRow = $nextRow;
}
Please try code given below.
$res = array();
while ($result = mysql_fetch_row($r)) {
$res[] = $result;
}
echo "<pre>";
foreach($res AS $index=>$res1){
echo "Current".$res1[1];
echo " Next" . $res[$index+1][1];
echo " Prev" . $res[$index-1][1]; echo "<br>";
}
thanks
I'd collect all the rows first, then walk through them with a for:
<?php
$rows = array();
while ($temp = mysql_fetch_row($res2))
{
$rows[] = $temp;
}
$rowCount = count($rows);
for ($i = 0; $i < $rowCount; $i++) {
echo "<br>currentRow:".$rows[$i][1];
if ($i > 0) {
echo "previousRow:".$rows[$i - 1][1];
}
if ($i + 1 < $rowCount - 1) {
echo "nextRow:".$rows[$i + 1][1];
}
}
?>

php mysql_fetch_array every 25 items wrap a div

I want to mysql_fetch_array 100 items from mysql database. then every 25 items wrap a div.
also, I make a total items result check.
My code as below, but it will add <div> to every item, no as my require. So how to make it easier? Thanks.
if (mysql_num_rows($result) != 0) {
$total = mysql_num_rows($result);
$num = 1;
while ($row = mysql_fetch_array($result)) {
if ($num === 1) {
echo '<div>';
}
echo $row['title'] . '<br />';
if ($total < 26) {
echo '</div>';
}
else {
if ($num === 26) {
echo '<div>';
}
if ($total < 51) {
echo '</div>';
}
else {
if ($num === 51) {
echo '<div>';
}
if ($total < 76) {
echo '</div>';
}
else {
if ($num === 75) {
echo '<div>';
}
if ($total < 101) {
echo '</div>';
}
}
}
}
$num++;
}
}
You can use the mod operator.
See: http://php.net/manual/en/internals2.opcodes.mod.php
echo '<div>';
while($row = mysql_fetch_array($result)){
....
if (($num % 25) === 1) { echo '</div><div>' }
$num++;
}
echo '</div>';
Try This...
if(mysql_num_rows($result)!=0){
$total = mysql_num_rows($result);
$num=1;
while($row = mysql_fetch_array($result)){
if($num===1)
echo '<div>';
echo $row['title'].'<br />';
if($num==25){
echo '</div>';
$num=1;
}
$num++;
}
}
use the mod operator.
$num =1;
while($row = mysql_fetch_array($result)){
if (($num % 25) === 1) { echo '<div>' }
-------here data ----
if (($num % 25) === 0) { echo '</div>' }
$num++;
}
My advice is to separate your concerns... Give it a shot more like this:
// first get all your data.
$results = array();
while($row = mysql_fetch_array($result)){
$results[] = $row;
}
// now you have an array of all of your records.
if (!empty($results)) {
// total count of the array up front.
$total = count($results);
$interval = 0;
// save the data in a buffer for echoing later.
$buffer = array('<div>');
foreach($results as $row) {
$buffer[] = $row['title'] . '<br />';
if (++$interval === 24) { // notice the prefix ++
$interval = 0;
// close and re-open divs
$buffer[] = '</div><div>';
}
}
// one final close tag
$buffer[] = '</div>';
// now we zip it up and echo the content.
echo implode('', $buffer);
}
Here is how I do it...
$count = 0;
while($row = mysql_fetch_array($result)){
if ($count%$25 == 0)
{
echo "<div>";
}
//whatever your data goes here
count++
if ($count%$25 == 0)
{
echo "</div>";
}
}

Condition where the result is empty in PHP

$output = "<loginsuccess>";
for( $i = 1; $row = mysql_fetch_array($result); $i++ ) {
$output .="<keyword>".$_POST['keyword']."</keyword><name>".$row['url']."</name><occur>".$row['occurrences']."</occur><queryTime>".(substr($end_time-$start_time,0,5))."</queryTime>";
}
$output .= "</loginsuccess>";
I need now a simple condition where if the result is empty then i need to return no inside the xml [ login success ].
Is this a correct way....
if($row = mysql_fetch_array($result)) {
for( $i = 1; $row = mysql_fetch_array($result); $i++ ) {
$output .="<keyword>".$_POST['keyword']."</keyword><name>".$row['url']."</name><occur>".$row['occurrences']."</occur><queryTime>".(substr($end_time-$start_time,0,5))."</queryTime>";
} } else {
$output.="no";
}
if (mysql_num_rows($result) == 0) {
$output .= '<loginsuccess>no</loginsuccess>';
} else {
// your code
}
Try this instead:
$i = 1;
while($row = mysql_fetch_array($result))
{
$output .="<keyword>".$_POST['keyword']."</keyword><name>".$row['url']."</name><occur>".$row['occurrences']."</occur><queryTime>".(substr($end_time-$start_time,0,5))."</queryTime>";
$i++;
}
if ($i == 1)
$output .= "no";
Just a quick note, I would do what Schnalle does, but in your code I would change the for loop to a while loop as you are not doing anything with the $i
while($row = mysql_fetch_row($result)){
In total I would write you code like this:
$output = '<loginsucces>';
if(mysql_num_rows($result)){
while($row = mysql_fetch_row($result)){
$output .="<keyword>".$_POST['keyword']."</keyword><name>".$row['url']."</name><occur>".$row['occurrences']."</occur><queryTime>".(substr($end_time-$start_time,0,5))."</queryTime>";
}
} else {
$output .= 'no';
}
$output .= '</loginsucces>';
Also It owuld be even better not to mix logic and output, but that would be overkill in this situation.
Wont the for-loop simply be skipped when there are no rows? Otherwise you might want to use mysql_num_rows to count the number of rows in your result set.

Categories