MySQL returning broken images - php

over the last couple of days I've been working on a application that let's a user upload a image and store the image in my filesystem and the file path in my database. I'm almost done but i have come across a brick wall.
The image gets uploaded to my filesystem and the file path stored in my database just fine. put when i go to the page that displays the images. it returns them as
"broken images"
here's the code that is giving me trouble
<?php
error_reporting (E_ALL ^ E_NOTICE);
session_start();
$uname = $_SESSION['username'];
$userid = $_SESSION['id'];
?>
<!DOCTYPE html>
<html>
<head>
<title>OurFile's Page</title>
</head>
<body>
<?php
require("pdoconn.php");
//img_path is the column in my DB that holds the image URL.
$stmt = $conn->prepare("SELECT img_path FROM ourimages");
$stmt->execute();
while($result = $stmt->fetch(PDO::FETCH_BOTH))
{
echo '<br><img src="' . $result['img_path'] . '" />';
}
$conn = null;
?>
</body>
</html>
any help would be appropriated.
Thank you for your future responses
i edited the code. using ed and jay's suggestions...but its still
output the same result

You can't do this:
<img src="<?php echo $value; ?>" />
because you're using $value to loop over every column in the table. The src attribute needs to be a URL, but I'm guessing only one column in your ourimages table holds a URL. You're outputting an image for every column thanks to this:
$stmt = $conn->prepare("SELECT * FROM ourimages"); // gets every column
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_BOTH);
foreach ($result as $value) // uses every column
{
The simple fix is to change your SQL:
$stmt = $conn->prepare("SELECT whateverColumnHasTheURL FROM ourimages");
Then use that column like this:
<img src="<?php echo $result->whateverColumnHasTheURL; ?>" />
Or, you can use the SELECT * ..., but just use the one column in the <img> tag:
$stmt = $conn->prepare("SELECT * FROM ourimages");
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_BOTH);
echo "<br>";?> <img src="<?php echo $result->whateverColumnHasTheURL; ?>" /><?php
Note: If you're actually trying to loop over the rows, you need to put $stmt->fetch in a loop, as in while ($result = $stmt->fetch(PDO::FETCH_BOTH);) { echo... }

Using a foreach loop to output the results of the query is an interesting way of doing things. Most folks use a while loop like this:
while($result = $stmt->fetch(PDO::FETCH_BOTH))
{
echo '<br><img src="' . $result['column_with_image_path'] . '" />';
}
Since you're selecting all of the columns from your table you need to be specific about the identifier you use in the image tag.

Related

Click on an image stored in a MySQL database table and get additional row content for that image

I have created a members.php page that connects to a database table. The table has the following fields: id, username, profile image.
The following PHP code displays the profile image for each user in rows of 6 and allows each image to be clickable.
<?php
// The code below will display the current users who have created accounts with: **datemeafterdark.com**
$result=mysql_query("SELECT * FROM profile_aboutyou");
$row1 = mysql_fetch_assoc($result);
$id = $row1["id"];
$_SESSION['id'] = $id;
$profileimagepath = $row1["profileimagepath"];
$_SESSION['profileimagepath'] = $profileimagepath;
$count = 0;
while($dispImg=mysql_fetch_array($result))
{
if($count==6) //6 images per row
{
print "</tr>";
$count = 0;
}
if($count==0)
print "<tr>";
print "<td>";
?>
<center>
<img src="<?php echo $dispImg['profileimagepath'];?>" width="85px;" height="85px;">
</center>
<?php
$count++;
print "</td>";
}
if($count>0)
print "</tr>";
?>
This is all great, however, when I click on the image that loads it re-directs me to: viewmemberprofile.php which is what it is supposed to do. But it always displays the same image with the same id value (i.e.) 150 no matter which image I click. What I would like to have happened is. If I click on an image with id 155 etc... it will display content for that image data field not consistently the same image data regardless of which image I click.
Your help and guidance would be greatly appreciated. Thank you in advance.
One thing that I forgot to mention is that I do use sessions so... when I am re-directed to the viewmemberprofile.php page I use the following code to aide in getting the data that I need from the table.
<?php
$id = $_SESSION['id'];
echo($id);
?>
<?php
echo('<br>');
?>
<?php
$profileimagepath = $_SESSION['profileimagepath'];
?>
<img src="<?php echo($profileimagepath);?>" width="50px;" height="50px;">
I have yet to impliment the suggested solution.
You need to pass the ID of the row to viewmemberprofile.php, e.g.:
<a href="viewmemberprofile.php?id=<?= $dispImg['profileimagepath'] ?>">
And viewmemberprofile.php needs to select that row from the DB:
SELECT * FROM profile_aboutyou WHERE id = $_GET['id']
The above SQL statement is pseudo-code; you need to write actual code to accomplish what it is describing, preferably using parameterized queries.

Can't display table contents that contain URL's from database

I'm a student using NetBeans to create very basic webpage(s) using HTML, PHP and SQLite. So far, everything is fine. The problem I have is that images aren't displayed on the moviedetails.php page. Everything else including the titles, ratings and description for each table entry works fine. (I am retrieving rows from a database table.) Here is my code:
(This is very new to me, so if it's a simple mistake, sorry for wasting your time :/)
Index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$pdo = new PDO('sqlite:movies.db'); //Import SQLite database "movies.db" to a Var
$query = $pdo->query("SELECT * FROM movie");
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
//For each id number in db, echo a hyperlink containing that ID's title and
echo '' . htmlentities($row['title']) . '';
echo '<br>';
}
?>
</body>
moviedetails.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$pdo = new PDO('sqlite:movies.db'); //Using movies.db
$query = $pdo->prepare("SELECT * FROM movie WHERE id=:id"); //Prepare this statement
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT); //GET INPUT from Variable 'id' and FILTER anything which isn't a number
$query->bindParam(':id', $id, PDO::PARAM_INT); //Bind :name 'id' to a $id variable
$query->execute(); //Execute the prepared statement
$row = $query->fetch(PDO::FETCH_ASSOC); //Fetch next row of results
//var_dump($row);
//display title, description and rating
echo '<h1>'.htmlentities($row['title']).'</h1>'; //Echo 'Title' from db into a heading
echo ''; //Echo 'image from db into a link
echo '<p>'.htmlentities($row['description']).'</p>'; //Echo 'description' from db to paragraph
echo '<p>Rating: '. htmlentities($row['rating']).'</p>'; //Echo 'rating' from db to paragraph
?>
</body>
Here is my database in an image, as this is the easiest way to show you:
http://i.cubeupload.com/TBI5Fv.png
Here is one of the webpages that should diplay a link. However, it contains only the other table fields:
http://i.cubeupload.com/1tcfsU.png
The strange thing is, it doesn't give me any errors, so I don't know where I'm going wrong.
Hope someone can help :)
Your <a> tag is empty, so it's invisible.
echo '';
You should put some content that will be displayed as a link like this:
echo 'THIS IS LINK TO IMAGE';
If you want to display the image itself instead of a link, you should use <img> tag like this:
echo '<img src="'.htmlentities($row['image']).'"/>';

how to retrive php query from db and set on textarea with executed?

This is the code which selects from DB and sets the image tag.
<div>
<?php $query = mysql_query("SELECT * FROM company where sn='1'");
while($rows = mysql_fetch_assoc($query)){
$logo = $rows['logo'];
$password = $rows['password'];
$phone = $rows['phone'];
}
?>
<img src="<?php echo $logo ?>"/>
</div>
When we get this and set on textarea then we want this query{which save in db} executed. and output show only Logo name.
But this time this show full query which save in db.
we want get this output on textarea:
<div><img src="logoname"/></div>
You are using mysql extension, which is deprecated. You should use mysqli instead.
The loop overwrites your variables ($logo, $password, $phone) in every iteration, so it makes no sense until you're fetching single row.
But if you're fetching single row, then you don't need a loop:
<?php
if ($r = mysqli_query($connection, "SELECT * FROM company WHERE sn = 1")) {
$company = mysqli_num_rows($r) ? mysqli_fetch_row($result)[0] : null;
mysqli_free_result($r);
}
?>
<img src="<?php echo empty($company) ? 'nophoto.png' : $company['logo']; ?>" />
Replace
SELECT * FROM company where sn='1'
With
SELECT * FROM company WHERE sn=1
If you take out the apostrophes, that might solve your problem since the value stored in your database is most likely not a string. Also you should have WHERE in capital letters.
Let me know if that answered your question! :)

How to echo an image at a certain id in MySql table?

I am having a little trouble trying to display the image at ID: 2 in my store table...
here's what i've come up with (p.s. the reason I set $id = 2 is because I plan on making this a loop where I will increment that value to print other images)
<!DOCTYPE html>
<html>
<head>
<title>Gallery</title>
</head>
<body>
<?php
mysql_connect ...
mysql_select_db ...
$id = 2;
$image = mysql_query("SELECT * FROM store WHERE id=$id");
$image = mysql_fetch_assoc($image);
$image = $image['image'];
echo $image;
?>
</body>
</html>
First, some caveats:
Don't use the mysql_* functions
Don't store images in SQL. Store the location. (You may already be doing this).
If you're storing the location, you'll need to add <img> tags to the echo
echo "<img src='$image'>";
Maybe you need to echo the markup also?
echo '<img src="'.$image.'">';

PHP - How to Create Dynamic URLs?

I've scoured the web for a tutorial about this simple task, but to no avail. And so I turn to you helpful comrades. Here's what I need to do:
I have a MySQL database with an Events table. I need to create a PHP web page with a list of the Event titles, and each title must be a link to the full details of the Event. But I want to avoid having to create a static page for each event, primarily because I don't want the data entry volunteer to have to create these new pages. (Yes, I realize that static pages are more SEO friendly, but I need to forego that in this case for the sake of efficiency.)
I've seen PHP url syntax with something like this:
pagename.php?id=20
but I don't know how to make it work.
Any and all help greatly appreciated.
Thanks!
Kip
This is basic php. You would simply query the DB for the event details before the page headers are written and write the html accordingly.
The first thing I would ask you is if you know how to connect to your database. From there, you query based on the $_GET['id'] value and use the results to populate your html.
Not to be rude, but the question itself suggests you're new to PHP, right? So in order to provide a solution that works we might want to know just how far you got.
Also, you can rewrite your dynamic urls to appear like static ones using apache's mod_rewrite. It's probably a novice level thing if you're interested in "pretty" url's.
MODIFIED ANSWER:
In your loop you would use the id from the query result (assuming your primary key is id)...
while($field = mysql_fetch_array($result)) {
echo "<p class='date'>";
echo $field['month']." ".$field['day'].", ".$field['year'];
echo "</p>";
echo "<h3>";
echo ''.$field['event_name'].'';
echo "</h3>";
}
Then on somepage.php you would use the get var id to pull the relevant info...
$result = mysql_query("SELECT * FROM `calendar` WHERE `id` = '".mysql_real_escape_string($_GET['id'])."');
don't forget to look into mysql_real_escape_string() for cleaning entries.
It's wise to take extra care when you are using $_GETvariables, because them can be easily altered by a malicious user.
Following with the example, you could do:
$foo = (int)$_GET['id'];
So we are forcing here the cast of the variable to a integer so we are sure about the nature of the data, this is commonly used to avoid SQL injections.
lets say you have the php file test.php
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("db", $conn);
$id = $_GET['id'];
$sql = "select * from table where id = $id";
$result = mysql_query($sql, $conn);
if ($result){
$row = mysql_fetch_row($result);
$title = $row[0];
$content = $row[1];
}
?>
<html>
<head>
<title><?php echo $title ?></title>
</head>
<body>
<h1><?php echo $title ?></h1>
<p><?php echo $content ?></p>
</body>
</html>
a dynamic page would be something like that..
Here is the pertinent code for extracting a list of events in November from a table named calendar, with each event having a link to a page called event.php and with the event's id field appended to the end of the url:
$result = mysql_query("SELECT * FROM calendar WHERE sort_month='11'");
while($row = mysql_fetch_array($result))
{echo
"<a href='event.php?id=".$row['id']."'>".$row['event_name']."</a>"
;}
And here is the pertinent code on the event.php page. Note the row numbers in brackets depends on the placement of such in your table, remembering that the first row (field) would have the number 0 inside the brackets:
$id = $_GET['id'];
$sql = "select * from calendar where id = $id";
$result = mysql_query($sql, $con);
if ($result){
$row = mysql_fetch_row($result);
$title = $row[12];
$content = $row[7];
}
?>
<html>
<head>
<title><?php echo $title ?></title>
</head>
<body>
<h1><?php echo $title ?></h1>
<p><?php echo $content ?></p>
</body>
</html>
This works for me, thanks to the help from those above.
$foo=$_GET['id'];
in your example $foo would = 20

Categories