Display as picture in PHP from MySQL?

Hi there,

You can do this using the $_GET superglobal variable.
Here is an example to demonstrate the principle.
Make a new PHP file, name it index.php, then with your favourite text editor, enter:

<?php
echo 'Hello ' . htmlspecialchars($_GET["name"]) . '!';
?>

Now access the file in your browser thus: http://site.com/index.php?name=luxuri
See how it works?

You can read more about this here: http://www.php.net/manual/en/reserved.variables.get.php

I hope that helps.

I tried it :slight_smile: it works but is it possible to use the browser link, i.e. ?id=1, then to take the row 1 from mysql and display it from there? because im having trouble referring to my older files and comprehending them.

Sure,
however, before we get into that, we should take a moment to think about the implications of passing unfiltered user input to a database query.
Imagine if a malicious user entered ?id=1; DROP review-- as a query string.
Then your MySQL query would select the appropriate data set, then promptly delete the entire table.
This is known as SQL injection.

So, one way to avoid this is to use the PDO library for your database queries.
You can read more about it here: http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/

Using this library, the code to select a row from the database (based on a $_GET variable) and output it to the screen would be like this:

<?php
$id = $_GET['id'];

// Connect to db
try
{
  $pdo = new PDO('mysql:host=_____;dbname=_____', 'user', 'password');
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $pdo->exec('SET NAMES "utf8"');
}
catch (PDOException $e)
{
  echo "Unable to connect to the database server!<br>" . $e;
  exit();
}

// The query
$sql= $pdo->prepare('SELECT * FROM review WHERE id = :id');
$sql->execute(array(':id' => $id));

// Do something with result
foreach ($sql as $row) {
  echo $row['text'];	
}
?>

As you can see, we have bound the user input to a pre-defined query, then executed it.
This goes a very long way to avoiding SQL injection attacks.

Hi, thanks for the detailed explanation. I’ll put this in my journal to record it (:

However, it doesn’t work when I load up my website… and as an amateur, I cannot trouble shoot it.

Is it okay if I do this

 $id=$rows['id'];
     $dname=$rows['name'];
     $dcomment=$rows['comment'];
     $linkspam="<a href=\\"validate.php?id=".$rows['id']."\\">Report as spam</a>";
     echo '<font color="red">Name:</font>  ' . $dname . '<br />' . '<br />' . '<font color="red">Comments:</font>  ' . '<br />' . $dcomment . '&nbsp' . '&nbsp' .

instead of

// Do something with result
foreach ($sql as $row) {
  echo $row['text'];	
}

,

or will it have no difference?

Hi,

It all depends how you are fetching data from the database.
As long as $row holds a valid dataset it doesn’t matter how you access its attributes.

You can post your code (minus passwords) if you get stuck.

Hi, I’ve looked at the site you showed me previously (tutsplus) and used their example to display my information from the database. However, it also displays some excessive numbers and letters. Currently, using your example, if I visit www.site.com/restaurant.php?id=1 , nothing will show in my content part.

Here’s the code(without passwords):

<?php
$hostname = "localhost";
$db_user = "user";
$db_password = ""
$database = "db";
$db_table = "review"; // leave this as is

$db = mysql_connect($hostname, $db_user, $db_password);
$page_title=$rows['name'];
$id=$rows['id'];
$dname=$rows['name'];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>foodhouse|<?php echo $page_title; ?></title>
<link rel="icon" type="image/png" href="favicon.png" />
<link rel="stylesheet" href="style.css" />
<script type="text/javascript" src="js/jquery-1.7.min.js"> </script>
<script type="text/javascript" src="js/jquery-ui-1.8.12.min.js"> </script>
<script type='text/javascript' src='/js/lib/mootools-core-1.3-full-compat-nc.js'></script>
<script type="text/javascript">
function Toggle(id,close,open,ms){
 var obj=document.getElementById(id),o=Toggle['zxc'+id],to;
 if (!o&&obj){
  Toggle['zxc'+id]=o={
   obj:obj,
   now:0,
   ms:500,
   ud:true
  }
 }
 if (o){
  ms=typeof(ms)=='number'?ms:o.ms;
  obj.style.display='block';
  to=o.ud?open:close;
  clearTimeout(o.dly);
  animate(o,o.now,to,new Date(),ms*Math.abs((to-o.now)/open));
  o.ud=!o.ud;
 }
}

function animate(o,f,t,srt,mS){
 var oop=this,ms=new Date().getTime()-srt,now=(t-f)/mS*ms+f;
 if (isFinite(now)){
  o.now=Math.max(now,0);
  o.obj.style.height=o.now+'px';
 }
 if (ms<mS){
  o.dly=setTimeout(function(){ oop.animate(o,f,t,srt,mS); },10);
 }
 else {
  o.now=t;
  o.obj.style.height=o.now+'px';
  if (t==0){
   o.obj.style.display='none';
  }
 }
}
</script>
<script type="text/javascript">
animatedcollapse.addDiv('jason', 'optional_attribute_string')
//additional addDiv() call...
//additional addDiv() call...
animatedcollapse.init()
</script>
<link href='http://fonts.googleapis.com/css?family=PT+Sans' rel='stylesheet' type='text/css'>
</head>

<body>
<div id="contain">
<div id="header">
<div id="hwrapper">
		<a href="#" id="logo"><img src="flogo.png" alt="Logo" width="460px" height="140px"/></a>
  </div>
</div>

<div id="container">
	<div id="line">
</div>
<div id="navbar">
    <div id="nav">
    	<ul>
        	<li><a href="#">Home</a></li>
            <li><a href="#">List</a></li>
            <li><a href="#">Submit</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#"><div class="button open-button" onMouseUp="Toggle('page-split-wrap',0,250,500);"><span style="font-style:italic; font-size:19px;">Restaurant Search</span></div></a>

</li>
        </ul>
    </div>

    <div id="body">
     <div id="page-split-wrap">
  <div class="page-split-head"> </div>
  <div class="page-split-content">
   <p class="inside">Content in here</p>
   <p class="inside">Content in here</p>
  </div>
 </div>
    <div id="wrapperb">
    <?php
$id = $_GET['id'];

// Connect to db
try
{
  $pdo = new PDO('mysql:host=localhost;dbname=db', 'user', 'pw');
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $pdo->exec('SET NAMES "utf8"');
}
catch (PDOException $e)
{
  echo "Unable to connect to the database server!<br>" . $e;
  exit();
}

// The query
$sql= $pdo->prepare('SELECT * FROM review WHERE id = :id');
$sql->execute(array(':id' => $id));

// Do something with result
foreach ($sql as $row) {
  echo $row['text'];	
}
?>
</div>
</body>
</html>

Hi,

You forgot the semicolon after $db_password = "", but I’m guessing that’s a typo, right?

Apart from that, I fear you might have misunderstood me.
You should only connect to your database once.

For the previous examples we were using mysql_connect
However, once you wanted to start feeding user input into database queries, you need to be considerably more vigilant and that’s why I recommended the PDO library.
This should then replace using mysql_connect.

So, what you need to do is get rid of the code which uses mysql_connect.
Then move the PDO code to the top of your file.
Check that you can connect to the database and select a table using this new method.
Then make a short example to check that you can display records based on what you are receiving via $_GET.

If this all sounds a bit complicated I can help you step through it if you like.

Hey,

I’m pretty sure it was a typo for that :). Now, I apologize for misunderstanding you. Again, I have yet to grasp the concepts of these, please forgive me :slight_smile:

I’ll try to figure it out on my own. If I need further help, I’ll reply here again. Thanks for the detailed explanation.
As always, thanks for your passionate help.

Hey,

No problem, everyone needs to learn somewhere.

It might be a good idea to start a new thread if you have any further questions to using the PDO library, as we have strayed somewhat from the original topic of this post, which was how to make a figure stored in a database appear as an image.

Okay. Thanks, though. I think I’ve got it working, as for now, I can get everything displaying properly, corresponding to the link.

Now, back to topic. Is it possible to display the image by means of entering the image url? For example, if I have a row called “one”, then can I insert a link inside the row, such as http://www.site.com/one.png, and then display the row “one” by showing the image? I’m asking for now because I have to go for dinner, and I’d want to try it out as soon as I get home.

Hi,

Not sure if I understand.
You want to store a URL in your database table and output it on your page?
That’s definitely possible.

Hi pullo.

thanks, I think I’ve solved this issue. please look at it and see if it is correct?
<span class=“ratings”>Rating</span>
<img src=“/img/rating’.$row[‘food’].'.png”/>

This is what I get, and in my /img/ file I have .png files from rating1.png to rating5.png, and the row[food] from 1-5 will select the respective pictures and display them.

Well done!
That looks great to me.

Thank you Pullo, so much for aiding me in the process of creating my pages. Your help is greatly appreciated - if it wasn’t for you, I don’t know if I’ll be able to finish it in time:) Thanks so much for your friendly help!

Do you mind if I use your name to reference you in my journal?

No, that’s cool.
Fame at last!
:slight_smile: