PHP IF ELSE statement Issue - php

My If Statement Inside of my while loop Does not seem to Execute Properly. I think It might have something to do with my logic. To me, it seems like it should work but there must be something Im missing. I need the While loop to run and count each time it does. On the fourth loop, I need the code in the if statement to run but that never seems to happen. Can anyone offer a soloution please?
<?php
$input = $_GET['input'];//Note to self $input in the name of the search feild
$terms = explode(" ", $input);
$query = "SELECT * FROM content WHERE ";
foreach ($terms as $each){
$i++;
if ($i == 1)
$query .= "keywords LIKE '%$each%' ";
else
$query .= "OR keywords LIKE '%$each%' ";
}
// connecting to our mysql database
mysql_connect("localhost", "username", "password");
mysql_select_db("database");
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if ($numrows > 0){
for($i=0; $i < $numrows; $i++){
while ($row = mysql_fetch_assoc($query)){
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
$plink = $row ['plink'];
$views = $row ['views'];
if($i== 4){
echo '<td valign="top" "width="248" height="100%">
<table width="100%" border="0">
<tr>
<td align="center" valign="top"><a href='.$link.'>
<img src='.$plink.'width="200" height="151" vspace="5" />
<br><b><a href='.$link.'>'.$title.'</b></a>
<br><strong><span style="line-height:20px">Total views: '.$views.'</span></strong>
</td>
</tr>
</table>
</td><tr>';
}
else{
echo '<td valign="top" "width="248" height="100%">
<table width="100%" border="0">
<tr>
<td align="center" valign="top"><a href='.$link.'>
<img src='.$plink.'width="200" height="151" vspace="5" />
<br><b><a href='.$link.'>'.$title.'</b></a>
<br><strong><span style="line-height:20px">Total views: '.$views.'</span></strong>
</td>
</tr>
</table>'
;
}
}
}
}
else
echo "No results found for \"<b>$input</b>\"";
// disconnect
mysql_close();
?>

You're looping once for each row, but within your for loop, you have a while that is fetching all the rows. You need to get rid of the for loop.So instead of doing this:
for($i=0; $i < $numrows; $i++){
while ($row = mysql_fetch_assoc($query)){
you should do this:
$i = 0;
while ($row = mysql_fetch_assoc($query)){
$i++;
....

On the first iteration of your for loop $i == 1, so your condition won't execute. However, your while loop will empty the result set so that on the second and subsequent iterations of your for loop there are no rows to fetch. Your if condition isn't encountered again.

Related

PHP SQLSRV Pagination function returns one row

My pagination isn't working correctly. I get the page numbers but each page only has one row when it should have 10 rows. I new to php and am adapting code that I found on this site. When I load the page I can tell by the id number that the result showing is what I would expect the 10th row in the query to be...rows 1-9 are missing.
<?php
//Function to return rows for each page
function getPage($stmt, $pageNum, $rowsPerPage)
{
$offset = ($pageNum - 1) * $rowsPerPage;
$rows = array();
$i = 0;
while(($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC,SQLSRV_SCROLL_ABSOLUTE,$offset + $i)) && $i < $rowsPerPage)
{
array_push($rows, $row);
$i++;
}
return $rows;
}
?>
<?php
// Set the number of rows to be returned on a page.
$rowsPerPage = 10;
$usr = $_SESSION['user'];
if ($_SESSION['admin']="YES") {
$query = "SELECT iID,FirstName,LastName, convert(varchar, SubmitDate, 101) as SubDate,LEFT(ImproveIdea,30) as MyIdea,Status FROM Idea where Status='Pending' ORDER BY iID desc";
}else {
$query = "SELECT iID,FirstName,LastName,convert(varchar, SubmitDate, 101) as SubDate,LEFT(ImproveIdea,30) as MyIdea,Status FROM Idea where SubmitBy='".$usr."' ORDER BY iID desc";
}
$stmt = sqlsrv_query($connect,$query, array(), array( "Scrollable" => 'static' ));
if ( !$stmt )
die( print_r( sqlsrv_errors(), true));
?>
<table class="table table-striped table-bordered">
<thead class="thead-light">
<tr>
<th width="54%" scope="col">Submitted By</th>
<th width="14%" scope="col">Date Submitted</th>
<th width="13%" scope="col">Status</th>
<th width="19%" scope="col">Actions</th>
</tr>
</thead>
<tbody>
<?php
$pageNum = isset($_GET['pageNum']) ? $_GET['pageNum'] : 1;
$page = getPage($stmt, $pageNum, $rowsPerPage);
foreach($page as $row)
$ideanum = $row[0];
$fname = $row[1];
$lname = $row[2];
$submitdate = $row[3];
$idea = $row[4];
$status = $row[5];
echo '<tr>';
echo '<td>'.$ideanum.' '.$fname.' '.$lname.' - '.$idea.'...</td>';
echo '<td>'.$submitdate.'</td>';
echo '<td>'.$status.'</td>';
echo '<td><button type="button" class="btn btn-success"><i class="la la-eye"></i></button><button type="button" class="btn btn-info"><i class="la la-edit"></i></button></td>';
echo "</tr>";
?>
<?php
// Get the total number of rows returned by the query.
// Display links to "pages" of rows.
$rowsReturned = sqlsrv_num_rows($stmt);
if($rowsReturned === false)
die( print_r( sqlsrv_errors(), true));
elseif($rowsReturned == 0)
{
echo "No rows returned.";
exit();
}
else
{
// Display page links.
$numOfPages = ceil($rowsReturned/$rowsPerPage);
for($i = 1; $i<=$numOfPages; $i++)
{
$pageLink = "?pageNum=$i";
print("<a href=$pageLink>$i</a> ");
}
echo "<br/><br/>";
}
?>
</tbody>
</table>
SOLVED: The issue was that I was missing the brackets in my foreach statement as a redditor pointed out to me.

Adding a new row in a table after every 3 images from database

I have a gallery where images are uploaded via MySQL database and displayed on my site in a table. Problem is, the images are inserted into rows of one. I need someone to alter my script to where a new row will be added after every 3 columns (images).
I asked this before but deleted the thread so I could start over. I've done a lot of research and learned a few things, but I cannot figure out how to write the script to fit my needs.
Script:
<table width="100%" border="1" cellspacing="0" cellpadding="4">
<?php
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." ORDER BY id ASC";
$sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
if (mysql_num_rows($sql_result)>0) {
while ($row = mysql_fetch_assoc($sql_result)) {
?>
<tr>
<td><?php echo $row["img"]; ?><br>Size: <?php echo $row["size"]; ?><br>Views: <?php echo $row["clicks"]; ?></td>
</tr>
<?php
}
} else {
?>
<tr><td colspan="3">No results found.</td>
<?php
}
?>
</table>
You need to open and close your tags not every iteration, but every 3 iterations. The resulting code might look something like this:
<table width="100%" border="1" cellspacing="0" cellpadding="4">
<?php
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." ORDER BY id ASC";
$sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
if (mysql_num_rows($sql_result)>0) {
$i=0;
while ($row = mysql_fetch_assoc($sql_result)) {
if ($i++ % 3 == 0) echo "<tr>";
?>
<td><?php echo $row["img"]; ?><br>Size: <?php echo $row["size"]; ?><br>Views: <?php echo $row["clicks"]; ?></td>
<?php
if ($i % 3 == 0) echo "</tr>";
?>
<?php
}
if ($i % 3 != 0) echo "</tr>";
} else {
?>
<tr><td colspan="3">No results found.</td>
<?php
}
?>
</table>
You the guy with this answer if ($i % 3 == 0) echo ""; are the savior. I tried so much in JavaScript. but haven't forgotten I could do this on back end.

Go to next row when HTML table is full

I am using an HTML table to display data from a MySQL table using PHP. I need it so once the table has 10 columns, it will move on to the next row.
<?php
$result = mysqli_query($con,"SELECT * FROM table");
echo '<table width="100%" border="1px"><tr width="100%">';
while($row = mysqli_fetch_array($result))
{
?>
<td width="10%"><?php echo $row['Name']; ?></td>
<?php
}
echo "</tr></table>";
mysqli_close($con);
?>
How can this be done?
Untested but something like this should work or get you started in a good direction:
<?php
$result = mysqli_query($con,"SELECT * FROM table");
echo '<table width="100%" border="1px"><tr width="100%">';
$x=0;
while($row = mysqli_fetch_array($result))
{
if($x==0){
echo "<tr>\n";
}elseif($x%10){
echo"</tr><tr>\n";
}
?>
<td width="10%"><?php echo $row['Name']; ?></td>
<?php
$x++;
}
echo "</tr></table>";
mysqli_close($con);
?>
Add a counter to your loop starting at one.
Each time through the loop if the remainder after dividing the counter value by 10 is 1
add the <tr>. If the remainder is 0 then add a </tr> Then after the loop a </tr> if the remainder is not evenly divisible by 10.
<?php
echo '<table width="100%" border="1px"><tr width="100%">';
$i = 0;
while($row = mysqli_fetch_array($result))
{
$i++;
?>
<?php if ($i%10 ==1): ?><tr><?php endif; ?>
<td width="10%"><?php echo $row['Name']; ?></td>
<?php if ($i%10 ==0): ?></tr><?php endif; ?>
<?php
}
if ($i%10 != 0) echo "</tr>";
echo "</tr></table>";
Using modulo (%)
After each 10th cell, if a new cell is added, the current row is closed and a new row is opened first, before outputting the cell.
<?php
$result = mysqli_query($con,"SELECT * FROM table");
echo '<table width="100%" border="1px"><tr>';
$cell = 0;
while($row = mysqli_fetch_array($result))
{
if ($cell++ % 10 == 0 && $cell > 1)
{
?>
</tr><tr>
<?php
}
?>
<td width="10%"><?php echo $row['Name']; ?></td>
<?php
}
echo "</tr></table>";
mysqli_close($con);
?>
The extra condition && $cell > 1 seems to be a little odd, but without it, you will get an empty row to start with. Eliminating it by putting ++ before $cell will cause the first row to be 9 cells instead of 10. Putting $cell > 0 && in front of the modulo will cause cell never to be incremented, because the first part of the expression is always false. Moving the if to execute it after outputting the cell, would cause the risk of ending with an empty row. It could be solved using a do..while loop, but you'd have to check up front if you have one row at least.
Long story short: use the code above. :)
Using a simple counter and reset it after each row
I think it's even more readable without the modulo, though you'd have to initialize $cell to -1 to prevent the first row to be 9 cells. Nevertheless, I think this is cleaner:
<?php
$result = mysqli_query($con,"SELECT * FROM table");
echo '<table width="100%" border="1px"><tr>';
$cell = -1;
while($row = mysqli_fetch_array($result))
{
if (++$cell == 10)
{
$cell = 0;
?>
</tr><tr>
<?php
}
?>
<td width="10%"><?php echo $row['Name']; ?></td>
<?php
}
echo "</tr></table>";
mysqli_close($con);
?>
<table>
<tr>
<?php
$endRow = 0;
$columns = 10; // number of columns
$hloopRow1 = 0;
do {
if($endRow == 0 && $hloopRow1++ != 0) echo "<tr>";
?>
<td>
<?php echo $row['Name']; ?>
</td>
<?php $endRow++; if($endRow >= $columns) { ?>
</tr>
<?php $endRow = 0; }
} while ($row = mysql_fetch_assoc($result));
if($endRow != 0) {
while ($endRow < $columns) {
echo("<td> </td>");
$endRow++;
}
echo("</tr>");
}
?>
</table>
This should work fine. Hope this helps.

PHP MYSQL, How to show records in four columns ,

Here is my code the records shows in four columns but if my records is blank it shows three balng images, any suggestions?
$query = mysql_query("SELECT * from rbf_events_images where event_id='".$_GET['id']."'");
echo '<table border="1">';
if(count(mysql_num_rows($query)>0)):
$tropentags='<tr>';
$troclosingtags='</tr>';
$formTags="";
$tdTags="";
$count=1;
while($row = mysql_fetch_array($query)){
$tdTags.='<td align="left" valign="middle" class="td" >$row['image']</td>';
if ($count>3)
{
$formTags.=$tropentags.$tdTags.$troclosingtags;
$tdTags="";
$count=0;
}
$count=$count+1;
}
if ($count>0)
{
for($i = 1; $i <= (4-$count) ; $i++)
{
$tdTags.='<td align="left" valign="middle" class="td" >$row['image']</td>';
}
$formTags.=$tropentags.$tdTags.$troclosingtags;
}
echo $formTags;
endif;
Thanks for your help!really appreciated!
I noticed that on lines like this one:
$tdTags.='<td align="left" valign="middle" class="td" >$row['image']</td>';
You are delimiting the string with single quotes ('), and you are also trying to embed a variable in the string that uses single quotes. I'm not sure how you did not get compile errors for that. I would switch to:
$tdTags= '<td align="left" valign="middle" class="td">' . $row['image'] . '</td>';
Here's what I usually do to put records in columns:
$id = mysql_real_escape_string($_GET['id']);
$query = mysql_query("SELECT * from rbf_events_images where event_id='$id'");
echo '<table border="1"><tbody><tr>';
if (mysql_num_rows($query) > 0) {
$count = 0;
while ($row = mysql_fetch_array($query)) {
if ($count && $count % 4 == 0) echo '</tr><tr>';
echo '<td align="left" valign="middle" class="td">'.$row['image'].'</td>';
$count++;
}
}
echo '</tr></tbody></table>';

How to print data in a table from mysql

I want to extract the last eight entries from my database and print them into a two columns table like this:
|1|2|
|3|4|
|5|6|
|7|8|
Is that possible?
This is my code:
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$db->connect();
$sql = "SELECT ID, movieno
FROM movies
ORDER BY ID DESC
LIMIT 8 ";
$rows = $db->query($sql);
print '<table width="307" border="0" cellspacing="5" cellpadding="4">';
while ($record = $db->fetch_array($rows)) {
$vidaidi = $record['movieno'];
print <<<END
<tr>
<td>
<a href="http://www.dadadada.com/watch?v=$vidaidi" target="_blank">
<img src="http://img.dadadada.com/vi/$vidaidi/1.jpg" width="123" height="80"></a>
</td>
</tr>
END;
}
print '</table>';
Yes it's possible.
<table border=1><tr>
<?
$count = 0;
$max = 4;
while(your loop){
$count++;
echo '<td>'.$count.' record stuff </td>';
if($count >= $max){
//reset counter
$count = 0;
//end and restart
echo '</tr><tr>';
}
}
?>
</tr></table>

Categories