php mysql - echo clear division after 3rd result - php

I echo results in DESC order from MySQL table with while loop. I've pagination system implemented already and its size is 9 records per page. The problem is, that if I do:
// ECHO CSS BREAK
if($row['id'] % 3 == 0){
echo '<li class="clear"></li>';
}
// SHOW VIDEOS
while($row = mysql_fetch_array($result)){
echo '<li>...echo code...</li>';
// problem = implement that echo css break in ASC order
}

Use a loop variable, e.g.
$i = 0;
Then instead of
if ($row['id'] % 3 == 0) {
do
if (++$i % 3 === 0) {
This makes sure it always happens are the third [sixth, ninth, ...] time.
You may want to get arbitrary rows from the database at another point in time, or shuffle the results -- relying on row IDs is not a good idea.

Is this what you are looking to implement?
// SHOW VIDEOS
while($row = mysql_fetch_array($result)){
if($row['id'] % 3 == 0){
echo '<li>...echo code...</li>';
echo '<li class="clear"></li>';
} else {
echo '<li>...echo code...</li>';
}
}

Related

Getting total count of nodes in tree

I am creating a simple Affiliate System (5 Level max). So basically the database have this kind of structure:
"aff level" column is just extra things so that i know that i listed out correctly.
I have successfully listed out (in bullet format) the parent & child of each agent. Below is my code:
function list_current_agents($aff_parent_id, $aff_level){
$max_level = 5;
if($aff_level <= 5)
{
$query = "SELECT aff_id, agent_code FROM affiliate WHERE aff_parent_id = '$aff_parent_id' AND aff_level = '$aff_level'";
$result = db_query($query);
$row = $result-> fetch_object();
if($result-> num_rows > 0)
{
echo '<ul>';
do{
$aff_id = $row-> aff_id;
$agent_code = $row-> agent_code;
echo '<li>';
echo $aff_id .' - '.$agent_code . ' - (level '.$aff_level.')';
echo '</li>';
$aff_level = $aff_level+1;
if($aff_level <= 5)
{
list_current_agents($aff_id, $aff_level+1);
}
}while($row = $result-> fetch_object());
echo '</ul>';
}
}
return $count;
}
and the output will be like this:
And now im stucked where i want to list out the total number of the child below if i select one of the parent agent. For example, if i select:
Agent1
total child : 8
Agent3
total child : 3
I have tried any method i can think of but cant work out with the logic.
Any help is very much appreciated.
thanks in advance.
Create an actual tree data structure and it will be easy to count the children.
Or you can use one of the many available on Github. This one is even made for you specific database structure.

Echo images using php according to a particular condition [duplicate]

This question already has an answer here:
echo image according to a condition
(1 answer)
Closed 6 years ago.
I have this query :
$q4 = "SELECT TOP 5 b.BadgeName, b.BadgeImage FROM BadgeImageTable AS b
INNER JOIN employee_badge AS e
ON e.badge_id = b.BadgeID
WHERE e.employee_id = 2164
ORDER BY e.earned_on DESC ";
$stmt3=sqlsrv_query($conn,$q4);
if($stmt3==false)
{
echo 'error to retrieve info !! <br/>';
die(print_r(sqlsrv_errors(),TRUE));
}
the query returns this :
Now in my php, i am trying to echo any three random images from the 'BadgeImage' column,if the query gives more than 3 rows of data.Else,if the query gives 2 rows,display only 2 images,if 1 row,display only 1 'badgeImage' and so on.
PHP Code that I tried and which is not giving the correct result :
<div class="badgesize">
<?php
if($count = sqlsrv_num_rows($stmt3) > 0){
while($recentBadge = sqlsrv_fetch_array($stmt3)){
$result[] = $recentBadge;
}
if($count > 3){
foreach(array_rand($result, 3) as $val){
$data[] = $result[$val];
}
$result = $data;
}
foreach($result as $recentBadge){
echo $recentBadge['BadgeName'], '<img src="'.$badgerecent['BadgeImage'].'">';
}
} else {
echo 'no results';
}
?>
</div>
When I run the above PHP it is giving 'no result' inh the UI i.e "it is not running the if statement' and directly going to the else part of the PHP.
This shouldnot happen as the query fetches 5 rows of data as shown in above picture.
When I try to echo simply (using below code) without the above condition,I am able to do so without any issue.
<img src="<?php echo "".($recentBadge['BadgeImage']).""; ?>" >
I am using PHP 5.5.38 and sql server 2012
Change the following:
if($count = sqlsrv_num_rows($stmt3) > 0){
to
$count = sqlsrv_num_rows($stmt3); // getting the record count
if($count > 0){ // checking if there is some rows present or not
while($recentBadge = sqlsrv_fetch_array($stmt3)){
// your code
}
}
and one more thing do not put full path of the image in badgeImage column as this will create problem when you move code from local to server. Keep only path of image folder and image name.
Apparently sqlsrv_num_rows() does not return an expected result which is explained here
Alternatively you can use that fix or you can use the following code:
if(sqlsrv_has_rows($stmt3)){
while( $row = sqlsrv_fetch_array($stmt3, SQLSRV_FETCH_ASSOC) ) {
$recentBadge[] = $row;
}
if(count($recentBadge) > 3){
foreach(array_rand($recentBadge, 3) as $key){
$data[] = $recentBadge[$key];
}
$recentBadge = $data;
}
} else {
$recentBadge = [];
}
foreach($result as $recentBadge){
echo $recentBadge['BadgeName'], '<img src="'.$badgerecent['BadgeImage'].'">';
}
This way we're checking if there are found rows instead, is so, store them all in an array and count the size of the array instead.
replace
if($count = sqlsrv_num_rows($stmt3) > 0){
with
$count = sqlsrv_num_rows($stmt3);
if($count > 0){

If rowCount empty, try again

I am running a query from a table whose data gets refreshed (deleted and re-inserted) every 30 seconds.
I want my query (which outputs row count) to detect that the row count is null (or zero) and re-run the query. Maximum retries: 5.
And after 5th retries, if it's still zero, I want the row count to print "0".
I know it's a loop but I don't know how to loop it from within the if for row.
<?php
$con=mysqli_connect("HOST","USERNAME","PASS","TABLENAME");
$sql="SELECT id FROM candyshop WHERE candy <= 5 AND sugartype ='hard'";
$number = 0; //init count for loop
if ($result=mysqli_query($con,$sql))
{
$rowcount=mysqli_num_rows($result);
printf($rowcount); //print number of rows
mysqli_free_result($result);
$number = $number+1; //increment number for loop
}
mysqli_close($con);
?>
Use a do while loop and only leave the loop if the rowcount is higher than 0 or 5 retries have been reached.
<?php
$sql = "SELECT id FROM candyshop WHERE candy <= 5 AND sugartype ='hard'";
$count = 0;
$retry = 5;
do {
// Count the rows
if ($result = mysqli_query($con, $sql)) {
$count = mysqli_num_rows($result);
}
// Wait for 10ms
if ($count === 0) {
usleep(10000)
}
} while ($count === 0 && --$retry > 0);
mysqli_close($con);
This is however very bad practice, I would recommend looking for another approach. Why would you clear and then refill the table?
Still new to StackOverflow but can you try this?
<?php
$con=mysqli_connect("HOST","USERNAME","PASS","TABLENAME");
$sql="SELECT id FROM candyshop WHERE candy <= 5 AND sugartype ='hard'";
$number = 0; //init count for loop
if ($result=mysqli_query($con,$sql)) {
$rowcount=mysqli_num_rows($result);
printf($rowcount); //print number of rows
mysqli_free_result($result);
$number = $number+1; //increment number for loop
if ($number = 5) {
printf(0);
break 2;
}
}
mysqli_close($con);
?>
$i = 0;
do {
$result = mysqli_query($con, $sql);
$count = mysqli_num_rows($result);
} while ($count == 0 && $i++ < 5)
As i understood you are trying to write a Web Based Game. Actually your method is probably going to make database a little busy. You don't have to loop queries. If you are going to do it, we are talking about milliseconds here. Let's say your queries are generally giving results in 0.05 seconds that means for 5 query you are just going to have the data of 0.25 seconds.
You can write your game or whatever easily with COMET Programming. But if you decided to go with loop queries , there is only one thing you will do and it's for loop.
$rowcount=0;
do {
if ($result=mysqli_query($con,$sql)) {
$rowcount=mysqli_num_rows($result);
printf($rowcount); //print number of rows
mysqli_free_result($result);
}
} while(++$number<5 && $rowcount!=0);
that is basicaly the answer to your request, though it needs some more explanation to be useful.

PHP/SQL Query find last result

I am running a while loop in PHP selecting data from a mysql database. How can i find out what the last record is,
for example:
$sql="SELECT * from table1 ";
$rs=mysql_query($sql,$conn);
while($result=mysql_fetch_array($rs))
{
echo $result["col1"].' - '.$result["col2"].'<br>';
}
then when it gets to the last record i want to display it like:
echo 'Last Record: '.$result["col1"].' - '.$result["col2"].'<br>';
You basically need to record how many rows you have, and then set up a counter. You can do that using mysql_num_rows():
$sql="SELECT * from table1";
$rs = mysql_query($sql,$conn);
$numRows = mysql_num_rows($rs);
$i = 1;
while($result=mysql_fetch_array($rs))
{
echo ($i == $numRows) ? 'Last Record: '.$result["col1"].' - '.$result["col2"].'<br />' : $result["col1"].' - '.$result["col2"].'<br />';
$i++;
}
You should note though that the mysql_*() family of functions is now deprecated. For security and longevity, you really ought to be using MySQLi or PDO.
Get the total count of rows returned and check use a flag variable for the loop iterations and check in loop if flag == total rows
$t=mysql_num_row($rs);
$i=0;
while($result=mysql_fetch_array($rs))
{
$i++;
if($t == $i){
echo "Last Record ";
}
echo $result["col1"].' - '.$result["col2"].'<br>';
}
mysql_num_rows
You can simply use the sql query itself to get the last value, based on whatever ordering you want (or just use DESC to get the bottom of the natural order):
SELECT * FROM table1
ORDER BY your_column DESC
LIMIT 1;
Edit: Since you're looking for the last row, you could check with mysql_num_rows
$numrows = mysql_num_rows($rs);
$i = 1;
// in while loop...
if ($i === $numrows) {
// print last result
} else {
// print normal result
}
$i++;
// end while loop
Essentially, you want a counter for the record you are on and then write when the number of rows is the same as the row number you are on (e.g. the last one)
$sql="SELECT * from table1 ";
$rs=mysql_query($sql,$conn);
$num_rows = mysql_num_rows ($rs);
for ($i=0; $i < $num_rows; $i++) {
$result=mysql_fetch_array($rs);
if ($i == ($num_rows - 1)) {
echo 'Last Record: '.$result["col1"].' - '.$result["col2"].'<br>';
} else {
echo $result["col1"].' - '.$result["col2"].'<br>';
}
}
Future-proof this routine by doing it the "hard way":
while ($next_row = fetch_row(...)) {
if ($prev_row) { do_output($prev_row); }
$prev_row = $next_row;
}
if ($prev_row) { do_output($prev_row, FLAG_IS_LAST_ROW); }
Why? Future maintenance might make mysql_num_rows() unreliable, either because your result set gets too big, or because you want to interface with a variety of SQL backends.
By default, the MySQL client library pulls the entire result set into memory — that is how it knows the number of rows SELECTed without having to count fetches. This behavior is rather convenient for small result sets, but devastating for large result sets. This it is user-configurable. (The options are usually named something like "store_result v. use_result" or "buffered v. unbuffered.")
Additionally, most RDBMS interfaces do not make the size of the result set known in advance. If you want to interface with these some day in a reusable way, you'll need to change your approach.

PHP mysql_fetch_array

$n=mysql_num_rows($rs);
$i=0;
while($n>0)
{
while(($row=mysql_fetch_array($rs))&&$i<=5)
{
echo $row['room_name'];
$i=$i+1;
//echo $n."<br>";
}
echo "<br>";
//echo "n1=".$n;
$n=$n-5;
//
$i=0;
}
Output:101102103104105106
108109110
The row for roomname 107 is missing....
anybody please tell me what is the problem while reentering the loop again...
When $i becomes 6 you fetch a row but do nothing. Because fetching happens before the $i<=5 check, the fetched row gets skipped.
Change the order of conditions in the while loop.
while(($row=mysql_fetch_array($rs))&&$i<=5)
To
while($i<=5 && ($row=mysql_fetch_array($rs)))
Just to follow up on my comment, this whole chunk of code could have been written much more clearly as follows. (assuming you meant to put in a <br> after every 5 records, right now you're doing it after 6 but I think that's probably a mistake)
$rownum = 1;
while ($row = mysql_fetch_array($rs))
{
echo $row['room_name'];
if ($rownum % 5 == 0)
echo '<br>';
$rownum++;
}
here if are checking $i<=5 condition so array stats from 0 , so your database values stats from 101,102,..106, so it will 6 elements .
$i<=5 condition remove this condition in while keep the condition if($i%5==0) echo ""; it will works

Categories