// connects to database here
if(isset($_GET['id']))
{
$id = mysql_real_escape_string($_GET['id']);
$query = mysql_query("SELECT * FROM `blob` WHERE `id`='$id'");
$data = mysql_fetch_array($query);
header("content-type: image/jpeg");
echo $imageData;
}
else
{
echo "Error!";
}
<img src="showimage.php?id=1">
the images are then being shown through and image tag shown above but they just appear as small icons (the correct number for those listed in the database but not the actual image)
First, remove the <img src="showimage.php?id=1"> and put it on a different page; you can't keep it in the same page since it causes the web server to send headers before your script is even executed; your showimage.php should only contain PHP code, nothing else.
Then, change your code like this :
$data = mysql_fetch_array($query);
header("content-type: image/jpeg");
echo $data["image"];
I assume that your row is called "image" from your previous question.
Also, don't ask multiple questions for the same problem, you already got several answers on your previous question.
Related
I want to list the contents of a 'name' column from an sql table on a HTML/PHP web page. This page currently allows me to create records, but is there a way of listing the records by name only, and displaying them somewhere specific on the HTML page?
The comments didn't seem to answer 100% to my knowledge so maybe this broad answer might help.
If you want to grab all the names located in a specific SQL table first make sure to connect to your database using
mysql_connect('SERVER', 'USER', 'PASSWORD');
mysql_select_db('DATABASENAME');
After you have connected you ran run queries to your database as stated. For your example it would be something like this:
//Query to get values
$query= mysql_query("SELECT name FROM TABLE_NAME");
//Places all query results into an array "row"
while($row = mysql_fetch_assoc($query)){
//Prints values as though it were HTML
echo $row['name']."<br>";
}
Here's an example of getting one name back from the users table and storing it in a variable to use later in the page.
<?php
$query = mysql_query("SELECT name FROM Users");
$result = mysql_fetch_array($query);
$name = $result['name'];
?>
<div class="greeting">Hello <?php echo $name; ?></div>
In a more advanced case you can also store variables in sessions (cookies) so that you can use them throughout your website (including subdomains) without having to re-query the database each time
<?php
session_start();
$query = mysql_query("SELECT name FROM Users");
$result = mysql_fetch_array($query);
$_SESSION['name'] = $result['name'];
?>
Now whenever you want to grab the variable you just got from the query simple do <?php $_SESSION['name']; ?> Just make sure that you have session_start() at the top of the page (my suggestion is place in a header file and include the header file in all pages)
Make sure your file is a .php file and you place the code about in the proper <?php ?> tags
I am only starting with PHP and as a part of exercise I wanted to design small website that allows you to upload image and then display all uploaded images
I got the image upload succesfully working and images are stored in database but I cant find the way to display images in table along with other data
$i=0;
while ($row = mysql_fetch_array($result))
{
echo '<td>'.mysql_result($result,$i,0).'</td>';
echo '<td>'.mysql_result($result,$i,1).'</td>';
echo '<td>'.mysql_result($result,$i,2).'</td>';
echo '<td>'.mysql_result($result,$i,3).'</td>';
echo '<td>'.base64_encode($result,$i,4).'</td>';
echo '<tr>';
$i++;
How to modify the code so the image is displayed?
this is code used to upload image
if (isset($_FILES['photo']))
{
#list(, , $imtype, ) = getimagesize($_FILES['photo']['tmp_name']);
// Get image type.
// We use # to omit errors
if ($imtype == 3) // cheking image type
$ext="png"; // to use it later in HTTP headers
elseif ($imtype == 2)
$ext="jpeg";
elseif ($imtype == 1)
$ext="gif";
else
$msg = 'Error: unknown file format';
if (!isset($msg)) // If there was no error
{
$data = file_get_contents($_FILES['photo']['tmp_name']);
$data = mysql_real_escape_string($data);
// Preparing data to be used in MySQL query
mysql_query("INSERT INTO {$table}
SET ext='$ext', title='$title',
data='$data'");
This is where I test it enter link description here
I was looking at Stack Overflow examples, but I couldn't find any that has the loop in it with data outputted into a table.
As you are starting with PHP, you should start with the right foot :)
Don't use mysql_* functions, these are deprecated. Instead, use mysqli_* or PDO
Storing images in the DB is "a bad idea", you better store the files in the file system (a-k.a. the HD) and reference the name to a field in the DB.
Instead of mysql_fetch_array, try with mysql_fetch_assoc so you can call the fields by name. i.e.: $row['db_field_name'];
About your problem, you will need a extra script to display the stored image. Something like this:
<?php
...
$row = mysql_fetch_assoc($result);
header("Content-type: image/jpeg"); //Set the correct image type.
echo $row['data'];
exit;
?>
And in your display html:
...
<img src="yourscript.php?image=XX" ...>
...
Hope this help :)
Please could someone help im building my first website that pulls info from a MySQL table, so far ive successfully managed to connect to the database and pull the information i need.
my website is set up to display a single record from the table, which it is doing however i need some way of changing the URL for each record, so i can link pages to specific records. i have seen on websites like facebook everyones profile ends with a unique number. e.g. http://www.facebook.com/profile.php?id=793636552
Id like to base my ID on the primary key on my table e.g. location_id
ive included my php code so far,
<?php
require "connect.php";
$query = "select * from location limit 1";
$result = #mysql_query($query, $connection)
or die ("Unable to perform query<br>$query");
?>
<?php
while($row= mysql_fetch_array($result))
{
?>
<?php echo $row['image'] ?>
<?php
}
?>
Thanks
Use $_GET to retrieve things from the script's query (aka command line, in a way):
<?php
$id = (intval)$_GET['id']; // force this query parameter to be treated as an integer
$query = "SELECT * FROM location WHERE id={$id};";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) == 0) {
echo 'nothing found';
} else {
$row = mysql_fetch_assoc($result);
echo $row['image'];
}
There are many things to consider if this is your first foray into MsSQL development.
SQL Injection
Someone might INSERT / DELETE, etc things via using your id from your url (be careful!, clean your input)
Leaking data
Someone might request id = 1234924 and you expected id = 12134 (so some sensitive data could be shown, etc;).
Use a light framework
If you haven't looked before, I would suggest something like a framework (CodeIgniter, or CakePHP), mysql calls, connections, validations are all boilerplate code (always have to do them). Best to save time and get into making your app rather than re-inventing the wheel.
Once you have selected the record from the database, you can redirect the user to a different url using the header() function. Example:
header('Location: http://yoursite.com/page.php?id=123');
You would need to create a link to the same (or a new page) with the URL as you desire, and then logic to check for the parameter to pull a certain image...
if you're listing all of them, you could:
echo "" . $row['name'] . ""
This would make the link.. now when they click it, in samepage.php you would want to look for it:
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
//query the db and pull that image..
}
What you are looking for is the query string or get variables. You can access a get variable through php with $_GET['name']. For example:
http://www.facebook.com/profile.php?id=793636552
everything after the ? is the query string. The name of the variable is id, so to access it through your php you would use $_GET['id']. You can build onto these this an & in between the variables. For example:
http://www.facebook.com/profile.php?id=793636552&photo=12345
And here we have $_GET['id'] and $_GET['photo'].
variables can be pulled out of URL's very easily:
www.site.com/index.php?id=12345
we can access the number after id with $_GET['id']
echo $_GET['id'];
outputs:
12345
so if you had a list of records (or images, in your case), you can link to them even easier:
$query = mysql_query(...);
$numrows = mysql_num_rows($query);
for ($num=0;$num<=$numrows;$num++) {
$array = mysql_fetch_array($query);
echo "<a href=\"./index.php?id=". $row['id'] ."\" />Image #". $row['id'] ."</a>";
}
that will display all of your records like so:
Image #1 (links to: http://www.site.com/index.php?id=1)
Image #2 (links to: http://www.site.com/index.php?id=2)
Image #3 (links to: http://www.site.com/index.php?id=3)
...
Okay, so this is my first project using PHP and MySQL and I thought a Facemash style site using HTML, PHP and MySQL would be good place to start.
Everything works correctly except calling the "updateHits" function as an image hyperlink doesn't behave as I'd expect.
I am confident that the MySQL database is functioning correctly and the pictures do display as expected. My research points towards the use of iFrames, jQuery or AJAX to update the "hits" field although I cannot understand how to apply them here.
I hope my code is readable and any advice would be greatly appreciated!
<html>
<body>
<?php
// Make a MySQL Connection
mysql_connect("localhost", "admin", "admin") or die(mysql_error());
mysql_select_db("facemash") or die(mysql_error());
// Select two random people
$personA = rand(1, 28);
$personB = rand(1, 28);
// Ensure that it is not the same person
if ($personB == $personA) {
$personB = rand(1, 28);
}
// Function to return path of photo
function photoPath ($person){
$query = mysql_query("SELECT photo FROM people WHERE id=$person");
$result = mysql_fetch_row($query);
$result = $result[0];
echo $result;
}
// Function to update the hits field
function updateHits($person){
$query = mysql_query("SELECT hits FROM people WHERE id=$person;");
$result = mysql_fetch_row($query);
$result = $result[0];
$result++;
mysql_query("UPDATE people SET hits = $result WHERE id=$person");
}
?>
<!--Image for personA-->
<img src="<?php photoPath($personA);?>"/>
<!--Image for personB-->
<a href="<?php updateHits($personB);?>"/><img src="<?php photoPath($personB);?>"/></a>
</body>
</html>
Thanks.
Erm, PHP does not work that way. ;)
PHP is serverside code, you're creating a link that points nowhere. To get the effect you want you'll need to make an AJAX call to the server to tell it to update the hits.
I have a site that currently uses images on a file server. The images appear on a page where the user can drag and drop each as is needed. This is done with jQuery and the images are enclosed in a list. Each image is pretty standard:
<img src='//network_path/image.png' height='80px'>
Now however I need to reference images stored as a BLOB in an Oracle database (no choice on this, so not a merit discussion). I have no problem retrieving the BLOB and displaying on it's own using:
$sql = "SELECT image FROM images WHERE image_id = 123";
$stid = oci_parse($conn, $sql);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
$img = $row['IMAGE']->load();
header("Content-type: image/jpeg");
print $img;
But I need to [efficiently] get that image as the src attribute of the img tag. I tried imagecreatefromstring() but that just returns the image in the browser, ignoring the other html. I looked at data uri, but the IE8 size limit rules that out.
So now I am kind of stuck. My searches keep coming up with using a src attribute that loads another page that contains the image. But I need the image itself to actually show on the page. (Note: I say image, meaning at least one image but as many as eight on a page).
Any help would be greatly appreciated.
Well, you can do a few things. You can either make a page that will render the image
<img src="image.php?id=123" />
That image.php page would have this:
$sql = "SELECT image FROM images WHERE image_id = " . (int) $_GET['id'];
$stid = oci_parse($conn, $sql);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
if (!$row) {
header('Status: 404 Not Found');
} else {
$img = $row['IMAGE']->load();
header("Content-type: image/jpeg");
print $img;
}
Or, you could base64 encode it into the src (note, not all browsers handle this well):
<img src="data:image/jpeg;base64,<?php echo base64_encode($img); ?>" />
But I need to [efficiently] get that image as the src attribute of the img tag
As Byron already says, the accepted and right way is to output the blob in an independent image resource, and to embed that using an img tag. It's the only good way. You can use data: URIs but they
fatten your HTML code
don't work in IE < 8 and are limited to 32 KB in IE 8,
expand the data volume by 33%, and
take away the brower's possibility to cache the image resource.
Almost never a good option.
The normal way to do this is with a <img src=/path/to/script?id=32> field. It will show up on the page not as a link. What is the problem with this? Do you want to embed the image data into HTML?
To make it more efficient, you can implement some type of caching ie, write the image data to a file and do a header(location...) if you find it instead of querying the db again. Also the browser caching headers should be set so the browser doesn't download the image if it has it cached locally.
You may try this :
$img = $row['IMAGE']->load();
print('<img src="data:image/png;base64,'.base64_encode($img).'" />');
<?php
if(isset($_POST['']))//get the id
$roll_no=$_POST[''];
$conn = oci_connect("", "", "");//DB connection
$query = 'SELECT image FROM TABLE where id=:id';
$stmt = oci_parse ($conn, $query);
oci_bind_by_name($stmt, ':id', $id);
oci_execute($stmt);
$arr = oci_fetch_array($stmt, OCI_ASSOC);
$result = $arr['image']->load();
header("Content-type: image/JPEG");
echo $result;
oci_close($conn);
?>