Form To Upload Multiple Images & Data To MySQL DB Via PHP - php

We are developing an application for internal use only to upload 2 images and some text boxes to a MySQL database via a form and PHP Script.
We can get a simple form to work where only text boxes are submitted with no image fields, and we can get a form with just image fields to work and upload images to the mySQL database as BLOB, but when combining the 2 we can only get it to upload the images, and not the text boxes.
Please find below the code for our php upload script, when our form is submitted this uploads to the database the 2 image fields as BLOB, but not the other text fields, any help to point out where we have gone wrong is greatly appreciated:
<?php
$con=mysqli_connect("localhost","Username","Password","outofhours");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$maxsize = 10000000; //set to approx 10 MB
$sitename = mysqli_real_escape_string($con, $_POST['sitename']);
$siteaddress = mysqli_real_escape_string($con, $_POST['siteaddress']);
$sitepostcode = mysqli_real_escape_string($con, $_POST['sitepostcode']);
$eqmake = mysqli_real_escape_string($con, $_POST['eqmake']);
$eqmodel = mysqli_real_escape_string($con, $_POST['eqmodel']);
$eqdesc = mysqli_real_escape_string($con, $_POST['eqdesc']);
$eqserial = mysqli_real_escape_string($con, $_POST['eqserial']);
$eqassetno = mysqli_real_escape_string($con, $_POST['eqassetno']);
$eqconttype = mysqli_real_escape_string($con, $_POST['eqconttype']);
$brewery = mysqli_real_escape_string($con, $_POST['brewery']);
$date = mysqli_real_escape_string($con, $_POST['date']);
$onsitetime = mysqli_real_escape_string($con, $_POST['onsitetime']);
$offsitetime = mysqli_real_escape_string($con, $_POST['offsitetime']);
$custprintname = mysqli_real_escape_string($con, $_POST['custprintname']);
$custposition = mysqli_real_escape_string($con, $_POST['custposition']);
$engname = mysqli_real_escape_string($con, $_POST['engname']);
// check if a file was submitted
if(!isset($_FILES['engsig1']))
{
echo '<p>Please select a file</p>';
}
else
{
try {
$msg= upload(); //this will upload your image
echo $msg; //Message showing success or failure.
}
catch(Exception $e) {
echo $e->getMessage();
echo 'Sorry, could not upload file';
}
}
// the upload function
function upload() {
include "file_constants.php";
$maxsize = 10000000; //set to approx 10 MB
//check associated error code
if($_FILES['engsig1']['error']==UPLOAD_ERR_OK) {
//check whether file is uploaded with HTTP POST
if(is_uploaded_file($_FILES['engsig1']['tmp_name'])) {
//checks size of uploaded image on server side
if( $_FILES['engsig1']['size'] < $maxsize) {
//checks whether uploaded file is of image type
$finfo = finfo_open(FILEINFO_MIME_TYPE);
if(strpos(finfo_file($finfo, $_FILES['engsig1']['tmp_name']),"image")===0) {
// prepare the image for insertion
$imgData1 =addslashes (file_get_contents($_FILES['engsig1']['tmp_name']));
$imgData2 =addslashes (file_get_contents($_FILES['custsig1']['tmp_name']));
// put the image in the db...
// database connection
mysql_connect($host, $user, $pass) OR DIE (mysql_error());
// select the db
mysql_select_db ($db) OR DIE ("Unable to select db".mysql_error());
// our sql query
$sql = "INSERT INTO oohours (sitename, siteaddress, sitepostcode, eqmake, eqmodel, eqdesc, eqserial, eqassetno, eqconttype, brewery, date, onsitetime, offsitetime, custprintname, custsig1, custposition, engname, engsig1)
VALUES
('$sitename', '$siteaddress', '$sitepostcode', '$eqmake', '$eqmodel', '$eqdesc', '$eqserial', '$eqassetno', '$eqconttype', '$brewery', '$date', '$onsitetime', '$offsitetime', '$custprintname', '{$imgData1}', '$custposition', '$engname', '{$imgData2}')";
// insert the image
mysql_query($sql) or die("Error in Query: " . mysql_error());
$msg='<p>Image successfully saved in database with id ='. mysql_insert_id().' </p>';
}
else
$msg="<p>Uploaded file is not an image.</p>";
}
else {
// if the file is not less than the maximum allowed, print an error
$msg='<div>File exceeds the Maximum File limit</div>
<div>Maximum File limit is '.$maxsize.' bytes</div>
<div>File '.$_FILES['engsig1']['name'].' is '.$_FILES['engsig1']['size'].
' bytes</div><hr />';
}
}
else
$msg="File not uploaded successfully.";
}
else {
$msg= file_upload_error_message($_FILES['engsig1']['error']);
}
return $msg;
}
// Function to return error message based on error code
function file_upload_error_message($error_code) {
switch ($error_code) {
case UPLOAD_ERR_INI_SIZE:
return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
case UPLOAD_ERR_FORM_SIZE:
return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
case UPLOAD_ERR_PARTIAL:
return 'The uploaded file was only partially uploaded';
case UPLOAD_ERR_NO_FILE:
return 'No file was uploaded';
case UPLOAD_ERR_NO_TMP_DIR:
return 'Missing a temporary folder';
case UPLOAD_ERR_CANT_WRITE:
return 'Failed to write file to disk';
case UPLOAD_ERR_EXTENSION:
return 'File upload stopped by extension';
default:
return 'Unknown upload error';
}
}
?>

You error lies probably in the fact you are using mysql and mysqli functions through each other. This doesnt work. Either you go with mysqli or you got with mysql .. i would go for mysqli.
I mean, check for yourself. You sanitize them with mysqli, but within the upload function to connect to the database, you use a mysql function.
// put the image in the db...
// database connection
mysql_connect($host, $user, $pass) OR DIE (mysql_error());
// select the db
mysql_select_db ($db) OR DIE ("Unable to select db".mysql_error());
// our sql query
$sql = "INSERT INTO oohours (sitename, siteaddress, sitepostcode, eqmake, eqmodel, eqdesc, eqserial, eqassetno, eqconttype, brewery, date, onsitetime, offsitetime, custprintname, custsig1, custposition, engname, engsig1)
VALUES
('$sitename', '$siteaddress', '$sitepostcode', '$eqmake', '$eqmodel', '$eqdesc', '$eqserial', '$eqassetno', '$eqconttype', '$brewery', '$date', '$onsitetime', '$offsitetime', '$custprintname', '{$imgData1}', '$custposition', '$engname', '{$imgData2}')";
// insert the image
mysql_query($sql) or die("Error in Query: " . mysql_error());
$msg='<p>Image successfully saved in database with id ='. mysql_insert_id().' </p>';
is mysql function, while you use for the rest mysqli
<?php
$con=mysqli_connect("localhost","Username","Password","outofhours");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$maxsize = 10000000; //set to approx 10 MB
$sitename = mysqli_real_escape_string($con, $_POST['sitename']);
$siteaddress = mysqli_real_escape_string($con, $_POST['siteaddress']);
$sitepostcode = mysqli_real_escape_string($con, $_POST['sitepostcode']);
$eqmake = mysqli_real_escape_string($con, $_POST['eqmake']);
$eqmodel = mysqli_real_escape_string($con, $_POST['eqmodel']);
$eqdesc = mysqli_real_escape_string($con, $_POST['eqdesc']);
$eqserial = mysqli_real_escape_string($con, $_POST['eqserial']);
$eqassetno = mysqli_real_escape_string($con, $_POST['eqassetno']);
$eqconttype = mysqli_real_escape_string($con, $_POST['eqconttype']);
$brewery = mysqli_real_escape_string($con, $_POST['brewery']);
$date = mysqli_real_escape_string($con, $_POST['date']);
$onsitetime = mysqli_real_escape_string($con, $_POST['onsitetime']);
$offsitetime = mysqli_real_escape_string($con, $_POST['offsitetime']);
$custprintname = mysqli_real_escape_string($con, $_POST['custprintname']);
$custposition = mysqli_real_escape_string($con, $_POST['custposition']);
$engname = mysqli_real_escape_string($con, $_POST['engname']);
So at that point, you have established the connection with a mysql in the function, but your text is in mysqli sanitized, so it has no clue what to do with it. Simple said as a bove, you chose one or the other ;)

Related

PHP update work on PHP but didnt update on mysql database

I have been working on uploading picture to a folder and saving the file name and some meta info to a MySQL database. I got everything working on PHP but nothing changes on my database. I don't know what is wrong.
<?php
$servername = "localhost";
$username = "root";
$password = "pass";
$dbname = "poster";
$uploadOk = "0";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (isset($_POST['btn-upload'])) {
$owner = $_POST['userid'];
$file = rand(1000,100000)."-".$_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$folder = "profile/";
if (!empty ($owner)) {
$uploadOk = 1;
} else {
echo "Are you sure you are not in the wrong place?";
$uploadOk = 0;
}
$new_size = $file_size/1024;
// new file size in KB
// make file name in lower case
$new_file_name = strtolower($file);
// make file name in lower case
$final_file=str_replace(' ','-',$new_file_name);
if ($file_type != 'jpg' ) {
$uploadOk = 1;
} else {
echo "Only jpg file type allowed.";
$uploadOk = 0;
}
}
if ($file_size > '5000') {
$uploadOk = 1;
} else {
echo "Your image file must be less than 5Mb";
$uploadOK = 0;
}
if (move_uploaded_file($file_loc,$folder.$final_file) && $uploadOk == 1) {
$sql = "UPDATE post SET `file`='$final_file', `type` = '$file_type' WHERE `userid`='$owner'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
$conn->close();
?>
Html Result
Record updated successfully
Database
|userid | file|type|
| 1 | foo | foo|
It said record updated successfully but nothing gets updated in my database. What did I do wrong here?
p.s.
Yes I do know that I should be using PDO by now, but I just need to finish this as my first PHP project.
Thank you in advance.
You are jumping between procedural style and object oriented style with your queries; this may be part of your problem.
Try changing your connection to this:
$conn = new mysqli($servername, $username, $password, $dbname);
Incidentally, since you mention it, you don't necessarily have to use PDO for prepared statements. As you like mysqli, you can do it with these. You are already halfway there. After you've done the above, just do this:
$sql = $conn->prepare("UPDATE post SET `file`= ?, `type` = ? WHERE userid= ? ");
$sql->bind_param("ssi", $file, $file_type, $owner);
$sql->execute();
$sql->close();
The ssi above just refers to "string string integer" (or whatever file types you are using, assuming the first two are varchars, and the third is an INT). Basically you are setting the parameters for each file to go into your query; you don't need to remember whether to quote or not quote the variable depending on type, as you've defined it in the bind_param() below.
It's fairly self-explanatory, and not hard to learn. Like I said, you are halfway there.
I think you have just made a error in either you database design or the way you record the new upload.
UPDATE post SET `file`='$final_file', `type` = '$file_type' WHERE `userid`='$owner'";
This will amend an already created row. So you will only ever have one row per user, and therefore when the user uploads a second file it will over write the previous data.
Assuming the userid column is not defines as auto increment you should in fact be creating a new row for each file a user uploads with an INSERT query rather than an UPDATE like so
INSERT INTO post (userid,file,type)
VALUES ('$owner', '$final_file', '$file_type')
Now you will get a new row for this user for each file they upload.

I ensure database that has image and the database connect is correct ,but I cannot display the image

My display code is :
<?php
include "file_constants.php";
// just so we know it is broken
error_reporting(E_ALL);
// some basic sanity checks
if(isset($_GET['id']) && is_numeric($_GET['id'])) {
//connect to the db
$link = mysql_connect("$host", "$user", "$pass")
or die("Could not connect: " . mysql_error());
// select our database
mysql_select_db("$db") or die(mysql_error());
// get the image from the db
$sql = "SELECT image FROM test_image WHERE id=" .$_GET['id'] . ";";
// the result of the query
$result = mysql_query("$sql") or die("Invalid query: " . mysql_error());
// set the header for the image
header("Content-type: image/jpeg");
echo mysql_result($result, 0);
// close the db link
mysql_close($link);
}
else {
echo 'Please use a real id number';
}
?>
I ensure database that has image and the database connect is correct.
I can upload image from php to phpmyadmin (MYSQL).
However, I cannot display the image.(http:// /file_display.php?id=1)
Can someone help me to display image in php?? THANK YOU SO MUCH!
The file-insert code:
<html>
<head><title>File Insert</title></head>
<body>
<h3>Please Choose a File and click Submit</h3>
<form enctype="multipart/form-data" action=
"<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
<input name="userfile" type="file" />
<input type="submit" value="Submit" />
</form>
<?php
// check if a file was submitted
if(!isset($_FILES['userfile']))
{
echo '<p>Please select a file</p>';
}
else
{
try {
$msg= upload(); //this will upload your image
echo $msg; //Message showing success or failure.
}
catch(Exception $e) {
echo $e->getMessage();
echo 'Sorry, could not upload file';
}
}
// the upload function
function upload() {
include "file_constants.php";
$maxsize = 10000000; //set to approx 10 MB
//check associated error code
if($_FILES['userfile']['error']==UPLOAD_ERR_OK) {
//check whether file is uploaded with HTTP POST
if(is_uploaded_file($_FILES['userfile']['tmp_name'])) {
//checks size of uploaded image on server side
if( $_FILES['userfile']['size'] < $maxsize) {
//checks whether uploaded file is of image type
//if(strpos(mime_content_type($_FILES['userfile']['tmp_name']),"image")===0) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
if(strpos(finfo_file($finfo, $_FILES['userfile']['tmp_name']),"image")===0) {
// prepare the image for insertion
$imgData =addslashes (file_get_contents($_FILES['userfile']['tmp_name']));
// put the image in the db...
// database connection
mysql_connect($host, $user, $pass) OR DIE (mysql_error());
// select the db
mysql_select_db ($db) OR DIE ("Unable to select db".mysql_error());
// our sql query
$sql = "INSERT INTO test_image
(image, name)
VALUES
('{$imgData}', '{$_FILES['userfile']['name']}');";
// insert the image
mysql_query($sql) or die("Error in Query: " . mysql_error());
$msg='<p>Image successfully saved in database with id ='. mysql_insert_id().' </p>';
}
else
$msg="<p>Uploaded file is not an image.</p>";
}
else {
// if the file is not less than the maximum allowed, print an error
$msg='<div>File exceeds the Maximum File limit</div>
<div>Maximum File limit is '.$maxsize.' bytes</div>
<div>File '.$_FILES['userfile']['name'].' is '.$_FILES['userfile']['size'].
' bytes</div><hr />';
}
}
else
$msg="File not uploaded successfully.";
}
else {
$msg= file_upload_error_message($_FILES['userfile']['error']);
}
return $msg;
}
// Function to return error message based on error code
function file_upload_error_message($error_code) {
switch ($error_code) {
case UPLOAD_ERR_INI_SIZE:
return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
case UPLOAD_ERR_FORM_SIZE:
return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
case UPLOAD_ERR_PARTIAL:
return 'The uploaded file was only partially uploaded';
case UPLOAD_ERR_NO_FILE:
return 'No file was uploaded';
case UPLOAD_ERR_NO_TMP_DIR:
return 'Missing a temporary folder';
case UPLOAD_ERR_CANT_WRITE:
return 'Failed to write file to disk';
case UPLOAD_ERR_EXTENSION:
return 'File upload stopped by extension';
default:
return 'Unknown upload error';
}
}
?>
</body>
</html>
The SQL is:
create table test_image (
id int(10) not null AUTO_INCREMENT PRIMARY KEY,
name varchar(25) not null default '',
image blob not null
);
The tutorial is http://vikasmahajan.wordpress.com/2010/07/07/inserting-and-displaying-images-in-mysql-using-php/
If you saved just the image name in the database , this will display the image in your HTML
<?php
$result = mysql_query("$sql") or die("Invalid query: " . mysql_error());
while($row = mysqli_fetch_array($result)) {
echo '<img src="www.yourdomain.com/your/directory/"'. $row["image "].'/>';
}
?>
NOTE : Dont need to use the while loop if you having only one row

Unable to show Images stored in mySQL using PHP

I am trying to store images in mySQL database and then displaying on the other page. I have this function to store images in mySQL.
function upload() {
include "databaseConnection.php";
$maxsize = 10000000; //set to approx 10 MB
//check associated error code
if ($_FILES['userfile']['error'] == UPLOAD_ERR_OK) {
//check whether file is uploaded with HTTP POST
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
//checks size of uploaded image on server side
if ($_FILES['userfile']['size'] < $maxsize) {
// prepare the image for insertion
$imgData = addslashes(file_get_contents($_FILES['userfile']['tmp_name']));
// put the image in the db...
// database connection
mysql_connect($host, $user, $pass) OR DIE(mysql_error());
// select the db
mysql_select_db($db) OR DIE("Unable to select db" . mysql_error());
// our sql query
$sql = "INSERT INTO carsinfo
(carName, carPicture)
VALUES
('{$_FILES['userfile']['name']}', '{$imgData}');";
// insert the image
mysql_query($sql) or die("Error in Query: " . mysql_error());
$msg = '<p>Image successfully saved in database with id =' . mysql_insert_id() . ' </p>';
} else {
// if the file is not less than the maximum allowed, print an error
$msg = '<div>File exceeds the Maximum File limit</div>
<div>Maximum File limit is ' . $maxsize . ' bytes</div>
<div>File ' . $_FILES['userfile']['name'] . ' is ' . $_FILES['userfile']['size'] .
' bytes</div><hr />';
}
}
else
$msg = "File not uploaded successfully.";
}
else {
$msg = file_upload_error_message($_FILES['userfile']['error']);
}
return $msg;
}
And this code to show iamges.
<?php
include "databaseConnection.php";
// just so we know it is broken
error_reporting(E_ALL);
// some basic sanity checks
//connect to the db
$link = mysql_connect("$host", "$user", "$pass") or die("Could not connect: " . mysql_error());
// select our database
mysql_select_db("$db") or die(mysql_error());
// get the image from the db
$sql = "SELECT carPicture FROM carsinfo;";
// the result of the query
$result = mysql_query("$sql") or die("Invalid query: " . mysql_error());
$row = mysql_fetch_assoc($result);
// set the header for the image
echo $row['carPicture'];
header("Content-type: image/jpeg");
// close the db link
mysql_close($link);
?>
When this code is run, nothing is shown on the page, even if I write some HTML inside this code, empty page is shown.
I assume you are saving the image content as blob and if your sql is returning the correct data then you can display as
header("Content-type: image/jpeg");
echo $row['carPicture'];
You need to add the header first before the image.
or
echo '<img src="data:image/jpeg;base64,' . base64_encode($row['carPicture']) . '">';
do not write
include databaseConnection.php
nothing include anything.

Not inserting data into the database

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();

How can I have a upload auto linked in a mysql table

I have a form that uploads a file with other information to a database and displays it in a chart. Right now the chart only displays the file name and doesen't link it. If the file was called test1.pdf, how would I make it so on the chart it still says chart1.pdf but links it to the directory that the file is on?
if ('POST' === $_SERVER['REQUEST_METHOD'])
{
$con = mysql_connect("localhost","xxxx","xxxxx");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("jjlliinn_test", $con);
$target = "clientdoc/";
$target = $target . basename( $_FILES['file']['name']);
$date = $_POST['date'];
$propertydescription = $_POST['propertydescription'];
$transactiontype = $_POST['transactiontype'];
$applicabledocument = ($_FILES['file']['name']);
$received = $_POST['received'];
$paid = $_POST['paid'];
//Writes the to the server
if(move_uploaded_file($_FILES['file']['tmp_name'], $target))
{
//Tells you if its all ok
echo "";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
$sql = mysql_query("INSERT INTO `transactions` (`date`, `agentclient`, `propertydescription`, `transactiontype`, `applicabledocument`, `received`, `paid`)
VALUES
('$date', '$agentclient', '$propertydescription', '$transactiontype', '$applicabledocument', '$received', '$paid')") or die(mysql_error());
$query = mysql_query($sql);
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
echo "Succesfully added transaction. Updating table...";
echo "<META HTTP-EQUIV=\"refresh\" CONTENT=\"48\">";
mysql_close($con);
}
}
?>
Assuming all your uploads are stored in the client doc folder and you have run the query to get the recordset from the transactions table...
link text
Another point, looking at the code, sending raw $_POST values direct to the db is asking for sql injection trouble. Have a look at either htmlentities with ENT_QUOTES set or the input filters available with php.

Categories