While loop causing website to vanish - php

$i = 0;
$sql_query = mysql_query("SELECT * FROM designs WHERE accessibility=`2` ORDER BY id DESC LIMIT 5");
while ($row = mysql_fetch_assoc($sql_query) {
if ($i == "0") { ?><div style="width: 49%; float: left;"><img id="lookup_designs_item_icon" src="img/designs/<?php echo $row["id"]; ?>.jpg" alt="<?php echo $row["resolution"]; ?> | <?php echo $row["artist"]; ?>"/></div>
<?php } elseif ($i == "1") { ?><div style="width: 49%; float: right;"><img id="lookup_designs_item_icon" src="img/designs/<?php echo $row["id"]; ?>.jpg" alt="<?php echo $row["resolution"]; ?> | <?php echo $row["artist"]; ?>"/></div>
<?php } $i++; if ($i == "7") { end while; }
}
Why doesn't this code work? If I do it manually without database. You know, just thinking you're PHP and creating the code in HTML and CSS, it works. But as soon as you mix PHP to it, everything goes blank, entire website.

while ($row = mysql_fetch_assoc($sql_query) {
"PHP Parse error: syntax error, unexpected '{' in
As mentioned in comments, you are missing a closing parenthesis (rounded bracket) on your while condition, before the opening brace (squiggly bracket). This should read:
while ($row = mysql_fetch_assoc($sql_query)) {
However, you do have another obvious parse error at the end of your while loop. The following is invalid syntax:
if ($i == "7") { end while; }
This should read:
if ($i == "7") { break; }
"mix PHP and HTML like that" - just don't mix PHP and HTML like that... it's hard to read/maintain.
Regardless of syntax used (conventional or alternative (that Tero Kilkanen suggests) - which is intended to make this type of code easier to read) you simply should not be mixing PHP and output like this anyway, by dropping out/in of PHP parsing mode.
If you need to construct some HTML to be output later then build a string and echo this once at the end of your loop.
So, instead of this:
$i = 0;
$sql_query = mysql_query("SELECT * FROM designs WHERE accessibility=`2` ORDER BY id DESC LIMIT 5");
while ($row = mysql_fetch_assoc($sql_query) {
if ($i == "0") { ?><div style="width: 49%; float: left;"><img id="lookup_designs_item_icon" src="img/designs/<?php echo $row["id"]; ?>.jpg" alt="<?php echo $row["resolution"]; ?> | <?php echo $row["artist"]; ?>"/></div>
<?php } elseif ($i == "1") { ?><div style="width: 49%; float: right;"><img id="lookup_designs_item_icon" src="img/designs/<?php echo $row["id"]; ?>.jpg" alt="<?php echo $row["resolution"]; ?> | <?php echo $row["artist"]; ?>"/></div>
<?php } $i++; if ($i == "7") { end while; }
}
Do something like this:
// HTML to be output
$htm = '';
$i = 0;
$sql_query = mysql_query("SELECT * FROM designs WHERE accessibility=`2` ORDER BY id DESC LIMIT 5");
while ($row = mysql_fetch_assoc($sql_query)) {
if ($i == "0") {
$htm .= <<<EOD
<div style="width: 49%; float: left;">
<img id="lookup_designs_item_icon" src="img/designs/{$row["id"]}.jpg" alt="{$row["resolution"]} | {$row["artist"];}"/>
</div>
EOD;
}
elseif ($i == "1") {
$htm .= <<<EOD
<div style="width: 49%; float: right;">
<img id="lookup_designs_item_icon" src="img/designs/{$row["id"]}.jpg" alt="{$row["resolution"];} | {$row["artist"];}"/>
</div>
EOD;
}
$i++;
if ($i == "7") {
break;
}
}
// Output HTML
echo $htm;
The code is now much easier to read at a glance and it quickly becomes obvious that there are further optimisations that can be made. For instance...
the only bit that seems to vary between your if blocks is the float: left / float: right part of your style attribute. So these could be combined.
$i is an integer, yet you are comparing it with a string in your if condition. This works, but is not "correct".
You don't appear to be doing anything in your loop when $i is 2, 3, 4, 5 or 6? So you should be breaking sooner. ie. simply else { break; } would seem to do the same thing?

Related

Paginate custom SQL query

I'm really new to WordPress backend. Here I'm trying to pass variables through $_POST and get results according to those variables from my database. Everything is working fine, the only problem I'm facing is that I'm getting 80 to 90 results and I want to paginate this thing.
I've tried doing it by bypassing the page variable in the URL, but I think $_POST variables are not passing on page 2.
I'm adding the code below.
<?php
$graphic = $_POST["graphics"];
$mem = $_POST["memo"];
$opsys = $_POST["osys"];
$cpuu = $_POST["cpu"];
$hddd = $_POST["hdd"];
?>
<?php
$rowcount = $wpdb->get_var("SELECT COUNT(*) FROM game_list WHERE game_ram <= $mem AND game_card <= $graphic AND game_hdd <= $hddd AND game_os <= $opsys AND game_cpu <= $cpuu ");
?>
<p>
<?php
global $wpdb;
global $row;
$result = $wpdb->get_results( "SELECT * FROM game_list where game_ram <= $mem AND game_card <= $graphic AND game_hdd <= $hddd AND game_os <= $opsys AND game_cpu <= $cpuu order by release_date desc");
?>
<div>
<div style="padding:7px;"><h3> We found <font style="color:blue;"><?php echo $rowcount; ?></font> Results</h3><br>Reset Parameters/Search Again</div>
<?php
foreach ($result as $row) {
echo "<div class=\"column\" style=\"width:100%;min-height: fit-content;padding:5px; margin:3px;border: 1px solid;border-radius: 15px; float: left;\">
<div class=\"column\" style=\"width:25%; float: left;\">
<img src=\"";
echo $row->game_icon;
echo "\" style=\"height: 138px;width:98px;\">
</div>
<div class=\"column\" style=\"padding:5px;width:75%; float: left;\"><a href=\"";
echo $row->game_link;
echo "\"><b>";
echo $row->game_name;
echo "</a></b><hr> <b>WGod7 Game Score : </b>";
echo $row->metacritic_score;
echo "<br><b>Release Date : </b>";
echo $row->release_date;
echo "<span style=\"float:right;\">Read More...</span>";
echo "</div></div>";
}
?>
</div>

How to apply if-else on css class in php code?

I am trying to apply if else condition in bootstrap class with php variable but its not working. My variable is getting result.
Below is my tbody where i am applying php code:
<div class="<?php '#count_rows#' <= '2')
{
echo 'middle_menu';
}
else
{
echo 'middle_menu1';
} ?>">
<table class="table_4">
<thead>
<tr>
<th class="th_11">Quantity</th>
</tr>
</thead>
<tbody>
#TABLE_BODY#
</tbody>
</table>
</div>
Below is my 2 css classes:
.middle_menu
{
margin-top: 40px;
padding-bottom: 200px;
}
.middle_menu1
{
margin-top: 40px;
}
I am fetching my variable from another page where i set this type of opening and closing variable with #.
Below is my code for your reference but i dont think that is an issue for me because i check this #count_rows# variable with print_r in my current page and it showing me correct result.
foreach ($form_field as $key => $value){
$htmlContent = str_replace('#'.$key.'#', $value, $htmlContent);
}
<?php $className = $count_rows <= 2 ? 'middle_menu' : 'middle_menu1'; ?>
<div class="<?php echo $className; ?>" />
You can create a test.php then run php test.php and you should see the result
<?php
// $count_rows = 1;
$count_rows = 3;
$className = $count_rows <= 2 ? 'middle_menu' : 'middle_menu1';
echo "<div class=\"$className\"/>\n";
<div class="<?php '#count_rows#' <= '2')
You are missing a keyword here and also some brackets (which should cause a fatal syntax error), Also you are comparing two different literal strings - surely one of the terms should be a PHP variable?
You can't read back stuff you've previously written to the output stream - you are confusing what is happening in HTML, CSS and PHP.
I think you mean...
<div class="<?php if ($form_fields['count_rows'] <= '2')
Comparing a number by casting it to a string is rather dangerous.
Personally I would do this:
<div class="<?php echo (2 <= $form_fields['count_rows'])
? 'middle_menu' : 'middle_menu1'; ?>">
Since you didn't mention that the script blew up in your face, I suspect there may be a lot of other issues.
foreach ($form_field as $key => $value){
$htmlContent = str_replace('#'.$key.'#', $value, $htmlContent);
}
This is very innefficient. Consider:
$find=array_keys($form_field);
foreach ($find as $index=>$term) {
$find[$index]='#' . $term . '#';
}
$htmlContent = str_replace($find, $form_feld, $htmlContent);

How to freeze column 1 and scroll through other columns and rows in html with php and sql fields

I have the following php generated table (drawing from sql database values) in which I want the first column (all the usernames) to be frozen (fixed) while the user can scroll horizontally and 'right' across the page to view the scores for each user.
I cannot figure out how to do this with the mix of php and html going on. Can anyone suggest a viable solution please?
An image for illustration purposes is below
(I wish for the username column (all rows) to be fixed) while scrolling through to the right - there will be many more quizzes)
PHP and HTML Code
<tbody>
<?php foreach(#$result as $record){?>
<tr>
<td><?php echo $record["username"];?></td>
<?php
$counter=0;
while(mysqli_num_rows($all_quizes) > $counter){
$current_td = mysqli_query($con,"SELECT * FROM quiz_takers WHERE username='".$record["username"]."' AND quiz_id=".$quizes[$counter][0]." ORDER BY marks DESC");
$td = mysqli_fetch_array($current_td);
if($td['percentage'] == null){
echo "<td>-</td>";
}else{
if(intval($td["percentage"]) >= 0 && intval($td["percentage"]) <= 30){
$color = 'red';
}elseif(intval($td["percentage"]) > 30 && intval($td["percentage"]) <= 70){
$color = '#ffbf00';
}elseif(intval($td["percentage"]) <= 30){
}else{
$color = 'green';
}
echo "<td style='color:".$color."'>".round($td["percentage"],2)."%</td>";
}
$counter++;
}
/*foreach($current_td as $td){
echo $counter." ".$td['username'] . " - ".$quizes[$counter]['3']."<br>";
if($quizes[$counter]['0'] == $td['quiz_id']){
?>
<td><?php echo $td["percentage"];?></td>
<?php } $counter++;}*/ ?>
</tr>
<?php } ?>
</tbody>
UPDATE:
What I have tried, thanks to the helpful suggestion below regarding CSS is the following: It works, but not quite (messed up formatting)
CSS
<style type="text/css">
.headcol {
position: absolute;
width: 5em;
left: 0;
top: auto;
border-top-width: 1px;
/*only relevant for first row*/
margin-top: -1px;
/*compensate for top border*/
}
.headcol:before {
content: 'Row ';
}
</style>
Added this line below:
<tbody>
<?php foreach(#$result as $record){?>
<tr>
<td><th class="headcol"><?php echo $record["username"];?></th></td>
<?php
$counter=0;
while(mysqli_num_rows($all_quizes) > $counter){
$current_td = mysqli_query($con,"SELECT * FROM quiz_takers WHERE username='".$record["username"]."' AND quiz_id=".$quizes[$counter][0]." ORDER BY marks DESC");
$td = mysqli_fetch_array($current_td);
if($td['percentage'] == null){
echo "<td>-</td>";
}else{
if(intval($td["percentage"]) >= 0 && intval($td["percentage"]) <= 30){
$color = 'red';
}elseif(intval($td["percentage"]) > 30 && intval($td["percentage"]) <= 70){
$color = '#ffbf00';
}elseif(intval($td["percentage"]) <= 30){
}else{
$color = 'green';
}
echo "<td style='color:".$color."'>".round($td["percentage"],2)."%</td>";
}
$counter++;
}
/*foreach($current_td as $td){
echo $counter." ".$td['username'] . " - ".$quizes[$counter]['3']."<br>";
if($quizes[$counter]['0'] == $td['quiz_id']){
?>
<td><?php echo $td["percentage"];?></td>
<?php } $counter++;}*/ ?>
</tr>
<?php } ?>
</tbody>
HTML Result is skewed: comes up with this
instead of the desired:

PHP: Show 3 td's of data per table row

I am wanting to use 8 images from my database and load them into a HTML Table. I would like to display 4 images per table row, but however when i run my code below, i seem to get all images in one table row. Any help would be great. Thank you in advance.
$count = $get->rowCount();
if ($count > 0)
{
echo '<table id="" class="uiGrid _51mz _1m6c" cellpadding="2" cellspacing="0">';
$i = 0;
while ($r = $get->fetch(\PDO::FETCH_OBJ))
{
$globals = new \Libraries\Helpers\Views\Globals;
if ($i == 0)
{
echo '<tr class="_51mx">';
}
echo '
<td class="_51m-">
<a href="/e/a/'.$r->data_id.'">
<div class="uiScaledImageContainer _f-u2" style="width:74px;height:74px;">
<img class="scaledImageFitWidth img" src="https://gstatic.acfee.org/akamaihd/i/'.$globals->data_image_name($r->data_id).'">
<div class="_3s6x">
<div class="_50f3"></div>
</div>
</div>
</a>
</td>
';
if ($i > 4)
{
$i = 0;
echo '</tr>';
};
$i++;
echo '
<script type="text/javascript">
$("#favs-preloader").hide();
</script>
';
}
echo '</table>';
put this code directly it will works...
echo '<table id="" class="uiGrid _51mz _1m6c" cellpadding="2" cellspacing="0">';
$i = 0;
while ($r = $get->fetch(\PDO::FETCH_OBJ))
{
$globals = new \Libraries\Helpers\Views\Globals;
$i++;
if ($i == 1)
{
echo '<tr class="_51mx">';
}
echo '
<td class="_51m-">
<a href="/e/a/'.$r->data_id.'">
<div class="uiScaledImageContainer _f-u2" style="width:74px;height:74px;">
<img class="scaledImageFitWidth img" src="https://gstatic.acfee.org/akamaihd/i/'.$globals->data_image_name($r->data_id).'">
<div class="_3s6x">
<div class="_50f3"></div>
</div>
</div>
</a>
</td>
';
if ($i >= 4)
{
echo '</tr>';
$i = 0;
};
echo '
<script type="text/javascript">
$("#favs-preloader").hide();
</script>
';
}
echo '</table>';
In your current code, you're verifying if the $i variable is == 0 in order to add a row. But you're always increasing it's value at the end, even after you set it to zero in the if($i > 4)
Change these lines
if ($i > 4)
{
$i = 0;
echo '</tr>';
};
$i++;
To this:
if ($i > 4)
{
$i = 0;
echo '</tr>';
}
else
$i++;

Alternative to using PHP-GMP to populate two column table

A page is using the PHP GNU Multiple Precision (GMP) to determine how many rows should end up in each column. While the code works, we would like to migrate the application to a new host that does not support the PHP5-GMP module. That said, what might be the best alternative to generating and populating a two column table that may not always have an even number of results? Further the table design is probably not the best so I am open to alternatives.
The code below taken from here gets us close but since it uses mysql_fetch_array, it places the items like:
a b
c d
instead of
a c
b d
Is there a way to have it display in the first example?
Newer code:
<head>
<style>
.container { width: 400px; float: left; }
.container .item { width: 50%; float: left; height: someFixedHeight; }
</style>
</head>
<?php
mysql_select_db("database",$db);
$cat= $_GET["cat"];
echo '<div class="container">';
$q = mysql_query("SELECT * FROM name WHERE Field4 = '$cat'",$db);
while ($res = mysql_fetch_array($q)){
echo '<div class="item">' . $res['Field1'] . '</div>';
}
echo '</div>';
?>
Original code:
<div id="bit-list" align="center" >
<table class="list" width="600" border="0" align="center">
<tr>
<td width="300" height="72" valign="top" border="1">
<div align="left">
<?php
$result = mysql_query("SELECT * FROM name WHERE field4 = '$cat' ",$db);
$myrow3 = mysql_fetch_row($result);
$num_rows = mysql_num_rows($result);
$d3 = gmp_div_q("$num_rows", "2", GMP_ROUND_PLUSINF);
$i = 1;
$result8 = mysql_query("SELECT * FROM name WHERE field4 = '$cat' ",$db);
while ($myrow3 = mysql_fetch_row($result8))
{
if ($i <= gmp_strval($d3))
{
echo "<p>";
echo '<a href="detail.php?';
echo 'page=';
echo "$myrow3[2]";
echo '&';
echo 'pnum=';
echo "$myrow3[6]";
echo '">';
echo "$myrow3[1]";
echo "</p>";
$i = $i + 1;
}
else
{
}
}
?>
</div></td>
<td width="300" valign="top" border="1">
<div align="left">
<?php
$result = mysql_query("SELECT * FROM name WHERE field4 = '$cat' ",$db);
$myrow3 = mysql_fetch_row($result);
$num_rows = mysql_num_rows($result);
$d4 = gmp_div_q("$num_rows", "2", GMP_ROUND_MINUSINF);
$d3 = gmp_div_q("$num_rows", "2", GMP_ROUND_PLUSINF);
$j = 1;
$result18 = mysql_query("SELECT * FROM name WHERE field4 = '$cat' ",$db);
while ($myrow3 = mysql_fetch_row($result18))
{
if ($j <= gmp_strval($d3))
{
$j=$j+1;
}
else
{
echo "<p>";
echo '<a href="detail.php?';
echo 'page=';
echo "$myrow3[2]";
echo '&';
echo 'pnum=';
echo "$myrow3[6]";
echo '">';
echo "$myrow3[1]";
echo "</p>";
$j = $j + 1;
}
}
?>
</div>
</td>
</tr>
</table>
</div>
If i read well, you use gmp_div_q for rounding only? Then, you should check round().
The only case, that round() cannot cover is GMP_ROUND_ZERO, but you don't use that (and you could cover it with a simple if).

Categories