Adding pagination to my mysql query [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP & MySQL Pagination
I'm a bit confused as to how to add pagination to my mysql query, since I am looping through the results and adding them to a variable each time:
$DBQuery3 = mysqli_query($dblink, "SELECT * FROM images WHERE project_id = '$FormProjectID'");
$ProjectContent ='';
while($row = mysqli_fetch_array($DBQuery3)) {
$DBImageID = $row['image_id'];
$DBProjectID = $row['project_id'];
$DBImageName = $row['image_name'];
$DBImageDescription = $row['image_description'];
$DBDateCreated = $row['date_created'];
$DBLinkToFile = $row['link_to_file'];
$DBLinkToThumb = $row['link_to_thumbnail'];
$DBGivenName = $row['given_name'];
//if the image was given a name by the user, display it
//otherwise display the generated name
if (strlen($DBGivenName) > 1) {
$FileName = $DBGivenName;
} else {
$FileName = $DBImageName;
}
$ProjectContent .= '
<img src="uploads/'.$DBLinkToThumb.'" width="150px" height="150px" alt="'.$FileName.'" title="'.$FileName.'"/>
';
Any pointing in the right direction would be greatly appreciated.

Hy,
Try use a php pagination script, there are a lot on the net, just search for those words.
For example this: http://www.coursesweb.net/php-mysql/pagination-class-script_s2 can paginate data stored into a database, or into an array.

Related

How to select first row then other rows from a single mysql query? [duplicate]

This question already has answers here:
pdo how to check if it is 1st record that retrieve from database?
(2 answers)
How to separate first result of query from the rest?
(3 answers)
php while loop if to do for first row else to do for second row?
(1 answer)
Closed 3 years ago.
I may be missing the obvious, how could I return the results I need? Take a look at this simple example:
$fetch_image = "SELECT image_url FROM table"; //returns about 10 rows
$stmt_img = $db->prepare($fetch_image);
$stmt_img->execute();
$stmt_img_result = $stmt_img->get_result();
while ($row_img = $stmt_img_result->fetch_assoc()) {
$image = $row_image['image_url'];
echo 'Image url: '.$image.'<br>'; //this will echo out 10 times.
}
The above code iterates through all 10 rows. How could I return the first row from the result set, and then the other 9 rows?
Edit: I'm trying to create an image previewer so that the first image shows up as the placeholder/main image then the other 9 rows show up as the thumbnails, something like this:
<div class="sp-wrap">
<a href="images/1.jpg">
<!-- This would be the placeholder/main/first image from the mysql result set -->
<img src="images/1_tb.jpg" alt="">
</a>
<!-- In real life these would be dynamically generated -->
<img src="images/3_tb.jpg" alt="">
<img src="images/4_tb.jpg" alt="">
<img src="images/5_tb.jpg" alt="">
<img src="images/6_tb.jpg" alt="">
</div>
A simple boolean variable can distinguish the first row:
$first_row = true;
while ($row_img = $stmt_img_result->fetch_assoc()) {
if ($first_row) {
echo 'the first row';
$image = $row_image['image_url'];
echo 'Image url: '.$image.'<br>';
$first_row = false;
} else {
$image = $row_image['image_url'];
echo 'Image url: '.$image.'<br>'; //this will echo out 9 times.
}
}
You may try to get the first row, and then the rest. But you need an ORDER BY clause in your SQL statement that will order rows in the same way in every execution.
<?php
$fetch_image = "SELECT image_url FROM table"; //returns about 10 rows
$stmt_img = $db->prepare($fetch_image);
$stmt_img->execute();
$stmt_img_result = $stmt_img->get_result();
// Fetch first row
if ($row_first = $stmt_img_result->fetch_assoc()) {
$image = $row_first['image_url'];
echo 'Image url: '.$image.'<br>';
}
// Fetch next rows
while ($row_next = $stmt_img_result->fetch_assoc()) {
$image = $row_next['image_url'];
echo 'Image url: '.$image.'<br>';
}
?>
Another possible approach is to implement custom check for first row:
<?php
$fetch_image = "SELECT image_url FROM table"; //returns about 10 rows
$stmt_img = $db->prepare($fetch_image);
$stmt_img->execute();
$stmt_img_result = $stmt_img->get_result();
$first = true;
while ($row_img = $stmt_img_result->fetch_assoc()) {
if ($first) {
// Specific output for the first row
$first = false;
$image = $row_image['image_url'];
echo 'Image url: '.$image.'<br>'; // this will echo out 1 time.
} else {
// Specific output for the next rows
$image = $row_image['image_url'];
echo 'Image url: '.$image.'<br>'; // this will echo out count - 1 times.
}
}
?>
make imageType Column in your table then use this query
SELECT image_url FROM table order by imageType`
give value 1 to the image you want to appear first in the loop.
if your first row is having the first image then you don't need imageType column. you can simply use
SELECT image_url FROM table order by id
where id is you PRIMARY KEY
but still, the above method is a more dynamic approach in case your records will change in the future. it is better to give them imageType column for future use which is more proper way instead of just getting the first record from the database.
$stmt_img = $db->prepare($fetch_image);
$stmt_img->execute();
$stmt_img_result = $stmt_img->get_result();
if ( $firstrow = mysql_fetch_assoc($stmt_img_result) ) {
$image = $firstrow['image_url'];
echo 'Image url: '.$image.'<br>'; //this will echo out 1 times.
while($row = mysql_fetch_assoc($stmt_img_result)) {
$image = $row['image_url'];
echo 'Image url: '.$image.'<br>'; //this will echo out 9 times.
}
}

Accidental infinite while loop in PHP [duplicate]

This question already has answers here:
The 3 different equals
(5 answers)
Closed 6 years ago.
Hi I have created a while loop but cannot understand why it loops forever. Could somebody please explain why?
while ($i<3){
if ($i=1){
$x='psu';
}else if ($i=2){
$x='cases';
}
$sqlcpu = "SELECT * FROM $x WHERE name LIKE '%{$term}%'";
$query = mysqli_query($db, $sqlcpu);
while ($row = mysqli_fetch_array($query)){
?><br /> Name: <?php echo $row['name'];?>
<?php
echo ' Price: £'.$row['price'];
}
$i++;
}
There are other problems with this code but they are not my main concern right now as this loop seems like it should be simple. The variables $x and $i never change after $i=1
if ($i=1) You're assinging 1 to $i here, instead of comparing 1 and $i, use
if ($i==1)
instead.
Instead of the for/if-elseif construct you could also use
foreach( array('psu', 'cases') as $table ) {
$sqlcpu = "SELECT * FROM $table WHERE name LIKE '%{$term}%'";

PHP code not running successfully

My question is very simple. The code I have written here produces absolutely no output on the webpage. I've been at it all day and I'm sure that it's something very simple that I am being an idiot for missing. So I am appealing to your good-natured fresh eyes! If anyone can spot a reason why this isn't working, I'd be very grateful.
The premise:
This is a decision tree online survey that has the following conditions: if a user has already started the survey, it will find them in the database, find their last answered question and display the next one. But if they haven't started, it will display the first question.
All survey questions are held in the database as well as the decision tree logic (for instance, if the user chooses option 2 for question 1, they will be directed to question 3, not 2).
Please assume that for the moment, I am updating relevant info directly from the database and not automating it on the website.
Thanks :)
PHP:
<?php
//Find the latest question reached by the user for display on the page
$sql = mysql_query("SELECT QuestionNumberReached FROM User WHERE EmailAddress = '***'");
$sqlCount = mysql_num_rows($sql);
if ($sqlCount > 0) {
while ($row = mysql_fetch_array($sql)) {
$QuestionNumberReached = $row["QuestionNumberReached"];
}
}
?>
<?php
//Find the last question answered by the user from the database
$StartedQuery = mysql_query("SELECT LastQuestionAnswered FROM User WHERE EmailAddress = '***'");
//Count the number of rows that the query produces
$StartedQueryCount = mysql_num_rows($StartedQuery);
//If data is found, whether it be a number or null, define the value
if ($StartedQueryCount > 0) {
while ($row = mysql_fetch_array($sql)) {
$LastQuestionAnswered = $row["LastQuestionAnswered"];
//If the field has a value and is not null, find the next question from the database
if (!empty($LastQuestionAnswered)) {
//Find the User's ID and the ID of the last question answered
$sqlA = mysql_query("SELECT PKID, LastQuestionAnswered FROM User WHERE EmailAddress = '***'");
//If the operation produces an error, output an error message
if (!$sqlA) {
die('Invalid query for SQLA: ' . mysql_error());
}
//Count the number of rows output
$sqlACount = mysql_num_rows($sqlA);
//If rows exist, define the values
if ($sqlACount > 0) {
while ($row = mysql_fetch_array($sqlA)) {
$sqlAPKID = $row["PKID"];
$sqlALastQuestionAnswered = $row["LastQuestionAnswered"];
}
}
//Find the answer given by the user to the last answered question
$sqlB = mysql_query("SELECT Answer FROM Responses WHERE User = $sqlAPKID");
//If the operation produces an error, output an error message
if (!$sqlB) {
die('Invalid query for SQLB: ' . mysql_error());
}
//Count the number of rows output
$sqlBCount = mysql_num_rows($sqlB);
//If rows exist, define the values
if ($sqlBCount > 0) {
while ($row = mysql_fetch_array($sqlB)) {
$sqlBAnswer = $row["Answer"];
}
}
//Find the number of the next question to be answered based on the user's previous answer and the question they answered
$sqlC = mysql_query("SELECT NextQuestion FROM Answers WHERE QuestionNumber = $sqlALastQuestionAnswered AND PKID = $sqlBAnswer");
//If the operation produces an error, output an error message
if (!$sqlC) {
die('Invalid query for SQLC: ' . mysql_error());
}
//Count the number of rows output
$sqlCCount = mysql_num_rows($sqlC);
//If rows exist, define the values
if ($sqlCCount > 0) {
while ($row = mysql_fetch_array($sqlC)) {
$sqlCNextQuestion = $row["NextQuestion"];
}
}
//Find the question text pertaining to the ID of the next question that needs to be answered
$sqlD = mysql_query("SELECT QuestionText FROM Questions WHERE PKID = $sqlCNextQuestion");
//If the operation produces an error, output an error message
if (!$sqlD) {
die('Invalid query for SQLD: ' . mysql_error());
}
//Count the number of rows output
$sqlDCount = mysql_num_rows($sqlD);
//If rows exist, define the values
if ($sqlDCount > 0) {
while ($row = mysql_fetch_array($sqlD)) {
$SurveyStartedQuestionText = $row["QuestionText"];
}
}
//Set a string of information that will show the question number and question text as appropriate
$ToDisplay = '' . $QuestionNumberReached . ': ' . $SurveyStartedQuestionText . '<br /><br />Answer Text Here';
//If the value for QuestionNumberReached is null, the user has not started the survey
} else if (empty($LastQuestionAnswered)) {
//Find the question text of the first question in the survey
$sql3 = mysql_query("SELECT QuestionText FROM Questions WHERE PKID IN (SELECT FirstQuestion FROM Batch WHERE BatchNumber IN (SELECT BatchNumber FROM User WHERE EmailAddress = '***'))");
//Count the number of rows output
$sql3Count = mysql_num_rows($sql3);
//If rows exist, define the values
if ($sql3Count > 0) {
while ($row = mysql_fetch_array($sql3)) {
$SurveyNotStartedQuestionText = $row["QuestionText"];
}
}
//Set a string of information that will show the question number and question text as appropriate
$ToDisplay = '' . $QuestionNumberReached . ': ' . $SurveyNotStartedQuestionText . '<br /><br />Answer Text Here';
}
}
}
?>
HTML:
<body>
<?php
// Display the concatenated information that has been previously defined
echo $ToDisplay;
?>
</body>
This bit:
if ($StartedQueryCount > 0) {
probably evaluates to false, and there's no matching else tag that adds content.
Try changing:
}
?>
with:
}
else {
$ToDisplay = 'Error: no rows found to display!';
}
?>
Edit:
Also, this bit:
} else if (empty($LastQuestionAnswered)) {
Could be replaced with the more readable:
} else {
Since it does exactly the same thing.
And within your while loop, you are constantly redefining $ToDisplay, I assume this is wanted behaviour? Otherwise initialize the variable on top (before the while() loop) like so:
$ToDisplay = '';
And change the assignments within the loop to concatenations, like so:
$ToDisplay = 'text assignment';
To:
$ToDisplay .= 'text concat'; // look at the dot before =
Thank you for all your help! I really appreciate you all taking the time.
I finally realised what was wrong...
On Line 18 of my PHP code, I had the following:
while ($row = mysql_fetch_array($sql)) {
whereas it should of course have been this:
while ($row = mysql_fetch_array($StartedQuery)) {
Essentially I was calling the rows from the wrong query. And I feel a clot because of it!
Thanks again, everyone :)

if else statement with loop in while loop/php

I will admit right now I have gone through all of the posts though I went through to 2008. My problem is that the if else statement is only receiving one row and calling all the others false off of both of the while loops or receives 2 when you use the form. I am trying to see if in all the rows if a item is bought using 2 different databases. Here is the code.
$id2 = $_SESSION['id'];
$naturesql = mysql_query("SELECT * FROM backgrounds WHERE type=2");
while($row = mysql_fetch_array($naturesql)) {
$id = $row['id'];
$name = $row['name'];
$background = $row['background'];
$pic = $row['image'];
$check = mysql_query("SELECT * FROM store_items WHERE userid='$id2'");
while($checkrow = mysql_fetch_array($check)) {
$types = $checkrow['type2'];
}
if($id == $types) {
$bought = 'This item has already been bought';
} else {
$bought = '<form>
</form>';
// this form works fine
}
$display .= '<table width="100%"><tr><td><center><font size="+1">' . $name . '</font></center></td></tr><tr><td><center><img src="' . $pic . '" width="80px"></img></center></td></tr><tr><td>' . $bought . ' </td></tr></table>';
}
...
<?php echo $display ?>
What shows up.
1st result
Name 1
Pic 1
form shows up here
2nd result
Name 2
Pic 2
form also shows up here
3rd and last result
Name 3
Pic 3
This item has already been bought
This is what I get when I look on the page. If I bought a item this is what I get lets say 1st item.
1st result
Name 1
Pic 1
This item has already been bought
2nd result
Name 2
Pic 2
form also shows up here
3rd and last result
Name 3
Pic 3
This item has already been bought
It pops this up. Though when I refresh turns back into the the 1st one I shown only showing 1 result. Any thoughts why not working with the others.
It should be like this if you bought all but is not
1st result
Name 1
Pic 1
This item has already been bought
2nd result
Name 2
Pic 2
This item has already been bought
3rd and last result
Name 3
Pic 3
This item has already been bought
My only other question is there an alternative to this so keeps the loop and checks if the statement is true or not like a if else statement. If I can't do it with if else statement.
First of all you can summarize this in 1 query (it's not in 2 database, but in 2 tables it seems from your code)
SELECT b.*, s.type2 AS store_items_type2
FROM backgrounds AS b
LEFT JOIN store_items AS s ON (s.type2 = b.id AND s.userid='$id2')
WHERE b.type=2
How come $id2 = $_SESSION['id'];? A session ID is not the same as a user ID..
You should try to put a little more effort in constructing your question and the code, to make it more understandable for us.
I can't post everything on here though here should give some in site what I did to get this to work. Surprisingly it worked like a charm. Note to everyone putting in 2 tables in one mysql_query didn't help at all it just made things worse. So I wouldn't advise it for this.
Simple version I did
$id = $_SESSION[id];
$check = mysql_query("SELECT * FROM store_items WHERE userid='$id2'");
while($checkrow = mysql_fetch_array($check)){
$types = $checkrow['type2'];
}
$naturesql = mysql_query("SELECT * FROM backgrounds WHERE type=2");
while($row = mysql_fetch_array($naturesql)) {
$id = $row['id'];
$name = $row['name'];
$background = $row['background'];
$pic = $row['image'];
$check = mysql_query("SELECT * FROM store_items WHERE userid='$id2' AND type=2 AND type2='$id' AND other='$pic'");
while($checkrow = mysql_fetch_array($check)) {
$types = $checkrow['type2'];
}
if($id == $types) {
$bought = 'This item has already been bought';
} else {
$bought = '<form>
</form>';
// this form works fine
}
$display .= '<table width="100%"><tr><td><center><font size="+1">' . $name . '</font></center></td></tr><tr><td><center><img src="' . $pic . '" width="80px"></img></center></td></tr><tr><td>' . $bought . ' </td></tr></table>';
}
Like I promised I would post if I figured it out. Might of toke a little longer then I hoped but well there you go.

Mystified about making a PHP double-query dynamic list work. Using PHP 5.3.5

I'm trying to create a dynamic list (5 row results) in php by first getting data from one table then using a resulting var to get the latest uploaded "image_links" (just 1 from each of the 5 artists) from another table -- then echo out.
The code here gives me the only one row with the latest image. When I comment out the "// get the latest image link uploaded ///" section of the code I get the 5 rows of different artists I really want but, of course, w/o images. I tried (among a bunch of things) mysql_result() w/o the while statement but that didn't work.
So what am I missing?
Thanks
Allen
//// first get the artists followed ////////////////
$QUERY= "SELECT * FROM followArtist WHERE user_id = $user_id ";
$res = mysql_query($QUERY);
$num = mysql_num_rows($res);
if($num>0){
while($row = mysql_fetch_array($res)){
$artist_name = $row['artist_name'];
$artist_id = $row['artist_id'];
$date_lastSent = $row['date_lastSent'];
$date_artPosted = $row['date_artPosted'];
$date_notePosted = $row['date_notePosted'];
//// get new notice data /////
if ($date_artPosted >= $date_lastSent) {
$artp = "new artwork posted";
}else{
$artp = "";
}
if ($date_notePosted >= $date_lastSent) {
$notep = "news/announcement posted";
}else{
$notep = "";
}
if ($artp!="" && $notep!="") {
$and = " and<br />";
}else{
$and = "";
}
if ($artp=="" && $notep=="") {
$no = "No new images or news posted since your<br /> last visit, but we'll let you know when there is.";
}else{
$no = "";
}
//////// get the latest image link uploaded ////////////////////////////////////
$QUERY2="SELECT image_link FROM artWork WHERE artist_id ='$artist_id' AND make_avail = '1' ";
//ORDER BY date_submit DESC
$res = mysql_query($QUERY2);
$num = mysql_num_rows($res);
if($num>0 ){
while($row = mysql_fetch_assoc($res)){
mysql_fetch_assoc($res);
$image_link= $row['image_link'];
}
//////// end of get the latest images uploaded ////////////////////////////////
echo "<tr align=\"center\" height=\"115px\">
<td align=\"left\" width=\"15%\"> <a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\">
<img src=slir/w115-h115/$path$image_link /></a></td>
<td align=\"center\" width=\"80%\"
<span class=\"deviceMedLtGrayFont\">$artist_name</span>
<br /><br />
<a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\"/>
$artp</a>
<a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\"/>
$and$no</a>
<a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\"/>
$notep</a>
</td>
</tr>";
} //// end bracket for getting latest image link
} ///loop end for getting followed artist data
} ///end: if ($num>0) clause<code>
If I read your code correctly, I see you looping using data from query1 in the control structure, and a lookup on query2 within each loop. You are reusing the variables in your loop1 control structure for query2 ($num and the query handle ($res)) for the second loop. Probably not desirable within the loop.
You're sharing the variables $num and $res between the two queries ... your original properties will be overwritten when the second query is run. Use different property names for the inner query.
Example of problem:
$result = QueryA();
while( $row = $result->getRow() )
{
// -- You're overwriting the original result here ...
$result = QueryB();
// Next time the loop runs, it will run using the result from QueryB();
}
So change ...
$res = mysql_query($QUERY2);
$num = mysql_num_rows($res);
if($num>0 )
{
while($row = mysql_fetch_assoc($res))
{
mysql_fetch_assoc($res);
$image_link= $row['image_link'];
}
to
$res2 = mysql_query($QUERY2);
$num2 = mysql_num_rows($res2);
if($num2 > 0)
{
while($row2 = mysql_fetch_assoc($res2))
{
$image_link= $row2['image_link'];
}
this is a mess - as others have said you're using the same variables for different purposes.
That you're storing integers which seem to represent enumerations in a char field is bad.
You're iterating through the second result set to find the last record (from an unsorted result set!).
You only need one query - not 2.
SELECT f.artist_name, f.artist_id, f.dateLastSent....
SUBSTR(
MAX(
CONCAT(DATE_FORMAT(date_submit, '%Y%m%d%H%i%s'), a.image_link)
), 15) as img_link
FROM followArtist f
LEFT JOIN artWork a
ON (a.artist_id=f.artist_id AND a.make_avail = '1')
WHERE user_id = $user_id
GROUP BY f.artist_name, f.artist_id, f.dateLastSent....

Categories