PHP - Image output: strange string - php

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
}

Related

background style from mysqli database

I'm trying to add background image property do div. I know that I can display normal image from database like this:
echo '<img src="data:image/jpeg;base64,'.base64_encode($image).'" />';
but what about adding background to div? I tried, I really did but just my code doesn't work so i ask how to do that?
This is my code:
<?php
require_once('config.inc.php');
$sql = "SELECT id, title, author, image FROM articles ORDER BY count DESC LIMIT 3";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<a href="'.$row["id"].'">';
echo '<div class="module" style="background:'.base64_encode($row["image"]).'">';
echo '<h3 class="article-title">'.$row["title"].'<br />'.$row["author"].'</h3>';
echo '</div>';
echo '</a>';
}
} else echo "Wystąpił błąd z bazą danych";
$mysqli->close();
?>
"DIV" tag does'nt support an a base64 format. If you want to show an image in, you have to use the background-image property of CSS.
Example:
<div style="background-image:url(<?=$YourBase64?>);padding:50px;background-size:cover;background-position:center center; background-repeat:no-repeat;"></div>
You can see more about it in: https://www.w3schools.com/cssref/pr_background-image.asp
You are not telling your CSS to use a base64 encoded image, also remember in CSS you need the url() function:
echo '<div class="module" style="background-image:url(data:image/jpeg;base64,' . base64_encode($row['image']) . ')">';

Assign a Single SQL SELECT Statement query result to a PHP Variable

Hi there I have a website which takes in a Car brand and generates a Car Id result which corresponds to a database. Although there are many solutions available for storing a sql query result to a variable but in this case it does not seem to work.
I have already tried the sql statement in the database and it works with 1 result output which is right.
<?php
session_start();
include "dbconn.php";
$carcat = $_SESSION['selectedcarcat'];
$carbrand = $_POST['carbrand'];
$userid = $_SESSION['loginid'];
$username = $_SESSION['loginname'];
$startdate = $_POST['date1'];
$enddate = $_POST['date2'];
$pick = $_POST['pickuploc'];
$return = $_POST['returnloc'];
$calqty = 0;
$selcaridsql = "SELECT carid FROM cars WHERE brand='$carbrand' ";
$caridresult = $dbcnx->query($selcaridsql);
$caridrow = mysql_fetch_object($caridresult);
$carid = $caridrow['carid'];
if (!$caridresult)
{
$errmessage = "Your carid select query failed.";
echo "<script type='text/javascript'>alert('$errmessage');</script>";
}
echo '<br>Debug 1 ';
echo '<br>The selected qty is '
.$qtyresult1.'<br />';
echo '<br>The calculated qty is '
.$calqty.'<br />';
echo '<br>The content carid is '
.$carid.'<br />';
echo '<br>The content userid is '
.$userid.'<br />';
echo '<br>The content start is '
.$startdate.'<br />';
echo '<br>The content end is '
.$enddate.'<br />';
echo '<br>The content pick is '
.$pick.'<br />';
echo '<br>The content return is '
.$return.'<br />';
echo '<br>The content carbrand is '
.$carbrand.'<br />';
?>
The error occurs with a blank result shown at the "Content carid is". After going through the forums it seems that the variable $carid has no value which I may have inferred wrongly.
The echo results:
Debug 1
The selected qty is
The calculated qty is 0
The content carid is
The content userid is
The content start is 2016-10-28
The content end is 2016-10-29
The content pick is jurong
The content return is bishan
The content carbrand is Honda
Apparently after using var_dump to debug the problem as stated by Chris, the problem was narrowed down to the NULL value that was collected by the mysql_fetch_object($caridresult);. As the DB connection utilizes #$dbcnx = new mysqli('localhost','values','values','values'); the DB class is wrong for retrieving the array values. Therefore the solution would be mysqli_fetch_array.
These codes might be helpful for those trying the debug:
<?php // register.php
session_start();
include "dbconn.php";
$carcat = $_SESSION['selectedcarcat'];
$carbrand = $_POST['carbrand'];
$userid = $_SESSION['loginid'];
$username = $_SESSION['loginname'];
$startdate = $_POST['date1'];
$enddate = $_POST['date2'];
$pick = $_POST['pickuploc'];
$return = $_POST['returnloc'];
$calqty = 0;
$selcaridsql = "SELECT carid FROM cars WHERE brand='$carbrand' ";
echo $selcaridsql."<br>";
$caridresult = $dbcnx->query($selcaridsql);
echo "<br>".var_dump($caridresult);
if ($caridresult->num_rows >0 )
{
// if they are in the database register the user id
echo '<br>Hello more than 1 <br>';
}
else
{
echo '<br>Hello less than 1 <br>';
}
$caridrow = mysqli_fetch_array($caridresult);
echo var_dump($caridrow)."<br>";
$carid = $caridrow['carid'];
echo var_dump($carid)."<br>";
if (!$caridresult)
{
$errmessage = "Your carid select query failed.";
echo "<script type='text/javascript'>alert('$errmessage');</script>";
}
echo '<br>Debug 1 ';
echo '<br>The selected qty is '
.$qtyresult1.'<br />';
echo '<br>The calculated qty is '
.$calqty.'<br />';
echo '<br>The content carid is '
.$carid.'<br />';
echo '<br>The content userid is '
.$userid.'<br />';
echo '<br>The content start is '
.$startdate.'<br />';
echo '<br>The content end is '
.$enddate.'<br />';
echo '<br>The content pick is '
.$pick.'<br />';
echo '<br>The content return is '
.$return.'<br />';
echo '<br>The content carbrand is '
.$carbrand.'<br />';
?>
Special Thanks to Chris for helping to find the error!
I do not have the ability to test this right now.
However, you have confirmed that $carid has no value (is null).
And you have confirmed the SQL statement returns correct values when run against the database. Therefore, a likely problem is with the query you are sending to the database with your code.
your query:
$selcaridsql = "SELECT carid FROM cars WHERE brand='$carbrand' ";
my suggestion to fix your query:
$selcaridsql = "SELECT carid FROM cars WHERE brand='" + $carbrand + "'";
You could be sending the string literal "$carbrand" and not know it unless you printed out that SQL statement to check.
Have you tried that?
Also, please check the values of all your $_POST to be sure they are what you think they are. That is very important for security as well.
Get to those println statements and let me know what you find :-).
Print everything out and make sure your values are what you expect.
I'm 99% sure that's where the problem is.

How to select multiple rows from one result set

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 } ?>

MySQL link to return results

I have an image that is displayed from a table and I want the user to be able to click the image which directs them to a page that returns the rest of the data for that row. Do I need a php loop for this? I can't quite figure it out.
This returns the Last Name, First Name, and an Image:
<?php
if (isset($_GET['LastName'])) {
$ln = $_GET['LastName'];
}
include 'connection.php';
$query = "SELECT * FROM residents WHERE LastName like '$ln%' ";
$result = mysql_query($query);
while($person = mysql_fetch_array($result)) { ?>
<div class="media col-sm-4">
<a class="pull-left" href="redirectionpage.php?<?php echo $person['ID'];?>.php">
<img class="media-object" src="upload/<?php echo $person['Picture'];?>" width="100" height="100"/>
</a>
<div class="media-body">
<h4 class="media-heading"><?php echo $person['LastName'] . ", " . $person['FirstName']; ?></h4>
</div>
</div>
<?php }>?
Is the best way to accomplish this by redirecting the user to a new page and using a mysql statement to display the new data?
This is the code for the other page:
<?php
//Gets data from the database
include ('header.php');
include ('footer.php');
include ('connection.php');
$query = "SELECT * FROM residents WHERE ID = LastName LIMIT 1";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$outputpicture.='<div><p><img src="upload/' . $row['Picture'].'" width="450" height="550"/></p></div>';
$outputname.= $row['LastName'] . ", " . $row['FirstName']. '<br />';
$outputspouse.= $row['Spouse']. '<br />';
$outputrelatives.= $row['Relatives']. '<br />';
$outputaddress.= $row['Address']. '<br />';
$outputbirthday.= $row['Birthday']. '<br />';
$outputbegan.= $row['BeganResidence']. '<br />';
$outputended.= $row['EndedResidence']. '<br />';
$outputformer.= $row['FormerResidence']. '<br />';
$outputcareer.= $row['Career']. '<br />';
$outputeducation.= $row['Education']. '<br />';
$outputmaritalstatus.= $row['MaritalStatus']. '<br />';
$outputsiblings.= $row['Siblings']. '<br />';
$outputspecialinterests.= $row['SpecialInterests'].'<br />';
}
?>
The link needs to be changed to
<a class="pull-left" href="redirectionpage.php?id=<?php echo $person['ID'];?>">
Adding this id= will allow you to access the id parameter in redirectionpage.php via the $_GET superglobal.
$id = $_GET['id'];
You can use the $id variable to select the specified row from your database. You will see a lot of examples that do it like this:
$query = "SELECT * FROM residents WHERE ID = $id";
This works but you should not do it, because it creates an SQL injection vulnerability. Read about prepared statements and create your SQL so that you can pass the ID as a paramater.
$stmt = $pdo->prepare("SELECT * FROM residents WHERE ID = :id");
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
$stmt->execute();
This should also be applied to the code you use to select the list of images.
Assuming ID is the key for your residents table, this should select only one record, so you will not need the while loop. You can just use one fetch.

Pass Variable Through An Image Hyperlink?

how do i hyperlink an image and also pass a variable through it as well? my incorrect code is as follows:
<?php
$result=mysql_query("select serial, name, price from products ORDER BY RAND() LIMIT 3");
while($row=mysql_fetch_array($result))
{
echo '<img src="getImage.php?id=' . $row['serial'] .'"/>'.' '.' ';
}
echo "</tr>";
echo "</table>";
?>
thanks for any help guys
as Book of Zeus said, you have a syntax error:
<?php
$result=mysql_query("select serial, name, price from products ORDER BY RAND() LIMIT 3");
while($row=mysql_fetch_array($result))
{
echo '<img src="getImage.php?id=' . $row['serial'] .'"/>'.' '.' ';
}
echo "</tr>";
echo "</table>";
?>

Categories