How to load image from the database in html? - php

This is my code.
<img src="getimage.php?id=1" alt="Delicious World" />
This is getimage.php
<?php
$id = $_GET['id'];
// do some validation here to ensure id is safe
$link = mysql_connect("localhost", "root", "");
mysql_select_db("db_cupcake");
$sql = "SELECT image FROM item WHERE id=$id";
$result = mysql_query("$sql");
$row = mysql_fetch_assoc($result);
mysql_close($link);
header("Content-type: image/jpeg");
echo $row['0'];
?>
I have directly stored the image in the database. I want to load those images in the webpage. Help me out.

First things first . If you are passing variables in the mysql query , then use quotations .Only then mysql will execute the query .
your query :- $sql = "SELECT image FROM item WHERE id=$id";
Instead use this query :- $sql = "SELECT image FROM item WHERE id='$id'";
And to display the image you can use
echo $row['image'];

You need to echo $row[image]; not echo $row[0];

<?php
$id = $_GET['id'];
// do some validation here to ensure id is safe
$link = mysql_connect("localhost", "root", "", "db_cupcake");
$result = mysql_query("SELECT image FROM item WHERE id=$id");
$row = mysql_fetch_assoc($result);
header("Content-type: image/jpeg");
echo $row['image'];
mysql_close($link);
?>

Related

What PHP function should I use to call the id of a dynamic page?

I'm creating a news website, and want to create a dynamic PHP page that will have the header and footer, and get the content itself (title and text) from the database by calling the article's id via the URL(like 'article.php?id=1'), so that there is no need for creating a new file for each article. However, I don't know what function should I use to make that work. Currently, the code is like this:
<?php
include "header.php";
$query = "SELECT title_article, subtitle_article, content_article FROM tb_article WHERE id_tb_article = 1";
$conn = mysqli_connect('127.0.0.1:3307', 'root', '', 'article') or die("error");
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<div class='titlediv'><h1 class='title'>" . $row["title_article"]. "</h1></div><div class='titlediv'><h3 class='title'>". $row["subtitle_article"]. "</h3></div><div class='textdiv'><p class='text'>" . $row["content_article"]. "</p></div><br>";
}
} else {
echo "Article not found";
}
include "footer.php";
?>
To get the id value from query string in URL, you can use the PHP's superglobal $_GET['id'].
To select a dynamic value from SQL using this value you must use prepared statements with parameter binding.
Your code with all the fixes would look more or less like this:
<?php
include "header.php";
$query = "SELECT title_article, subtitle_article, content_article FROM tb_article WHERE id_tb_article = 1";
// Enable mysqli error reporting and NEVER die()
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli('127.0.0.1:3307', 'root', '', 'article');
$conn->set_charset('utf8mb4'); // You should always specify the correct charset, which most of the time should be utf8mb4
// prepare -> bind -> execute -> get result
$stmt = $conn->prepare('SELECT title_article, subtitle_article, content_article
FROM tb_article
WHERE id_tb_article = ? ');
$stmt->bind_param('i', $_GET['id']);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows) {
// output data of each row
foreach ($result as $row) {
echo "<div class='titlediv'><h1 class='title'>" . htmlspecialchars($row["title_article"]). "</h1></div>";
echo "<div class='titlediv'><h3 class='title'>". htmlspecialchars($row["subtitle_article"]). "</h3></div>";
echo "<div class='textdiv'><p class='text'>" . htmlspecialchars($row["content_article"]). "</p></div><br>";
}
} else {
echo "Article not found";
}
include "footer.php";
Whenever output values into HTML context always do it via htmlspecialchars
You can use a GET method and the url look like 'article.php?id=2'.
<?php
include "header.php";
//use GET to get the id
$id = $_GET["id"];
// use .$id to concat to the query
$query = "SELECT title_article, subtitle_article, content_article FROM tb_article WHERE id_tb_article = ".$id;
$conn = mysqli_connect('127.0.0.1:3307', 'root', '', 'article') or die("error");
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<div class='titlediv'><h1 class='title'>" . $row["title_article"]. "</h1></div><div class='titlediv'><h3 class='title'>". $row["subtitle_article"]. "</h3></div><div class='textdiv'><p class='text'>" . $row["content_article"]. "</p></div><br>";
}
} else {
echo "Article not found";
}
include "footer.php";
?>
You want to look at the global variables $_GET and $_POST. In your example ('article.php?id=1') you will find the value of 'id' in $_GET['id'].
URL: article.php?id=42
echo $_GET['id']; // Outputs 42
Remember that anyone can change that value in the URL and even injecting malicious queries into your query. Its better to at least cast your id to an integer first and use always mysqli_real_escape_string() for URL given variables in the query.
URL: article.php?id=42;DROP TABLE tb_article
echo $_GET['id']; // Outputs "42;DROP TABLE tb_article", would delete your table when used directly
// Convert to an integer value
$id = intval($_GET['id']); // Returns 42
$query = "... FROM tb_article WHERE id_tb_article = ".mysqli_real_escape_string($id);

How to display blob with PHP?

Why can't my php display the image?
<?php
include("sql.php");
//$sql = "SELECT * FROM filesdb WHERE fileid = 5";
$id = $_GET['id'];
// do some validation here to ensure id is safe
$sql = "SELECT * FROM filesdb WHERE fileid =$id";
echo $sql."<br>";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
//header('content-type: image/jpeg');
echo "<br>Fileid:".$row['fileid'];
echo "<br>FileName:".$row['filename'];
header("Content-Type: image/jpeg");
echo "<br>".$row['dbforfile'];
}
it can display fileid and filename, but not dbfofile, which is a BLOB.
If you're downloading the file contents, you must not put HTML elements around it.
You can also only send one image at a time, so there's no point in looping.
<?php
include("sql.php");
//$sql = "SELECT * FROM filesdb WHERE fileid = 5";
$id = $_GET['id'];
// do some validation here to ensure id is safe
$sql = "SELECT dbforfile FROM filesdb WHERE fileid =$id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
header('content-type: image/jpeg');
$row = $result->fetch_assoc();
echo $row['dbforfile'];
}
You are only doing one image, so you don't need a loop. But if you want to do multiples; you need to use an img tag and call another PHP script as if it were an image in the src and have that script output the image (with headers). Or you can use base64 encoded data as the image source in the tag:
while($row = $result->fetch_assoc()) {
echo "<br>Fileid:".$row['fileid'];
echo "<br>FileName:".$row['filename'];
echo "<br>";
echo '<img src="data:image/jpeg;base64,'.base64_encode($row['dbforfile']).'"/>';
}

php script does not show all images stored in a table

in mysql Datbase there is images stored using php Script (image got from a form.html/POST method) let's cal them (phpImages). and there is others stored using android application ( by converting Bitmap to String and using StringBuilder ). let's call them (androidImages).
with this php script i can load and display phpImages, but i cannot display androidImages.
<?php
$con = mysqli_connect("localhost","root","","othmane") or die(mysqli_error($con));
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
$sql = "SELECT image FROM images WHERE id = '$id'";
$r = mysqli_query($con,$sql) or die(mysqli_error($con));;
$result=mysqli_fetch_array($r);
header('Content-Type:image/jpeg');
echo ( $result['image']);
mysqli_close($con);
}
?>
with this php script i can load androidImages, but i cannot load phpImages :
<?php
$con = mysqli_connect("localhost","root","","othmane") or die(mysqli_error($con));
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
$sql = "SELECT image FROM images WHERE id = '$id'";
$r = mysqli_query($con,$sql) or die(mysqli_error($con));;
$result=mysqli_fetch_array($r);
header('Content-Type:image/jpeg');
echo base64_decode( $result['image'] );
mysqli_close($con);
}
?>
i wan't a php script that could display the both. because i want to load all images in a ListView of an android Apps.
**This is php script relied to android Application : **
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$image = $_POST['image'];
$con=mysqli_connect("localhost","root","","othmane")or die(mysqli_error($con));
$sql = "INSERT INTO images (image,image_type) VALUES (?,'android')";
$stmt = mysqli_prepare($con,$sql);
mysqli_stmt_bind_param($stmt,"s",$image);
mysqli_stmt_execute($stmt);
$check = mysqli_stmt_affected_rows($stmt);
if($check == 1){
echo "Image Uploaded Successfully";
}else{
echo "Error Uploading Image";
}
mysqli_close($con);
}else{
echo "Error";
}
?>
this is php Script relied with Form.html post method :
<?php
echo ini_get( 'file_uploads' );
if(!isset($_POST['submit'])){
echo '<p>Please Select Image to Upload</p>';
}
else
{
try {
upload();
}
catch(Exception $e)
{
echo '<h4>'.$e->getMessage().'</h4>';
}
}
function upload(){
$imgfp = fopen($_FILES['photo']['tmp_name'], 'rb');
print_r($_FILES);
$dbh = new PDO("mysql:host=localhost;dbname=othmane", 'root', '');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("INSERT INTO images (image,image_type) VALUES (?,'php')");
$stmt->bindParam(1, $imgfp, PDO::PARAM_LOB);
$stmt->execute();
}
?>
Add a column called image_type in your table and pass one of the following values to determine what the source of the image is upon uploading: phpImage or androidImage
So you can do:
<?php
$con = mysqli_connect("localhost","root","","othmane") or die(mysqli_error($con));
if ($_SERVER['REQUEST_METHOD'] == 'GET'){
$id = $_GET['id'];
$sql = "SELECT image, image_type FROM images WHERE id = '$id'";
$r = mysqli_query($con,$sql) or die(mysqli_error($con));
$result = mysqli_fetch_array($r);
header('Content-Type: image/jpeg');
if ($result['image_type'] == 'phpImage') {
echo ( $result['image']);
} else if ($result['image_type'] == 'androidImage') {
echo base64_decode( $result['image'] );
}
mysqli_close($con);
}
?>

How I can navigate to another page and display user data?

I know how to fetch user data from database with the code below. Now I want to navigate to another page (using onclick) and to display this user data by id. This would be like StackOverflow or Facebook, when you click on a photo or ID, and the site takes you to the user's profile page.
Here is my code so far:
<?php
$connect = mysql_connect("localhost","root","") or die(mysql_error());
$select = mysql_select_db("profile") or die(mysql_error());
$result = mysql_query("SELECT * FROM users order by id DESC");
$id = $_SESSION['id'];
while($row = mysql_fetch_array($result)){
if($row['id'] !== $id){
echo "<table id='suggest'><tr><td id='frienddata'><a href='http://localhost/profile/userprofile.php'>".$row['first'].' '. $row['last']."<a/></td><br></tr></table>";
}
}
?>
$id = $_GET['id'];
if(!isset($id))
{
$connect = mysql_connect("localhost","root","") or die(mysql_error());
$select = mysql_select_db("profile") or die(mysql_error());
$result = mysql_query("SELECT * FROM users WHERE id = '"$id"'");
if(!$result)
{
die('user_not_found');
}
mysqli_fetch_row( $result );
echo "<table id='sugest'><tr><td id='frienddata'><a href='http://localhost/profile/userprofile.php'>".$row['first'].' '. $row['last']."<a/></td><br></tr></table>";
suppose you are in a page before clicking on a user profile,the link should be some thing like this 'site.com/userprofile.php?id=5'.
now in userprofile.php:
$id = $_GET['id'];
if(!isset($id))
die('user not found');
$connect = mysql_connect("localhost","root","") or die(mysql_error());
$select = mysql_select_db("profile") or die(mysql_error());
$result = mysql_query("SELECT * FROM users where id='".$id."'");
if (!$result) {
die('user not found');
}
$row = mysql_fetch_row($result);
echo "<table id='sugest'><tr><td id='frienddata'><a href='http://localhost/profile/userprofile.php'>".$row['first'].' '. $row['last']."<a/></td><br></tr></table>";

How can I unlink multiple images at once?

I have this code which will delete images with the category name from my database and but it only unlink one image from my images folder but I need it to unlink multiple images at once can anyone help here is an example of my code.
if(isset($_GET['delete'])) {
$delete_id = $_GET['delete'];
$sql = "SELECT image FROM images WHERE category = '$delete_id'";
$query = mysqli_query($connection,$sql) or die (mysqli_error());
while ($row = mysqli_fetch_array($query)){
$image = $row['image'];
$location_full_image = "../images/$image";
$location_thumb_image = "../images/thumbnails/$image";
#unlink($location_full_image);
#unlink($location_thumb_image);
$sql = "DELETE FROM images WHERE category = '$delete_id'";
$query = mysqli_query($connection,$sql) or die (mysqli_error());
}
}
try below code and make sure you are fetching right column from database which contains image name.
if(isset($_GET['delete'])) {
$delete_id = $_GET['delete'];
$sql = "SELECT image FROM images WHERE category = '$delete_id'";
$query = mysqli_query($connection,$sql) or die (mysqli_error());
while ($row = mysqli_fetch_array($query)){
$image = $row['image'];
#unlink('../images/'.$image);
#unlink('../images/thumbnails/'.$image);
$sql = "DELETE FROM images WHERE category = '$delete_id'";
$query = mysqli_query($connection,$sql) or die (mysqli_error());
}
}
Try this,
while ($row = mysqli_fetch_array($query)){
$image = $row['img'];
#unlink("images/".$image);
}

Categories