# loop de doop! Need advice on loops.



## CharlieMouse (Jun 13, 2003)

Hay,
I am setting up a picture galley using mysql and php, I am storing the names of the pictures and other info into the database,(not using a gd).

I am able to get the results from the DB and display them on the page, in table format, Problem is its only 1 rows, becouse I don't lnow how to break out of the while or do while loop to print the first row, create a new row and pick up where it left off.


Bascily what I got is a thumbnail gallery with all the pictures aligned in the center running across the page.


I need some advice on how to create an automaded script,(has to be able to write code from the choices the sufer make from pull down menu)

Which loop, or array, etc, should I use.

Thanks for any advice you can provide.


----------



## coderitr (Oct 12, 2003)

What language?


----------



## Snake~eyes (Apr 18, 2002)

It's PHP, reread his post 


> _Originally posted by CharlieMouse:_
> *I am setting up a picture galley using mysql and php*


Anyways show me the code that you have now. I really don't understqand what you're trying to do but maybe if i see the code it will help.


----------



## CharlieMouse (Jun 13, 2003)

What happens is when I view the page the webserver put all the images on the same row in the table like in the attachment below ss.bmp what I want is to display the pictures in 4 rows.

I use the javascript code.
var x=1
while(x<5){
document.write("[TD]<img src=nameofpic.jpg>[/TD]");
x++
}
var x=5
while(x<10){
document.write("[TD]<img src=nameofpic.jpg>[/TD]");
x++
}
var x=10
while(x<15){
document.write("[TD]<img src=nameofpic.jpg>[/TD]");
x++
}

What that does it create a loop that prints out a template I use to make gallerys only a few words have to be changed for each page.

in php I use this script:

<?php
include('./connect.inc');

mysql_select_db("pgdb",$db);

$result = mysql_query("SELECT * FROM imageinfo WHERE Catogory='black'",$db);

if ($myrow = mysql_fetch_array($result)) {

echo "
<img src=%s%s border=0 width=45 height=45>\n", $myrow[3], $myrow[1], $myrow[2], $myrow[1]);

} while ($myrow = mysql_fetch_array($result));

echo "
\n";

do {

printf("
[TD]\n";

} else {

echo "Sorry, no records were found!";

}

?>

it only display 1 row like in the attachment ss1.bmp below


----------



## CharlieMouse (Jun 13, 2003)

ok I cant get the screenshot to upload to TSG


----------



## Snake~eyes (Apr 18, 2002)

I'm still confused, the part I don' tunderstand is why you use javascript?

Here is a rough design of what will output the stuff in rows with 4 columns. I'm not sure if this works. Infact I might have made an ovious error, which I did before and I had to edit it. I THINK this works. I wrote this real quick and everything but good luck trying it out. 

```
int $counter=0;
echo("[TR]");
while ($myrow = mysql_fetch_array($result))
{
	echo("[TD]");
	echo($myrow[$counter]);
	echo("[/TD]");
	$row_num = ($counter + 1) % 4;
	if($row_num == 0)
		echo("[/TR][TR]");

}
echo("[/TR]");
```


----------



## CharlieMouse (Jun 13, 2003)

sorry I did not explain, I used javascript in the past, thats how I used to make my pages. I was just using that little script as an example of what I needed but in php. Plus I forgot to put in two lines on that example so it probley doesn't work right. 

Any ways you probley been to a site where you had a choice of what to wanted to view from a drop down menu or raido button, or check box etc. and it queryed the DataBase and displayed the results in a certain format. Thats what I am tring to learn to do, I have got book after book and I can't fnd one that gives good info on how to get results from a DB. 

All the online help I can find Like Dev Shed.com, have tutorials, for creating a picture gallery but they all use the a Gd. 

I am tring to learn one step at a time, took a while b ut I finaly learned how to display pictures from a Db. 
I'll give your script a try, and get back to you.


----------



## Guy (Feb 19, 1999)

Tip: use [ code][ /code] tags (without the leading space) to display code or [ php][ /php] to do php specifically

okay is this something like you want? (added code is bold)


```
<?php
include('./connect.inc');
$MAX_ACROSS = 4;
// you may want the above variable to be created dynamically
// based on the size of the window or thumbnails but I will just
// use a static value for this example
mysql_select_db("pgdb",$db);
$result = mysql_query("SELECT * FROM imageinfo WHERE Catogory='black'",$db);
if ($myrow = mysql_fetch_array($result))
{
    $count = 0;
    echo "[TABLE][TR]\n";
    do
    {
        printf("[TD][URL]<img src=%s%s border=0 width=45 height=45>[/URL][/TD]\n", $myrow[3], $myrow[1], $myrow[2], $myrow[1]);
        $count++;
        if( $count == $MAX_ACROSS )
        {
            echo( "[/TR]\n[TR]" );
            $count = 0;
        }
    } while ($myrow = mysql_fetch_array($result));
echo "[/TR][/TABLE]\n";
}
else
{
    echo "Sorry, no records were found!";
}
?>
```


----------



## Snake~eyes (Apr 18, 2002)

That's basically what my code is, except a little simpler, mine is just the loop part.


----------



## Guy (Feb 19, 1999)

Yeah sorry snake~eyes, for some reason I didnt catch your code. Didnt mean to steal your thunder.


----------



## CharlieMouse (Jun 13, 2003)

wow great work guys the scripts works great.


but that created another problem, now I got row with 4 across how do I stop it at 4 rows down, and contiune on a seperate page, like gallery 1 and than gallery 2. 

I found a great tutorial at Dev Shed on how to create next and last links autmicaly, but I have ben unable to modify it to work for me. Took me a while to understand the script you wrote but I think I understand


----------



## CharlieMouse (Jun 13, 2003)

I found this great script from Dev Shed but have been unable to modify to work with my db

```
<?
// Set Script Variables
$DB_Host="localhost";
$DB_Name="MyDataBase";
$DB_User="MyUserName";
$DB_Pass="MyPassword";
$Per_Page=10;
// Open MySQL Connection
$Connection=mysql_connect($DB_Host, $DB_User, $DB_Pass);
// Run The Query Without a Limit to get Total result
$SQL="SELECT COUNT(*) AS Total FROM Products WHERE Description LIKE '%".$_REQUEST['Keyword']."%'";
$SQL_Result=mysql_db_query($DB_Name, $SQL);
$SQL_Result_Array=mysql_fetch_array($SQL_Result);
$Total=$SQL_Result_Array['Total'];
// Create a new SELECT Query with the ORDER BY clause and without the COUNT(*)
$SQL="SELECT * FROM Products WHERE Description LIKE '%".$_REQUEST['Keyword']."%' ORDER BY ProductID";
// Append a LIMIT clause to the SQL statement
if (empty($_GET['Result_Set']))
   {
   $Result_Set=0;
   $SQL.=" LIMIT $Result_Set, $Per_Page";
   }else
   {
   $Result_Set=$_GET['Result_Set'];
   $SQL.=" LIMIT $Result_Set, $Per_Page";
   }
// Run The Query With a Limit to get result
$SQL_Result=mysql_db_query($DB_Name, $SQL);
$SQL_Rows=mysql_num_rows($SQL_Result);
// Display Results using a for loop
for ($a=0; $a < $SQL_Rows; $a++)
    {
    $SQL_Array=mysql_fetch_array($SQL_Result);
    $Product=$SQL_Array['Name'];
    $Description=$SQL_Array['Description'];
    echo "$Product - $Description

";
    }
// Create Next / Prev Links and $Result_Set Value
if ($Total>0)
   {
   if ($Result_Set<$Total && $Result_Set>0)
      {
      $Res1=$Result_Set-$Per_Page;
      echo "[URL]<;<; Previous Page[/URL] ";
      }
   // Calculate and Display Page # Links
   $Pages=$Total / $Per_Page;
   if ($Pages>1)
      {
      for ($b=0,$c=1; $b < $Pages; $b++,$c++)
          {
          $Res1=$Per_Page * $b;
          echo "[URL]$c[/URL] \n";
          }
      }
   if ($Result_Set>=0 && $Result_Set<$Total)
      {
      $Res1=$Result_Set+$Per_Page;
      if ($Res1<$Total)
         {
         echo " [URL]Next Page >>[/URL]";
         }
      }
   }
// Close Database Connection
mysql_close($Connection);
?>
```


----------



## CharlieMouse (Jun 13, 2003)

here a link to the site

http://www.devshed.com/Server_Side/PHP/Paginating/print_html


----------



## Snake~eyes (Apr 18, 2002)

> _Originally posted by Guy:_
> *Yeah sorry snake~eyes, for some reason I didnt catch your code. Didnt mean to steal your thunder.  *


Ahaha its okay. I'm just messin around. The more the better, because theres a better chance I might learn somthing better or learn a better alogrithm.


```
if($counter=="")
       $counter=0;

echo("<tr>");
while (($myrow = mysql_fetch_array($result)) && (($counter+1) % 16 != 0))) 
{
echo("<td>");
echo($myrow[$counter]);
echo("</td>");
$row_num = ($counter + 1) % 4;
if($row_num == 0)
echo("</tr><tr>");

}
echo("</tr>");


<a href="photopage.php?counter="<? echo $counter; ?>">Next Page</a>
```
okay I'm really tired. I know this isn't goign to work. But maybe you'll ge the idea 
Also you may want to rename counter through oout the program to somthing better because its going to be in the address.

Sorry, I will try a little later when I'm feeling better but maybe Guy can help out.


----------



## CharlieMouse (Jun 13, 2003)

I have found yet anothre great script but I can not get it to work either

```
designplace.org search script



<?php

  // Get the search variable from URL

  $var = @$_GET['q'] ;
  $trimmed = trim($var) //trim whitespace from the stored variable

// rows to return
$limit=10;

// check for an empty string and display a message.
if ($trimmed == "")
  {
  echo "

Please enter a search...

";
  exit;
  }

// check for a search parameter
if (!isset($var))
  {
  echo "

We dont seem to have a search parameter!

";
  exit;
  }

//connect to your database ** EDIT REQUIRED HERE **
mysql_connect("localhost","username","password"); //(host, username, password)

//specify database ** EDIT REQUIRED HERE **
mysql_select_db("database") or die("Unable to select database"); //select which database we're using

// Build SQL Query  
$query = "select * from the_table where 1st_field like \"%$trimmed%\"  
  order by 1st_field"; // EDIT HERE and specify your table and field names for the SQL query

 $numresults=mysql_query($query);
 $numrows=mysql_num_rows($numresults);

// If we have no results, offer a google search as an alternative

if ($numrows == 0)
  {
  echo "
[B][SIZE=13]Results[/SIZE][/B]
";
  echo "

Sorry, your search: "" . $trimmed . "" returned zero results

";

// google
 echo "

[URL]Click here[/URL] to try the 
  search on google

";
  }

// next determine if s has been passed to script, if not use 0
  if (empty($s)) {
  $s=0;
  }

// get results
  $query .= " limit $s,$limit";
  $result = mysql_query($query) or die("Couldn't execute query");

// display what the person searched for
echo "

You searched for: "" . $var . ""

";

// begin to show results set
echo "Results";
$count = 1 + $s ;

// now you can display the results returned
  while ($row= mysql_fetch_array($result)) {
  $title = $row["1st_field"];

  echo "$count.) $title" ;
  $count++ ;
  }

$currPage = (($s/$limit) + 1);

//break before paging
  echo "
";

  // next we need to do the links to other results
  if ($s>=1) { // bypass PREV link if s is 0
  $prevs=($s-$limit);
  print " [URL]<< 
  Prev 10[/URL]&nbsp ";
  }

// calculate number of pages needing links
  $pages=intval($numrows/$limit);

// $pages now contains int of pages needed unless there is a remainder from division

  if ($numrows%$limit) {
  // has remainder so add one page
  $pages++;
  }

// check to see if last page
  if (!((($s+$limit)/$limit)==$pages) && $pages!=1) {

  // not last page so give NEXT link
  $news=$s+$limit;

  echo " [URL]Next 10 >>[/URL]";
  }

$a = $s + ($limit) ;
  if ($a > $numrows) { $a = $numrows ; }
  $b = $s + 1 ;
  echo "

Showing results $b to $a of $numrows

";

?>
```
all of these scripts use a form which I do not have set up(or really want at this point)

I have not been able to modify your last script snake~eyes to work.


----------



## CharlieMouse (Jun 13, 2003)

can someone help me fill in the missing code,
Ok I got it where it count the rows in the search and display the next last links. There are 53 rows(Records in DB). When you click on the next link and will take you to the next page. which is what I want but I do not know how to get it to display the Pictures as well as the next/last links. Right now it display blank pages with the words Next and Last on them.

heres the Code I have Now.

```
<?PHP
include('./connect.inc');
if(!isset($start)) $start = 0;

$query = "SELECT * FROM $table where Catogory='sc' LIMIT " . $start . ", 10";

$result = mysql_query($query);

$query = "SELECT count(*) as count FROM $table where Catogory='sc'"; 
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$numrows = $row['count'];
if($start > 0) 
   echo "[URL]Previous[/URL]
\n";

if($numrows > ($start + 10)) 
   echo "[URL]Next[/URL]
\n";
?>
```


----------

