My image is broken when im displaying using php - php

When im displaying the image of restaurant but the image is broken.can anyone help me to solve or find out the problem?i tried to googling or looking tutorial yet i found there are several way to store image which is either storing the file path to database or storing the image to database,in my case is storing the file path to database.
this is the data in my database.the image is type is blob.
this is my html code for displaying
<?php
$sql = "SELECT * FROM restaurant";
$result = $conn->query($sql) or die($conn->error);
while ($row = $result->fetch_assoc()){
<tr>
<td>{$row['ID']}</td>
<td>";echo "<img src='".$row['Logo']."' />";echo "</td>
<td>{$row['Name']}</td>
<td>{$row['ContactNumber']}</td>
<td>{$row['Address']}</td>
<td>{$row['CuisineType']}</td>
<td>{$row['SupportArea']}</td>
</tr>\n";
}
?>
this is php code for adding restaurant
<?php
include 'db.php';
//define other variables with submitted values from $_POST
$name = $_POST['restaurant_name'];
$contactnum = $_POST['restaurant_contactnum'];
$address = $_POST['restaurant_address'];
$cuisinetype = $_POST['cuisinetype'];
$checkbox1 = $_POST['area'];
$allowedExts = array("png","jpg","jpeg"); /* ACCEPTED FILE FORMAT */
$extension = pathinfo($filename, PATHINFO_EXTENSION); /* GET THE FILE EXTENSION */
$extension = strtolower($extension); /* LOWER THE STRINGS OF THE EXTENSION */
$chk="";
foreach($checkbox1 as $chk1)
{
$chk.= $chk1.",";
}
if(in_array($extension,$allowedExts)){ /* IF FILE IS INDEED AN IMAGE */
$photo="restaurantlogo/" . $_FILES["restaurant_logo"]["name"];
}
//insert user data into database
$sql = "INSERT INTO restaurant (Logo, Name, Password, ContactNumber, Address, CuisineType, SupportArea ) VALUES ('$photo', '$name', '$password', '$contactnum', '$address', '$cuisinetype','$chk')";
$insert = mysqli_query($conn, $sql) or die(mysqli_error($conn));
//check if mysql query is successful
if ($sql){
//redirect the user to welcome.php
header("Location: ../restaurant-add.php");
}

The problem is in your PHP output. You were missing echo at multiple places and I exchanged the " for ' so the HTML <img>'s src tag is wrapped in " ".
Here is the corrected code:
<?php
$sql = "SELECT * FROM restaurant";
$result = $conn->query($sql) or die($conn->error);
while ($row = $result->fetch_assoc())
{
echo '<tr>
<td>'.$row['ID'].'</td>
<td><img src="'.$row['Logo'].'" /></td>
<td>'.$row['Name'].'</td>
<td>'.$row['ContactNumber'].'</td>
<td>'.$row['Address'].'</td>
<td>'.$row['CuisineType'].'</td>
<td>'.$row['SupportArea'].'</td>
</tr>";
}
?>

Click F12 to open inspect element, check if you are getting valid src path for image.
If it is valid, try to open in in new tab and see if it appears there. Clearly you will find your error there

Related

how to fetch my image from my database where my upload path folder?

i already look in stackoverflow where i have a similar problem. but it wont just work on me.
Is it possible that the problem is how i upload my image into the folder?
this is the common answer in the stackoverflow and they say it work but it wont work on me the image will still display broken.
Ps. im sorry if the problem is not specify enough. this my first asking here in stackoverflow
this is just an example to what i have:
<?php
include('session.php');
$query = mysqli_query($link, "SELECT * from tbl_menu");
while($res = mysqli_fetch_array($query)){
echo "<img src='Image_name/".$res['image']."'>";
}
?>
this is how i upload my image:
<?php
include_once('connect.php');
if(isset($_POST['AddMenu'])){
$uploadimage = 'C:/xampp/htdocs/thesis/Images_name/'.$_FILES["image"]["name"];
$mname =$_POST['mname'];
$price =$_POST['price'];
$mcategory =$_POST['mcategory'];
$image =$_FILES['image']['name'];
mysqli_query($link, "INSERT into tbl_menu(mname, price, mcategory, image) values('$mname', '$price', '$mcategory', '$image')");
if (move_uploaded_file($_FILES["image"]["tmp_name"], $uploadimage)) {
$msg = "image upload";
}else {
$msg = "not upload";
}
header("location: menu.php");
}
?>
echo "<img src='http://localhost/thesis/Image_name/".$res['image']."'>";
I would recommend you save a variable "home" as "http://localhost/thesis/" in your main config file. and use that variable where ever you need.

How to add image php file from MAMP server

I am trying to add image in MAMP server table & fetch it in PHP, and create json. But I am not getting how to add image in table and again it in file. I am new in PHP scripting. Please someone provide me right direction. I have added my PHP code & also MAMP table screenshot.
PHP Code file
<?php
$conn = mysql_connect("localhost:8888","asmita","asmita123") or die(mysql_error());
if($conn)
{
mysql_select_db("EmployeeInfo");
//echo "connected";
//echo $_SERVER['DOCUMENT_ROOT'];
}
else
{
echo "not connected";
mysql_error();
}
$selectQuery="select * from Emp";
$row=mysql_query($selectQuery);
while($result=mysql_fetch_array($row))
{
//echo $_SERVER['http://localhost:8888/images/index.jpg'];
//output need in JSON format for webservice ...
$empname= $result['Name'];
$empadd= $result['Address'];
$emppho= $result['Phone'];
$emppost= $result['Post'];
$empphoto=$result['Photo'];
$jsonArray[]=array("name"=>"$empname","address"=>"$empadd","phone"=>"$emppho","post"=>"$emppost","photo"=>"$empphoto");
}
echo json_encode($jsonArray);
?>
MAMP table data
Here I added image path. Is this correct? Thanks.
HTML Code
<input type="file" name="img_file" id="imageUpload">
PHP Code
$filename = $_FILES['img_file']['name'];
$src = $_FILES['img_file']['tmp_name'];
$folder = "/images/" ;
$move= move_uploaded_file($src,"$folder/".$image);
if($move!=false)
{
$pic = "http://localhost:8888/directoryName/images" .$filename; //This variable insert into Photo column
$query="Insert or Update Query for your table";
$rslt = mysql_query($query);
}
$data=array();
$selectQuery="select * from Emp";
$row=mysql_query($selectQuery);
while($result=mysql_fetch_array($row))
{
$data[] = $result;
}
echo json_encode($data);

PHP Form is Updating SQL Table Even When SQL Table Column Isn't Blank

I am trying to make a PHP form that will only allow the user to update the MySQL Table column photo, if the photo column is blank. Currently, the form will still update the photo column even if there is data other than "blank" data. For example, the photo column contains the data "columbia.jpg" and the user submits the form with the image "Jefferson.jpg" in the first input. The image column's data gets replaced from columbia.jpg to jefferson.jpg when it is not supposed to replace it at all. Instead it should return an error message stating that the user must first delete the old image before adding a new one. The column data should only get replaced when the column data is equal to "blank". (Not the word "blank" but "".)
Here is my full PHP page code:
<?php
if (isset($_GET["id"])) {
$sn = (int)($_GET["id"]);
?>
<!DOCTYPE html>
<head>
<title>MySQL file upload example</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="<?php $_PHP_SELF ?>" method="post" enctype="multipart/form-data">
Photo 1: <input type="file" name="photo"><br>
<input name="add_image" id="add_image" type="submit" value="Upload file">
</form>
<p>
See all files
</p>
</body>
</html>
<?php
if(isset($_POST['add_image']))
{
$dbLink = new mysqli('daom', 'sm', 'aer', 'kabm');
//This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILES['photo']['name']);
$pic=($_FILES['photo']['name']);
$query = "SELECT photo FROM used_trailers WHERE id = $sn";
$result = mysqli_query($dbLink, $query);
$array=mysqli_fetch_assoc($result);
if($query = " "){
//Writes the information to the database
$query1 =
"UPDATE used_trailers ".
"SET photo = '$pic' ".
"WHERE id = $sn" ;
// Execute the query
$results = $dbLink->query($query1);
// Check if it was successfull
if($results) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded to Photo 1, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your image.";
}
} else {
echo '<p>You must first delete the "Photo 1" image, $array, in order to add a new photo. This is to prevent the server from overloading with too many images.</p>';
}
}
}
echo "$query1";
?>
Thank you for any help. All help is appreciated.
There are some errors in your script. First of all if ($query = " ") will always return true, because you are assigning the variable $query the string " ". To correctly check this, you'd need to use if ($query == " ").
However, this won't solve your problem as $query is the query - not the result. This should work
$query = "SELECT photo FROM used_trailers WHERE id = $sn";
$result = mysqli_query($dbLink, $query);
$array = mysqli_fetch_assoc($result);
if (empty($array['photo'])){
//etc.
}

How to stop sending input form data to SQL database on browser refresh?

On every browser refresh old data that have already been sent to database are sending again.
I want to insert data in database if the input name 'title' have some value.
This is my html form:
<form method="post" enctype="multipart/form-data">
<table>
<tr>
<td><p>Title: <input type="text" name="title"></p></td>
</tr>
<tr>
<td><p>Comment: <input type="text" name="comment" class="inputtext"></p></td>
</tr>
<tr>
<td>
<input type="hidden" name="MAX_FILE_SIZE"value="16000000">
<input name="userfile" type="file" id="userfile">
</td>
<td width="80"><input name="upload"type="submit" class="box" id="upload" value=" Upload "></td>
</tr>
</table>
</form>
My php code:
<?php
$con = mysql_connect('','','') or die(mysql_error());
$db = mysql_select_db('db', $con);
if(isset($_POST['upload'])&&$_POST['title']>0)
{
$title = $_POST['title'];
$comment = $_POST['comment'];
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fileType=(get_magic_quotes_gpc()==0 ? mysql_real_escape_string(
$_FILES['userfile']['type']) : mysql_real_escape_string(
stripslashes ($_FILES['userfile'])));
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
if($db){
$query = "INSERT INTO table (title,comment, name, size, type, content ) ".
"VALUES ('$title','$comment','$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
mysql_close();
echo "<br>Success: $title <br>";
}else { echo "Error"; }
}
?>
After you do whatever you need with the submitted data, you can make a redirect to the same page, for example:
header('Location: /yourpage/');
exit;
If anyone tries refreshing that, it will just refresh to content but the form won't be submitted.
If you need to display an error message or a success confirmation, you can just save it in session parameters and unset them when the message is shown.
exit is needed so that the script doesn't continue to execute and send data to clients who chose to ignore the header.
"Headers already sent" error
If any content has been output before the header() call, you'll get a headers already sent error. If PHP has any content to send to the browser, it automatically finishes the headers and starts outputting page content. At that point no additional headers can be set. This can be caused by anything outputting content, e.g., print, echo, print_r, var_dump and other functions, or perhaps HTML code or even whitespace outside <?php .. ?> tags.
To avoid this you can either:
Structure your code so that all of the PHP code is executed in the beginning, before any content is output.
Use output buffering so that PHP collects all content and outputs it only at the end of the script. You can read more about it (including about other ways to access the content) here, but the simplest way is to just put ob_start() somewhere near the beginning of your script, before any HTML code or content output.
I would query the database with the values give first so you can make sure you are not entering a duplicate entry (which you'll want to check anyways..)
and just return if any entries are returned.
if($db){
$checkQuery = "SELECT * FROM table WHERE TITLE = $title AND COMMENT = $comment"
$result = mysql_query($checkQuery) or die('Error, query failed');
if (mysql_num_rows($result) > 0) { return; }
$query = "INSERT INTO table (title,comment, name, size, type, content ) ".
"VALUES ('$title','$comment','$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
mysql_close();
echo "<br>Success: $title <br>";
}else { echo "Error"; }
}
If you don't want to do this you can use a post, then redirect, then get pattern: explanation
reset the form using JavaScript reset() on window load.
window.onload=function(){
var frm=document.getElementsByTagName(form);
frm.reset();
};

blob in data module

I am using the data module in drupal 7 and i created a view which shows my table.
But I have a blob in my table and this is filling my page with content.Is there any way that I can get the blob to display as a link and the file must be downloaded when clicked.
Also is it possible for the data module to access tables in a different database than the default drupal database mentioned in settings.php.I added another database in the settings.php which has the required table but I am not able to adopt tables from there.(They do not show up in the orphaned tables list).Is there a place where I can change so that the data module only sees the new database and not the default database
Fixed the first problem by doing this in the theme.inc
if($vars['fields'][$field] == 'content')
{
$field_output = "<form action=\"download.php\"
method=\"POST\">
<input type=\"submit\" name=\"download\" value=\"Download\">
<input type=\"hidden\" name=\"did\" value=\"$num+1\">
</form>";
}
and download.php needs to have something like this
<?php
if(isset($_POST['id']))
{
$table = 'tablename';
$download_id = $_POST['id'];
$q="SELECT * FROM {$table} where id = $download_id";
$link = mysqli_connect(...);
$res = mysqli_query($link,$q);
if($res)
{
$row = mysqli_fetch_assoc($res);
$id = $row['id'];
$name = $row['name'];
$status = $row['status'];
$content = $row['content'];
header("Content-type: required type");
header("Content-Disposition: attachment; filename=$name");
echo $content;
exit;
}
else{
echo "Cannot download";}
}
?>
I am still unable to fix the second problem.

Categories