How to select multiple rows from one result set - php

Alright, a bit of context: I'm trying to display images(the image is in the table) in four boxes at the bottom of a page. However, I can't figure out how to select all four images from one result set. I've been looking around but it feels like none of the answers that I've found apply to what I'm trying to do...
my SQL is:
SELECT image FROM products WHERE popular = '1'
image is the image name that i'm pulling from the table.(i.e 'image'.jpg)
and this is the PHP I currently have(pardon if it's nasty, it's been changed multiple times in the past hour and a half, as no solution I've tried has worked:)
$sql_getpopular = "SELECT image FROM products WHERE popular='1'";
$result_getpopular = $mysqli->query($sql_getpopular);
$rows_getpopular = mysqli_fetch_row($result_getpopular);
$rows[0] = $rows_getpopular;
$rows_getpopular = mysqli_fetch_row($result_getpopular);
$rows[1] = $rows_getpopular;
$rows_getpopular = mysqli_fetch_row($result_getpopular);
$rows[2] = $rows_getpopular;
$rows_getpopular = mysqli_fetch_row($result_getpopular);
$rows[3] = $rows_getpopular;
also, i've tried doing this in a loop, but that didn't work either. that's why I've got it all written out like this.
and here is what I'm trying to display it in:
<div><?php echo "<img src='images/products/" . $rows[0] . ".jpg'>"; ?></div>
<img id="spacing">
<div><?php echo "<img src='images/products/" . $rows[1] . ".jpg'>"; ?></div>
<img id="spacing">
<div><?php echo "<img src='images/products/" . $rows[2] . ".jpg'>"; ?></div>
<img id="spacing">
<div><?php echo "<img src='images/products/" . $rows[3] . ".jpg'>"; ?></div>

Your main issue is with
$rows[0] = $rows_getpopular;
as mysqli_fetch_row() returns a enumerated array so it would need to be
$rows[0] = $rows_getpopular[0];
Using loops - ie. while() and foreach() - specifically could reduce your code
to get the image into $rows use while()-
$sql_getpopular = "SELECT image FROM products WHERE popular='1'";
$result_getpopular = $mysqli->query($sql_getpopular);
while($rows_getpopular = mysqli_fetch_row($result_getpopular)){
$rows[] = $rows_getpopular[0];
}
to echo the image values, use foreach() -
<?php foreach($rows as $row){ ?>
<div><?php echo "<img src='images/products/" . $row . ".jpg'>"; ?></div>
<img id="spacing">
<?php } ?>

Related

Displaying image as image gallery using PHP derived from phpmyadmin(MySQL)

I am using PHP, HTML, and MySQL to build a website.
So, my goal is to make an image gallery for my webpage which should display only 3 images each row.
But my code seems wrong and I do not know where should I do the correction.
-) Here is my code:
$query = mysql_query("SELECT DISTINCT * FROM products WHERE catID = 11 ORDER BY typeID ASC");
echo "<table>";
while ($row = mysql_fetch_assoc($query))
{
echo "<tr>";
for ($c = 0; $c < 3; $c += 1){
echo "<td>";
echo '<img src="data:image/jpg;base64,'.base64_encode($row['productImg'] ).'" width="300" height="200" alt=""
/>';
echo "<br>";
echo "<b>";
echo $row['productName'];
echo "</b>";
echo "<br>";
// More detail button set up
?>More Detail <i class="fa fa-arrow-circle-o-right"></i> <?php
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
-) Here is the result:
wrong result image
The result turns out not what I expected since on 1 row it displays 3 same images. What I wanted is to display 3 different images on each
row. I do not know where I did wrong.
The result turns out not what I expected since on 1 row it displays 3 same images.
That's because of the for loop, you are looping through the same image three times. Instead use a counter variable $counter to track number of iterations and display three different images per row.
<?php
$query = mysql_query("SELECT DISTINCT * FROM products WHERE catID = 11 ORDER BY typeID ASC");
if(mysql_num_rows($query)){
$counter = 0;
echo "<table><tr>";
while ($row = mysql_fetch_assoc($query)) {
if($counter != 0 && $counter % 3 == 0){
echo "</tr><tr>";
}
echo "<td>";
echo '<img src="data:image/jpg;base64,'.base64_encode($row['productImg'] ).'" width="300" height="200" alt=""/>';
echo "<br>";
echo "<b>";
echo $row['productName'];
echo "</b>";
echo "<br>";
// More detail button set up
?>
More Detail <i class="fa fa-arrow-circle-o-right"></i>
<?php
echo "</td>";
++$counter;
}
echo "</tr></table>";
}
?>
Sidenote: Don't use mysql_* functions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. Use mysqli or pdo instead. And this is why you shouldn't use mysql_* functions.

Have Image Files Printed on Screen Inside While Loop (Corresponding to the Thread ID)?

This Question Has Gotten Updated:
I have these columns stored in the table "thread":
id - title - caption - image_file_id - hashtag_id - date_created
An example for "image_file_id", it are the ID numbers of the "images" table for the image files:
583, 584, 585
The script should get the "title" and the "caption" from the "thread" table and print them with a while loop, then it also should get the image files from the "images" table and also print them corresponding to the thread ID.
E.g.
Thread ID: 35
<h1>Title</h1>
<p>Caption</p>
1. <img src=""/>
2. <img src=""/>
3. <img src=""/>
4. <img src=""/>
Thread ID: 36
<h1>Title</h1>
<p>Caption</p>
1. <img src=""/>
2. <img src=""/>
EDIT:
After the suggestion by "Steve" I have gotten it to work with this script here:
<!DOCTYPE html>
<html>
<head>
<title>
</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
</head>
<body>
<?php
include("connect.php");
?>
<?php
$tqs = "SELECT * FROM `thread`";
$tqr = mysqli_query($dbc, $tqs) or die(mysqli_error($dbc));
// $row = mysqli_fetch_assoc($tqr);
// The ID numbers of the image files.
// This prints e.g.:
// Array ( [0] => 583 [1] => 584 [2] => 585 )
// print_r($exploded);
// echo "<br/><br/>";
//This prints e.g.:
// 3
// print_r(count($exploded));
// Select the image files by the ID numbers
// Iterate through he image files:
while ($row = mysqli_fetch_assoc($tqr)){
echo "<div class='content'>";
echo "<div class='title_caption'>";
echo "<h1>" . $row['title'] . "</h1>";
echo "<p>" . $row['caption'] . "</p>";
echo "</div>";
echo "<div class='parent-container'>";
// Have the image files printed on screen here!
$exploded = explode(", ", $row['image_file_id']);
foreach($exploded as $id){
$tqs_two = "SELECT `image_file` FROM `images` WHERE `id` = '" . $id . "'";
$tqr_two = mysqli_query($dbc, $tqs_two) or die(mysqli_error($dbc));
$row_two = mysqli_fetch_assoc($tqr_two);
echo "<img src='http://localhost/gallerysite/multiple_image_upload/thumbs/" . $row_two['image_file'] . "' />";
}
echo "</div>";
echo "</div>";
}
?>
</body>
</html>
I would like to ask if this script is correct, as said it is working.
This script goes row by row, though my question would be: how can I ensure that the image files are correctly printed on screen corresponding to the "thread ID"?
You can simplify this by using IN query, to reduce you overall number of queries:
$tqs = "SELECT * FROM `thread`";
$tqr = mysqli_query($dbc, $tqs) or die(mysqli_error($dbc));
while ($row = mysqli_fetch_assoc($tqr)){
echo "<div class='content'>";
echo "<div class='title_caption'>";
echo "<h1>" . $row['title'] . "</h1>";
echo "<p>" . $row['caption'] . "</p>";
echo "</div>";
echo "<div class='parent-container'>";
// No need to explode, just use IN query
$tqs_two = "SELECT `image_file` FROM `images` WHERE `id` IN ({$row['image_file_id']})";
$tqr_two = mysqli_query($dbc, $tqs_two) or die(mysqli_error($dbc));
while($row_two = mysqli_fetch_assoc($tqr_two)){
echo "<img src='http://localhost/gallerysite/multiple_image_upload/thumbs/" . $row_two['image_file'] . "' />";
}
echo "</div>";
echo "</div>";
}
Ideally you would have the image ids stored in a normalized fashion - eg using a lookup table, but then you could do the whole thing with one query.

Need ideas in proper html rendering with php

I have constructed an SQL query to lay out some info on a web page. The query works well. The problem is with each iteration of while loop a CSS class needs to be auto-incremented by 1.
<div class="related-item item1">
'item1' should become 'item2' in the next iteration and so on. Can you give me something ideas how to do it?
<?php
//Construct the SQL query code
$rel = "SELECT entries.*, images.name
FROM entries, images
WHERE entries.id = blog_id
ORDER BY dateposted DESC
LIMIT 0, 3;";
//Send the query to the MySQL server
$result = mysql_query($rel);
//Pull the row as an associative array
while ($row = mysql_fetch_assoc($result)) {
echo '<div class="related-item item1">
<div class="thumbnail-wrapper">';
echo '<img src="./images/' . $row['name'] . '" alt="How SHAPE Reader Caitlin Flora Lost 182 Pounds"/></div>
<h4 class="related-article-title">
' . $row['subject'] . '
</h4>
</div>';
} //End of while loop
?>
Just keep a counter variable going
$cnt = 1;
while(fetch from db) {
echo "<a class='foo{$cnt}'>click me</a>";
$cnt++;
}
which produces
<a class='foo1'>click me</a>
<a class='foo2'>click me</a>
<a class='foo3'>click me</a>
etc...
but generally this sort of thing is NOT necessary for CSS. You'd have to create a css rule for EVERY one of those <a> elements being created, which gets incredibly ugly and repetitive. There is nth-child support in CSS, so you can write rules which "modify" themselves based on which child an element is (1st, 2nd, ... Nth).
Add an integer and increment it...
<?php
//Construct the SQL query code
$rel = "SELECT entries.*, images.name
FROM entries, images
WHERE entries.id = blog_id
ORDER BY dateposted DESC
LIMIT 0, 3;";
//Send the query to the MySQL server
$result = mysql_query($rel);
$i = 1;
//Pull the row as an associative array
while ($row = mysql_fetch_assoc($result)) {
echo '<div class="related-item item{$i}">
<div class="thumbnail-wrapper">';
echo '<img src="./images/' . $row['name'] . '" alt="How SHAPE Reader Caitlin Flora Lost 182 Pounds"/></div>
<h4 class="related-article-title">
' . $row['subject'] . '
</h4>
</div>';
$i++;
} //End of while loop
?>

PHP - Image output: strange string

I have to output a series of random images previously saved inside a DB.
At the moment of the output, instead print a picture, the code print a strange string (meaby dumpfile?):
(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢¢’ú~ü±®æIüa¤Äû[SÓÕºàܦ'$·›ØÒ¢°o>)xvÀŸ7ZÓדþULünð®ì.±„ðFíŸÉj=¬íìæöLꨮ6ã㦇êW8b³|Ä⪟ÚL-…Óu¦ÇRmÕ#ÿǪ^"’ûH¯cQô;Ê+ÏeøýC£Ý:ó÷çHÏåTnh[­¿»ÐãRz/Ïýò¦£ë”—_ÌW©Øõ +Écý µIæùltuà¯Údfúgg_´­ÿh1ÿMÓ?O&à¹ü™ùÒXÊ/¯æSÂÔ]H¢¼õi £mœÝ[°ë¹Pãòlþ•¥iñïÂwmµudVÎèd~;qúÖ‘ÄR{IèT_e…‹iñ#Ã÷»|½kKfnŠnQXþ浭ŒFßµ¦´ÖëöÏôpND;W?ÝL…V9à'5ÏSK–GE<,çhŸNîWϺoÇu·\ëW–¹É˜Í ¯ÕÖRºgß½^“Äñ_D¬ºÕ×™ÈÿM‘”þ$°üy¬þ¹…}R]Ot¨n5;{?õ×Åþû…þuóî¦öîònû»,ñ³Ãþ†¨ËtÖŸô €ò“üÿLGþ5/ýÒヿSè¼s¢Û¶×Ö4µoF»ŒZ‚‰:°ùµK^ÿp—þUàªI(eä{z ³œÁyú`U9V5>c¤…T‚7ØÉz®EGץصƒ]Yï|n𼃪+Ù ‘赿41þ«í·î#WÿBÅxŒ­ªmÿH½ó±)_ å³O·˜Jî±ÚÝ6:eb…‰õû£ô¨xéô±_S‡™ì§ãréÚ§# 7’3ÿ‘*´¿­óˆ´é™²Ïqÿ"kËžÂiUzÛ«­rƒóÀþ•Nh$óTIçÎPmn§Àú€ê?J—Œ¨RÂÀõi~:ÜÿË=Y¼oT5Vããn´Ì='O…›§uŸýšòñ£GqüVJ­ü|Óϳ1Ç¥8h&7GjÁ;maíÇ9ÅfñU{”°Ô»_yè—µhŸC·œ€ÿÌ·ôª³üsÔ¤ÿW¨i¬Ýˆ+üëˆ&ÞÏ8¸’>p°R3þî)ñ[­óñ%ño{–eÿЇYªú—õzk¡ÖIñ{W½UªH¥€ÿWj}ú*§7Å#îó5«ÍÃÑZ1ü¿•ssè6¨Û¦U™¾ñÖ }2ÇóÅ8-¸m¶²dÿN¨ÓŒÔ:•V5NšÙÒüGšBÊ××ó?ç´Ÿ úV|þ&þЙn$QÔõÇJlSB]•¡‡o\;·õëS‰]¢†=¸àˆœ¨={ŸåëÞ£ß{²’ŠÙ÷¬Ï»ì3Éè¼ûöÜjIDiá¤Ä«Û|hÌ?J-æ˜Ûå)çæ…rãüõ©Ròt’B­œÿ¬‰8úýj,Ê¿b8šêÕwCco©þ€h¼Ôµgý\kï'ò;³ú~U$º
My code:
<?php
include_once('conn.php');
$n="SELECT COUNT('id_product')
FROM 'products'";
$value=mysql_query($n);
do
{
$selectionASC='SELECT id_product
FROM products
ORDER BY id_product ASC
LIMIT 1';
$selectionDESC='SELECT id_product
FROM products
ORDER BY id_product DESC
LIMIT 1';
$ASC=mysql_query($selectionASC)
or die ('Impossible execute the query <br />').mysql_error();
$DESC=mysql_query($selectionDESC)
or die ('Impossible execute the query <br />').mysql_error();
//____________________________________________________________________
$ASC = mysql_num_rows($ASC);
$DESC = mysql_num_rows($DESC);
$rand_n=rand(($ASC-1),($DESC+1));
//____________________________________________________________________
$selected='SELECT id_product,name, price, img
FROM products
WHERE id_product='.$rand_n;
$selected = mysql_query($selected);
//____________________________________________________________________
while($row=mysql_fetch_row($selected))
{
echo "Product'id: &nbsp"; echo $row[0];
echo '<br />';
echo "Name: &nbsp"; echo $row[1];
echo '<br />';
echo "Price:: &nbsp"; echo $row[2];
echo '<br />';
echo "Immage: <img src='images/".$row['3']."'alt='Image'>";
echo '<hr> <br />';
$value--;
}
}
while ($value==0)
?>
The rest of the output is coherent with the code. Anyone know why it happen? And how to fix it? Thanks!
You cannot output image like what you did , first of things
when you fetch image from db .
for example if my image filed stored in img field i will call it like this
$id=$_GET['id'];
$query = mysql_query("select * from img where img id=$id ");
$row = mysql_fetch_array($query);
$img = $row['img'];
header("Content-type: image/jpeg");
print $img;
so this page only for displaying the pictures and when you want to use it you can do
<img src="display_img.php?id=2" />
it's not possible to keep every things in one page but also you can divide your page like this
if($$_GET['action']=="display_img"){
// show img code
}

PHP/MySQL query - displaying data refresher [is code syntax correct?]

This is my page from an online radio station site of mine on localhost, it's a basic PHP/MySQL one for test purposes:
<?php
mysql_connect('localhost', 'root', 'mypass') or die (mysql_error());
mysql_select_db('radiotest') or die (mysql_error());
$result = mysql_query("SELECT *, TIME_FORMAT(airtime, '%H:%i') `airtime`
from presenters");
//Table starting tag and header cells
while($row = mysql_fetch_array($result)){
//Display the results in different cells
echo "<dd><dl><img src=' " . $row['image'] . " '>" . $row['airtime'] ."
" . $row['presenter'] . "</dd></dl>";
echo "<dd><dl>" . $row['showinfo'] . "</dd></dl>";
}
?>
It works properly, displays the data from the table in the required format.
However, I want to try doing it this way:
<dd><dl><img src='<?php echo $row['image'] ?'> <?php echo $row['airtime']?>
<?php echo. $row['presenter']?> </dd></dl>
My problem: I admit I've forgotten how to do echo without displaying it in the PHP/MySQL query like above, so how can I ensure it displays the variables using echo without having to declare it in the MySQL connection? I know my original is correctly formatted, but I don't want it to have the echo variables after the while part of the syntax, I wanted to echo them within the dd / dl HTML (definition list).
Basically, I'm just trying to brush up my skills in this area; had a look on Google but am not quite sure
Any help is appreciated!
It's really no different, and definitely not better, but I think you are asking to do:
while($row = mysql_fetch_array($result)){
//Display the results in different cells
?>
<dd><dl>
<img src='<?php echo $row['image']; ?>'>
<?php echo $row['airtime']; ?> <?php echo $row['presenter']; ?>
</dd></dl>
<dd><dl>'<?php echo $row['showinfo']; ?></dd></dl>
<?php
}
Try this instead:
<dd>
<dl>
<img src='<?=$row['image'] ?>'> <?=$row['airtime'] . " - " .$row['presenter']?>
</dd>
</dl>

Categories