Trying to test which row the loop is on and if it's greater than or equal to six, plug the $TESTIMAGE variable into the span element for the next iteration.
When I run the code, it plugs the variable into everything following the first row.
While($row = mysql_fetch_array($result))
{
//assign variables
$title = $row['title'];
$url = $row['location'];
$image = "/waves/files/images/games/$title.png";
echo "
<span class='dropt'>
<a href=$url>$title</a>
<span class='$TESTIMAGE'>
<img src='$image'>
</span>
</span>
<br />
";
//Test to see which row we're on -- adjust image position
If (mysql_num_rows($result) >= 6)
{
$TESTIMAGE = "image_display_up";
}
}
use an increasing index:
$i = 0;
while($row = mysql_fetch_array($result)){
$i += 1;
}
That is because mysql_num_rows() will return the same exact value for each iteration of the loop, as the number of rows in the result change will not change.
You would need to implement a counter to do what you are wanting to do.
try it like this:
$i = 1;
While($row = mysql_fetch_array($result)) {
if(!($i%6)) { // will enter here on the 6th try.
//assign variables
$title = $row['title'];
$url = $row['location'];
$image = "/waves/files/images/games/$title.png";
echo "
<span class='dropt'>
<a href=$url>$title</a>
<span class='$TESTIMAGE'>
<img src='$image'>
</span>
</span>
<br />
";
}
if($i!=6) // this way it remains on 6
$i++;
}
$i=0;
While($row = mysql_fetch_array($result)) {
//assign variables
$title = $row['title'];
$url = $row['location'];
$image = "/waves/files/images/games/$title.png";
$TESTIMAGE = ($i++ >= 6) ? "image_display_up" : "";
echo "
<span class='dropt'>
<a href=$url>$title</a>
<span class='$TESTIMAGE'>
<img src='$image'>
</span>
</span>
<br />
";
}
The call to mysql_num_rows($result) always returns the same number. You want to increment an index on each iteration instead:
$idx = 0
while (blah) {
if ($idx >= 6)
{
$TESTIMAGE = "image_display_up";
}
$idx += 1
}
Related
I have arranged values alphabetically according to their starting alphabet
section, values starting with A to be under the A column header, and
companies starting with B to be under the B header...or if i have no value
with the value of B then B be skipped. And to show just 5 values... But
problem is that values seprating from their column headers and i wants to show then in their own cloumn header...here is my
code.
<?php
$sql = "select company_name from companies ORDER BY company_name ";
$result = mysqli_query($con, $sql);
while($data = mysqli_fetch_assoc($result)){
$company = $data['company_name'];
creatCompanyList($company, $letter,$count);
}
$count = 0;
$letter = '';
//echo $count;
function creatCompanyList($company, &$letter, &$count){
// echo $count;
if($letter !== $company[0]) {
if($count >0) {
endCompanyList();
$count = 0;
}
$letter = $company[0];
startCompanyList($letter, $count);
}
if($letter == $company[0] && $count <= 4) addCompanyList($company);
if($count==4) endCompanyList();
$count++;
}
function startCompanyList($letter, &$count){
?>
<li class="loop-entry">
<div class="col"> <span><?php echo $letter?></span>
<div class="list-col">
<?php
}
function endCompanyList(){
?>
</div>
</div>
</li>
<?php
}
function addCompanyList($company){
?>
<?php echo $company?>
<?php
}
?>
This is screen shot of webpage and i wants the values of E in E column header
Your code considers lowercase and uppercase of a letter not the same. Fixed that by including strtolower() condition in your if statements.
Also added strtoupper() for your header letter so it always appears uppercase in case lowercase letter is passed as header.
Updated Code:
<?php
$sql = "select company_name from companies ORDER BY company_name ";
$result = mysqli_query($con, $sql);
while($data = mysqli_fetch_assoc($result)){
$company = $data['company_name'];
creatCompanyList($company, $letter,$count);
}
$count = 0;
$letter = '';
//echo $count;
function creatCompanyList($company, &$letter, &$count){
// echo $count;
if(strtolower($letter) !== strtolower($company[0])) {
if($count >0) {
endCompanyList();
$count = 0;
}
$letter = $company[0];
startCompanyList($letter, $count);
}
if(strtolower( $letter ) == strtolower( $company[0] ) && $count <= 4) addCompanyList($company);
if($count==4) endCompanyList();
$count++;
}
function startCompanyList($letter, &$count){
?>
<li class="loop-entry">
<div class="col"> <span><?php echo strtoupper( $letter )?></span>
<div class="list-col">
<?php
}
function endCompanyList(){
?>
</div>
</div>
</li>
<?php
}
function addCompanyList($company){
?>
<?php echo $company?>
<?php
}
?>
i have this php mysql query
<?php
$product = mysql_query('SELECT * FROM products LIMIT 6 ');
$pro = mysql_fetch_assoc($product);
?>
Now that query will return 6 products from database and what i want to do is echo 3 products inside a <div> and the other 3 products inside another <div> like this
<div class="first-3>
///Here i want to echo 3 products from the query from 1-3
<?php echo $pro['title']; ?>
</div>
<div class="second-3>
///Here i want to echo the rest 3 products of the query from 4-6
<?php echo $pro['title']; ?>
</div>
<?php
$num = 6;
$product = mysql_query('SELECT * FROM products LIMIT $num');
$firstDiv = "";
$secondDiv = "";
$i = 0;
while ($pro = mysql_fetch_assoc($product)) {
if ($i < ($num /2)) {
$firstDiv .= $pro['title'];
}
else {
$secondDiv .= $pro['title'];
}
$i++;
}
?>
And:
<div class="first-3>
<?php $firstDiv ?>
</div>
<div class="second-3>
<?php $secondDiv ?>
</div>
Iterate and output the values.
<?php
$product = mysql_query('SELECT * FROM products LIMIT 6 ');
$i = 1;
echo '<div class="first-3">';
while ( $pro = mysql_fetch_assoc($product) ) {
if ($i === 3) {
echo '</div><div class="second-3">';
}
echo $pro['title'];
$i++;
}
echo '</div>';
?>
Note that it's not safe to use mysql_query, you should be using mysqli or preferrably PDO.
mysql_fetch_assoc is used to retrieve a row in the resultset.
Doc: http://php.net/manual/es/function.mysql-fetch-assoc.php
A loop is required to iterate on each row.
A very simple example:
// Get a collection of 6 results
$products = mysql_query('SELECT * FROM products LIMIT 6 ');
// iterate over the 6 results
$i=0;
echo '<div class="first-3>';
while ($pro = mysql_fetch_assoc($products)) {
$i++;
// Print an item
echo $pro["title"];
// If 3 items are printed end first div and start second div
if($i==3){
echo '</div><div class="second-3">';
}
}
echo '</div>';
// Free the collection resources
mysql_free_result($products);
Just set up a counter to divide in groups of 3:
$count = 0;
while (...)
{
// your code
$count++;
if ( ($count % 3) === 0 )
{
echo '</div><div class="...">';
}
}
Please note that the mysql_* functions are deprecated and you should switch to PDO or mysqli.
$product = mysqli_query($conn, 'SELECT * FROM products LIMIT 6 ');
$results = array();
while($pro = mysqli_fetch_assoc($product)) {
$results[] = $pro;
}
echo '<div class="first-3">';
for($i = 0; $i < 3; $i++) {
echo $results[$i]['title'];
}
echo '</div><div class="second-3">';
for($i = 3; $i < 6; $i++) {
echo $results[$i]['title'];
}
echo '</div>';
Everytime you get the multiple of 3, ($k % 3 == 0) you will increment the flag variable, you can do then some conditions with the variable flag, i used here iterators because the hasNext() beauty.
Example
$pro = array(1, 2, 3, 4, 5, 6);
$flag = 0;
$pro = new CachingIterator(new ArrayIterator($pro));
foreach ($pro as $k => $v) {
// if multiples 3
if ($k % 3 == 0) {
$flag++;
if ($flag == 1) {
echo '<div class="first-3" style="border:1px solid black;margin-bottom:10px;">';
} else if ($flag == 2) {
echo '</div>'; // Closes the first div
echo '<div class="second-3" style="border:1px solid red">';
}else{ // if you have more than 6
echo '</div>';
}
}
// insert Data
echo $v . '<br/>';
if (!$pro->hasNext())
echo '</div>'; // if there is no more closes the div
}
I'm trying to display different images from the database that are in the same field but the result is echoed either as "m" or "Array".
Here's my code:
$badges = $row['badges'];
$badges = explode(",", $badges);
$badge = count($badges);
if(empty($badges)) {
$badges = "";
} else {
$i = 0;
while($i <= $badge) {
$badges = "<img src='".$badges[$i]."' /> ";
$i++;
}
}
$rank = "<tr><td><img src='".$rank."' /> ".$badges."</td></tr>";
$rank is then echoed to the div that I want it to be displayed but the image src is always "m" or when I try putting the while in place of the $rank variable it echoes as "Array". Does anyone know why this is?
I would use another variable name, like badgeString as the output. Also, it seems like you want to append all the badges
if(empty($badges)) {
$badgeString = "";
} else {
$i = 0;
while($i <= $badge) {
$badgeString .= "<img src='".$badges[$i]."' /> ";
$i++;
}
}
$rank = "<tr><td><img src='".$rank."' /> ".$badgeString."</td></tr>";
I would like to show 3 random images from database in my website. Below is its code:
$query = mysql_query ("SELECT id,url FROM tbl_gallery2");
if (mysql_num_rows($query) >= 3) {
$my_array = array();
$last_array = array();
while ($r = mysql_fetch_row($query)) {
$my_array[] = $r[1];
}
function makernd () {
$number = array_rand($my_array,1);
if (in_array($number,$last_array)) {
makernd();
} else {
$last_array[] = $number;
return $number;
}
}
for($i = 1 ; $i < 3 ; $i++) {
$item = makernd();
echo '<img src="./images/slider/'.$item.'.jpg" alt="" class="slider" />';
}
}
But whenever I run this code, I get the error below:
Undefined variable: my_array in line ... // The first line of makernd() function.
But I expected $my_array to be an accessible array for this function.
What's the problem?
To simply fix your problem, you should pass $my_array to makernd() as a parameter:
$query = mysql_query ("SELECT id,url FROM tbl_gallery2");
if (mysql_num_rows($query) >= 3) {
$my_array = array();
$last_array = array();
while ($r = mysql_fetch_row($query)) {
$my_array[] = $r[1];
}
function makernd ($my_array) {
$number = array_rand($my_array,1);
if (in_array($number,$last_array)) {
makernd($my_array);
} else {
$last_array[] = $number;
return $number;
}
}
for($i = 1 ; $i < 3 ; $i++) {
$item = makernd($my_array);
echo '<img src="./images/slider/'.$item.'.jpg" alt="" class="slider" />';
}
}
HOWEVER, I strongly suggest putting the randomization in MySQL, to
Simplify your code
Significantly improve the performance, and
Eliminate excessive loops & recursion in PHP
Example:
$sql = "SELECT id,url
FROM tbl_gallery2
ORDER BY RAND()
LIMIT 3";
$query = mysql_query ($sql);
if (mysql_num_rows($query) >= 3) {
while ($r = mysql_fetch_row($query)) {
echo '<img src="./images/slider/' . $r[1] . '.jpg" alt="" class="slider" />';
}
}
PS - I also suggest you update your code to use mysqli, as mysql is deprecated
PPS - I also suggest you look into mysqli_fetch_assoc so you can reference query results by name instead of index (e.g. $r['url'] instead of $r[1] - as if you ever change the order of your query, you will break references by index.
I need to loop through a recordset (PHP + MySQL), grouping each 2 records in a list item
My actual code (semplified) is this:
<?php
// how many total records do I have?
mysql_select_db($database_connEIB, $connEIB);
$query_rsMediaCount = "SELECT COUNT(*) AS med_count FROM media";
$rsMediaCount = mysql_query($query_rsMediaCount, $connEIB) or die(mysql_error());
$row_rsMediaCount = mysql_fetch_assoc($rsMediaCount);
$mCount = $row_rsMediaCount['med_count']; // total records
$mPages = ceil($mCount / 2); // max LIs to create
$mIndex = 0; // useful initialization for LIMIT, see below
if ($mCount > 0) { // let's show markup only if there's some record!
?>
<ul>
<?php for ($mPage = 1; $mPage <= $mPages; $mPage++) { // create the LIs ?>
<li>
<?php
$query_rsMedia = "SELECT med_id FROM media LIMIT $mIndex, 2";
$rsMedia = mysql_query($query_rsMedia, $connEIB) or die(mysql_error());
$row_rsMedia = mysql_fetch_assoc($rsMedia);
do { ?>
<div><?php echo $row_rsMedia['med_id']; ?></div>
<?php } while ($row_rsMedia = mysql_fetch_assoc($rsMedia));
$mIndex += 2; // increment the LIMIT by 2 steps ?>
</li>
<?php } ?>
</ul>
<?php } ?>
The output is sort like this:
<ul>
<li>
<div>1</div>
<div>2</div>
</li>
<li>
<div>3</div>
<div>4</div>
</li>
<li>
<div>5</div>
</li>
</ul>
Everything works, but is there a more elegant or efficient solution?
Thanks in advance
Do only one query and group the results within the loop. Use the modulo operator %:
$query_rsMedia = "SELECT med_id FROM media";
$rsMedia = mysql_query($query_rsMedia, $connEIB) or die(mysql_error());
if (mysql_num_rows($rsMedia) > 0) { // check if there is at least one result
echo '<ul>';
$index = 0;
while ($row_rsMedia = mysql_fetch_assoc($rsMedia)) {
if ($index % 2 == 0) echo '<li>'; // open <li> bevore even result
echo '<div>'.$row_rsMedia['med_id'].'</div>';
if ($index % 2 == 1) echo '</li>'; // close <li> after odd result
$index++;
}
if ($index % 2 == 1) echo '</li>'; // close <li> if odd result count
echo '</ul>';
}
(just written, not testet)
I would try to run fewer queries.
$query_rsMedia = "SELECT med_id FROM media";
$rsMedia = mysql_query($query_rsMedia, $connEIB) or die(mysql_error());
$count = 0;
echo '<ul>';
while($row = mysql_fetch_assoc($rsMedia))
{
//check divisibility to know when to show li
if ($count % 2 == 0) {
echo '<li>';
}
echo '<div>' . $row['med_id'] . '</div>';
$count++;
if ($count % 2 == 0) {
echo '</li>';
}
}
if ($count % 2 == 1) echo '</li>';
echo '</ul>';
Ask query once without the LIMIT statement. Then do something like this:
$iteration=0;
echo '<li><ul>';
while ($row_rsMedia = mysql_fetch_assoc($rsMedia)
{
echo '<div>'.$row_rsMedia['med_id'].'</div>';
$iteration++;
if ($iteration%2==0 && $iteration<$mCount)
echo '</ul><ul>'
}
echo '</ul><li>';
I would separate the HTML and PHP for ease of reading first. Also, I am not entirely convinced of the do...while loop that actually prints the result (what if the table was empty?).
Your code also contains two distinct ideas (generating the list and getting the page count), so I would break them into two separate functions. Makes code easier top read.
It may, therefore, look like this:
<ul>
<?php generateList(); ?>
</ul>
<?php
function getPageCount() {
mysql_select_db($database_connEIB, $connEIB);
$query_rsMediaCount = "SELECT COUNT(*) AS med_count FROM media";
$rsMediaCount = mysql_query($query_rsMediaCount, $connEIB) or die(mysql_error());
$row_rsMediaCount = mysql_fetch_assoc($rsMediaCount);
$mCount = $row_rsMediaCount['med_count'];
$mPages = ceil($mCount / 2);
}
function generateList()
$mIndex = 0;
$mPages = getPageCount();
if ($mCount > 0) {
for ($mPage = 1; $mPage <= $mPages; $mPage++) {
$result = "<li>" ;
$query_rsMedia = "SELECT med_id FROM media LIMIT $mIndex, 2";
$rsMedia = mysql_query($query_rsMedia, $connEIB) or die(mysql_error());
$row_rsMedia = mysql_fetch_assoc($rsMedia);
while ((row_rsMedia = mysql_fetch_assoc($rsMedia)) != null) {
$result .= "<div>".$row_rsMedia['med_id']."</div>";
}
$mIndex += 2;
$result .= "</li>
}
echo $result;
}
?>
Hope it helps.