So I think I'll never get an answer lol ...
Old Question, please read the EDIT
I am trying to display a picture after uploading it to a mysql database.
But by trying to open the picture firefox shows the following warning:
the image cannot be displayed because it contains errors
I already had been searching google because of it for hours now but I really can't find a fix for this issue. So now you guys are my very last hope :)
Here is the php:
<?php
session_start();
$con = mysql_connect("localhost", "...", "...");
mysql_select_db('...',$con);
$id = $_GET['id'];
$result = mysql_query("SELECT image, mime FROM artikel WHERE id='$id'");
$row = mysql_fetch_object($result);
header("Content-type: $row->mime");
echo $row->image;
?>
EDIT
I think the mistake is in the insert.php..
Could someone please have a look at it and tell mewhat might be wrong? Thank you :) (I think the image is not uploaded correct)
<?php
session_start();
header('content-type: text/html; charset=utf-8');
$uname = $_POST['username'];
$typ = $_POST['typ'];
$titel = $_POST['titel'];
$content = $_POST['content'];
$timestamp = time();
$db = new mysqli("localhost", "...", "...", "...");
if($db->connect_errno > 0){
die("Unable to connect to database: " . $db->connect_error);
}
if(is_uploaded_file($_FILES['image']['tmp_name'])) {
// Verweis auf Bild
$image = $_FILES['image']['tmp_name'];
// Vorbereiten für den Upload in DB
$data = addslashes(file_get_contents($image));
// Metadaten auslesen
$meta = getimagesize($image);
$mime = $meta['mime'];
}
//create a prepared statement
$stmt = $db->set_charset("utf8");
$stmt = $db->prepare("INSERT INTO artikel (`red`, `typ`, `titel`, `content`, `image`, `mime`, `timestamp`) VALUES (?,?,?,?,?,?,?)");
//bind the username and message
$stmt->bind_param('sssssss', $uname, $typ, $titel, $content, $data, $mime, $timestamp);
//run the query to insert the row
$stmt->execute();
header("Location: erfolg.php");
?>
I followed the instruction from here. I inserted the image with additional mime field and checked the code is working.
Confirm whether you have your mime types correct. If yes, then possibly the image might be corrupted.
having simply
header("Content-type: ");
also worked for me.
$result = mysql_query("$sql") or die("Invalid query: " . mysql_error());
$row = mysql_fetch_object($result);
/*Only for testing purpose.*/
// echo $row->mime; //This line should output image/jpeg
/*Only for testing purpose*/
/*Only to check output*/
header("Content-type: $row->mime");
echo $row->image;
/*Only to check output*/
Try this. Check whether you are getting values inserted. If inserted and still getting error, post pics of database compared to my earlier post.
//create a prepared statement
$stmt = $db->set_charset("utf8");
$stmt = $db->prepare("INSERT INTO artikel (`red`, `typ`, `titel`, `content`, `image`, `mime`, `timestamp`) VALUES (?,?,?,?,?,?,?)");
//run the query to insert the row
$stmt->execute(array($uname, $typ, $titel, $content, $data, $mime, $timestamp));
header("Location: erfolg.php");
Related
I have a problem, because the picture isnt sent to my database. I used different PHP file which doesnt decode picture again and everything works fine, all results appear in my database, but when I try to connect to that file it doesnt work. This is the php that doesnt work properly:
<?php
header('Content-type : bitmap; charset=utf-8');
if(isset($_POST["encoded_string"])){
$username = $_POST["username"];
$description = $_POST["description"];
$encoded_string = $_POST["encoded_string"];
$decoded_string = base64_decode($encoded_string);
$path = 'place on server where I want pictures to be sent' ;
$file = fopen($path, 'wb');
$is_written = fwrite($file, $decoded_string);
fclose($file);
if($is_written > 0){
$con = mysqli_connect("localhost", "xx", "xx", "xx");
$query = "INSERT INTO meals(username, description, image) values('$username', '$description' , '$path');";
$result = mysqli_query($con, $query);
if($result){
echo "success";
}else{
echo "failed";
}
mysqli_close($con);
}
}
?>
And that one send details properly but not in the way I would like to:
<?php
$con = mysqli_connect("localhost", "xx", "xx", "xx");
$username = $_POST["username"];
$description = $_POST["description"];
$encoded_string = $_POST["encoded_string"];
$statement = mysqli_prepare($con, "INSERT INTO images (username, description, image)
VALUES (?, ?, ?)");
mysqli_stmt_bind_param($statement, "sss", $username, $description, $encoded_string);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
Is it casued beacause I have to change FTP settings?
the second code passes all data to database but image is in base64 format so there are plenty characters and it runs slowly. What I want to do is to be able to use the first code, but it doesn't decodes base64 to actual image I am sending and it shows no result in database nor folder in server.
Try this:
$encoded_string = $_POST["encoded_string"];
$path="uploads"."/".rand()."_".time().".jpeg"; //uploads is folder, file name is composed of random number+underscore+time.jpeg
$upload_url="http://xxx.xx.xx.xx/".$path;
if(file_put_contents($path,base64_decode($encoded_string))){
//file uploaded, insert $upload_url into database(Type varchar)
}else{
//echo "file could not uploaded";
}
I've migrated a access database with images on its fields to mysql.
When I try to visualize them with several php codes I get a broken image icon or I download php code (PHP: Retrieve image from MySQL using PDO) that I tried to use in a new try:
<?php
$con = mysqli_connect('localhost', 'root', '', 'access');
$query = mysqli_query($con,"SELECT EscudoClub FROM tclubs WHERE CodClub = 'C13'");
$imageData = mysqli_fetch_array($query, MYSQLI_ASSOC);
$image = $imageData['EscudoClub'];
header("Content-type: image/jpeg");
echo $image;
mysqli_free_result($query);
mysqli_close($con);
?>
With above code I get a broken image icon and using pdo I only get dowwnload php code I guess because some syntax problems:
//$dbName = $_SERVER["DOCUMENT_ROOT"]."\\..\db\\teknofo.mdb";
//$con = new PDO("odbc:DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=access; Uid=; Pwd=;");
$con = new PDO('mysql:host=localhost;dbname=access;charset=utf8', 'root', '');
$sql = "SELECT EscudoClub FROM tclubs WHERE CodClub = 'C13'";
$st = $con->prepare($sql);
$st->execute(array(17));
$st->bindColumn('photo', $photo, PDO::PARAM_LOB);
$st->fetch(PDO::FETCH_BOUND);
odbc_longreadlen($st, 131072);
odbc_binmode($st,ODBC_BINMODE_CONVERT);
ob_clean();
header('Content-Type: image/*');
if ($rd = $st->fetch(PDO::FETCH_BOUND))
{
echo $rd['photo'];
ob_end_flush();
$con = null;
}
?>
Please, could you help me with this?
Kind regards
When executing your statement, you provide an explicit parameter value (of 17)—but the statement does not contain any parameter placeholders! You're then attempting to bind a column named 'photo', which doesn't exist in the resultset. The odbc_* calls shouldn't be there either.
$con = new PDO('mysql:host=localhost;dbname=access;charset=utf8', 'root', '');
// DON'T USE ROOT USER !!!
$st = $con->prepare('SELECT EscudoClub FROM tclubs WHERE CodClub = ?');
$st->execute(array('C13'));
if ($rd = $st->fetch())
{
header('Content-Type: image/*'); // you should give an exact MIME type
echo $rd['EscudoClub'];
}
You should first map the $sql call from:
$sql = "SELECT EscudoClub FROM tclubs WHERE CodClub = 'C13'";
To :
"SELECT EscudoClub FROM tclubs WHERE CodClub = ':cod_club'";
$st = $con->prepare($sql);
$st->execute(array('cod_club' => 123456));
I don't know if this could solve your issue, but when you get straightly the PHP source code from a call, it is generally due to your server configuration (apache, nginx, etc.).
I would like to add that pictures on access database are stored as microsoft word pictures. I don't know if I should export them to any image format (jpeg, png..) before trying to display them. The problem is that I migrated all data from access database and there is a table with 1,3GB of photos.
Kind regards.
I am trying to create a image upload part of my website and it keeps giving this error
"Could not enter data: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '’8°€OIßûü ÷ÞÝuÀBjöÁ› ' at line 1" I dont understand what it means. My php code is
<?php
require('php/connect.php');
$title = $_POST['title'];
$price = $_POST['price'];
$desc = $_POST['desc'];
$answer = $_POST['radiog_dark'];
$nulll = "null for now";
$imageName = $_FILES["image"]["name"];
$imageData = file_get_contents($_FILES["image"]["tmp_name"]);
$imageType = $_FILES["image"]["type"];
$sql = "INSERT INTO items ".
"(title, price, shipping, description, sellerid, date, imagename, image) ".
"VALUES('$title','$price', '$answer', '$desc', '$nulll', CURDATE(), '$imageName', '$imageData')";
$retval = mysql_query( $sql, $dbhandle );
if (substr($imageType,0,5) == "image") {
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
} else {
echo "Oh No Something Went Wrong! :(";
}
mysql_close($dbhandle);
?>
I think it is a problem with the image stuff because it worked fine before :(
Thank You To All That Could Help!
Because you are entering invalid character like this '’8°€OIßûü ÷ÞÝuÀBjöÁ› first use utf-8 and second put mysql_real_escape, and also try to use this
str_replace("'","''",var); //this code find the single quote and replace 2 quote to save in db
i think that should do
I am trying to create a form that require to retrieve the information about an employee then the employee enter their expenses claim. The process of retrieving data is work correctly, but it is not saving the entered data of expenses claim into the database.
I would be most grateful if anybody could help me.
This is my code.
<?php
session_start();
if($_SESSION['emp_no']){
echo "Welcome, ".$_SESSION['emp_no']."!";
}
else
die("You must enter your employee no. ");
$connect = mysql_connect("localhost","root","Omaima2010") or die ("Could not connect");
mysql_select_db("expenses") or die ("Could not find the data base");
$emp_no= $_SESSION['emp_no'];
$query = mysql_query("select e.emp_no, e.manager_no, e.emp_name, m.manager_no, m.manager_name, m.dept_name
from employee e , manager m
where emp_no = '$emp_no' and e.manager_no = m.manager_no");
while($query1 = mysql_fetch_array($query)){
$emp_no = $query1['emp_no'];
$emp_name = $query1 ['emp_name'];
$manager_name = $query1 ['manager_name'];
$manager_no = $query1 ['manager_no'];
$dept_name = $query1 ['dept_name'];
}
if(isset($_POST['exp_desc'])){
//This is the directory where vouchers will be saved
$target = "vouchers/";
$target = $target .basename( $_FILES['datafile']['name']);
$exp_desc = $_POST['exp_desc'];
$date = (date ("d/m/Y"));
$receipt = $_FILES['datafile']['name'];
$amount = $_POST['amount'];
$exch_rate= ($_POST['exch_rate']);
$bd = ($_POST['BD']);
mysql_query("INSERT INTO expenses_claim(emp_no,manager_no,exp_desc,claimant_date,amount,exch_rate,BD,receipt) VALUES ('$emp_no','$manager_no','$exp_desc','$date','$amount','$exch_rate','$bd','$receipt',now())");
//Writes the file to the server
if(move_uploaded_file($_FILES['datafile']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file " . basename( $_FILES['datafile']['name']). " has been uploaded";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
}
?>
You have 8 columns and 9 values in your query,just delete ,now()
Use prepared statements. Also mysql_query is depreciated as of PHP 5.5, so you should switch to mysqli or PDO.
Validate your input. I'd wager that your problem is the result of bad input causing the query to fail.
If you're sending a query that could fail, make sure to catch your error. For example:
if(!mysql_query($query))
echo "Your query failed. It consisted of: $query and the error was " . mysql_error();
I am building a simple website, I want to allow the users to upload and change their avatars. At present I have been able to upload images to a mysql database, stored as blobs with the code as follows:
//connected to DB, userID fetched
$image = $FILES['fileToUpload']['tmp_name'];
$fp = fopen($image, 'r');
$content = fread($fp, filesize($image));
$content = addslashes($content);
fclose($fp);
$sql = "UPDATE tbUsers SET profileImage = '".$content."' WHERE userID = ".userID;
$result = mysql_query($sql) or die (mysql_error());
When I download the files from phpmyadmin after upload they are saved as .bin files, but can be viewed normally. I'm not sure if this is correct or not.
My code to display the images is as follows:
HTML:
<?php echo '<img src ="showPic.php?q='.$_SESSION['profile'].'"/>'; ?>
PHP:
if (!empty($_GET['profile']) && is_numeric($_GET['profile']))
{
$con = mysql_connect("localhost", "root", "");
$mysql_select_db("projectDB");
$sql = "SELECT profileImage FROM tbUsers WHERE userID = ". $_GET['profile'];
$result = mysql_query($sql) or die (mysql_error());
header('Content-type: image/jpeg');
$row = mysql_fetch_object($result);
echo $row['image_data'];
}
I am unsure if I am attempting to display the image in the correct way, any help (corrections/alternative solutions) would be greatly appreciated :)
You can do this :
if (!empty($_GET['profile']) && is_numeric($_GET['profile']))
{
$con = mysql_connect("localhost", "root", "");
$mysql_select_db("projectDB");
$sql = "SELECT profileImage FROM tbUsers WHERE userID = ". $_GET['profile'];
$result = mysql_query($sql) or die (mysql_error());
$content = mysql_result($result,0,"file_content");
$name = mysql_result($result,0,"file_name");
$type = mysql_result($result,0,"file_type");
$size = mysql_result($result,0,"file_size");
header("Content-type: $type");
echo $content
}
Note : You should have these column in you table where you save your BLOB data
file_name = for save filename
$_FILES['file']['name']
file_type = for save file type
$_FILES['file']['type']
file_size = for save file size
$_FILES['file']['size']
You select this
$sql = "SELECT profileImage FROM tbUsers WHERE userID = ". $_GET['profile'];
and refer to not selected column
echo $row['image_data'];