MySQL not inserting data into a table upon a file being uploaded - php

I'm trying to create a gallery system which creates entries per image in a table allowing the script to retrieve all images with certain values. At the moment I've managed to get the file upload to work although it's not inputting the file name and gallery id into my table - it's not creating a row at all. Below is the code, any help would be amazing :)! I've messed around with a few things although file uploads and the likes aren't really my forte.
<?php
require "common.php";
$con = mysql_connect("localhost","$username","$password");
mysql_select_db("$dbname", $con);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$id = $_GET['id'];
$query2 = mysql_query("SELECT id,title,date FROM galleries WHERE id = $id");
if (!$query2) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($query2);
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 2000000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("../galleries/images/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"../galleries/images/" . $_FILES["file"]["name"]);
$file = '["file"]["name"]';
$sql="INSERT INTO images (url, gallery)
VALUES
('$_POST[$file]','$_POST[$id]')";
header("Location: ../../../gallery.php?id=" . $row[0]);
die("Redirecting to: admin.php");
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
}
}
}
else
{
echo "Invalid file";
}
?>

The problem is that you redirect and kill your script before you execute your query:
$sql="INSERT INTO images (url, gallery)
VALUES
('$_POST[$file]','$_POST[$id]')";
header("Location: ../../../gallery.php?id=" . $row[0]);
die("Redirecting to: admin.php");
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ nothing after this gets executed
if (!mysql_query($sql,$con))
^^^^^^^^^^^^^^^^^^^^^^ this query will never run
...
And you really should switch to PDO (or mysqli) and prepared statements to avoid sql injection problems.

Related

Unable to display BLOB image with Data URI

I have a jpg image stored in MySql Database table in the column with the data type as BLOB that part of the php code works fine.
I am trying to display that image using the below php code but it would not work. I see a small icon on the screen which is definitely not the image ? what's wrong any help?
1) Read the image php file
<?php
header("Content-Type: image/jpg");
$db=mysqli_connect("localhost","root","root123","deal_bank","3306");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($db,"deal_bank");
$sql = "SELECT * FROM image";
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
echo '<img src="data:image/jpg;base64,'.base64_encode( $result['image'] ).'"/>';
?>
2) Upload the file into the MySql Database
<?php
$con=mysqli_connect("localhost","root","root123","deal_bank","3306");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,"deal_bank");
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] > 20000)
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
} else {
$stmt = $con->prepare('INSERT INTO image (image) VALUES (?)');
$null = null;
$stmt->bind_param('b', $null);
$stmt->send_long_data(0, file_get_contents($_FILES['file']['tmp_name']));
$stmt->execute();
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
// $image = addslashes(file_get_contents($_FILE['file']['tmp_name']));
//mysqli_query($con,"INSERT INTO image (image) VALUES ('{$image}') ");
}
}
} else {
echo "Invalid file";
}
?>
I replaced
header("Content-Type: image/jpg");
with
ob_start( );
it now works fine i am not sure what was the problem before ?

PHP if statement not properly detecting a MySQL table

I have two PHP documents. One that connects to my MySQL server and database (it will also create the database if it doesn't exist). This document is titled "db_connect.php". My next PHP document is titled "create.php" and it is designed to connect to a specific table within the database and create that table if it doesn't exist. There's also a javascript document involved in this which makes it so the user can type things and enter them into the table without the page being refreshed. I don't think you'll need this document and so I won't include it, but I thought you guys might find it helpful to know that this is for a message board.
Here's my db_connect.php file:
<?php
$db = "my_db";
//establish a connection with the server
$connection = mysqli_connect('localhost', 'root', 'password');
if(!$connection){
exit("<p>Could not establish a connection :" . mysqli_connect_error() . "</p>");
}
//connect to the database
$dbSelect = mysqli_select_db($connection, $db);
if(!$dbSelect){
// Create database
$sql="CREATE DATABASE " . $db;
if (mysqli_query($connection, $sql)) {
} else {
echo "<p>Error creating database: " . mysqli_error($connection) . "</p>";
}
}
?>
Here's my create.php file:
<?php
//connect to the database
include('db_connect.php');
$table = 'NDI';
//update the table if the notes are posted
if(isset($_POST['notes'])){
$notes=$_POST['notes'];
$name=$_POST['name'];
$file = $_POST['file'];
$file2 = $_FILES['file'];
echo "<p>Hello $file $file2</p>";
/////////////////////////////////////////////
//Check for file type
/////////////////////////////////////////////
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "application/x-shockwave-flash")
)
&& ($_FILES["file"]["size"] < 999000)){
/////////////////////////////////////////////
//Check for errors
/////////////////////////////////////////////
if ($_FILES["file"]["error"] > 0){
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}else{
///////////////////////////////////////////
//Set the upload
///////////////////////////////////////////
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
/////////////////////////////////////////////////////////
//Check to see if file exists already
/////////////////////////////////////////////////////////
if (file_exists("../uploads/" . $_FILES["file"]["name"])){
//echo $_FILES["file"]["name"] . " already exists. ";
$_FILES["file"]["name"] = rand(1, 1000).$_FILES["file"]["name"];
}
////////////////////////////////////////////////////////////
//If not, move to the upload folder
////////////////////////////////////////////////////////////
$path = '../uploads/';
$tmp_name = $_FILES["file"]["tmp_name"][$key];
$fn = basename( $_FILES['file']['name']);
move_uploaded_file($_FILES['file']['tmp_name'], $path.$fn);
//move_uploaded_file($_FILES["file"]["tmp_name"],
//"../uploads/" . $_FILES["file"]["name"]);
echo "Stored in: ../uploads/". $_FILES["file"]["name"];
$myImg = "../uploads/" . $_FILES['file']['name'];
//echo "\n $myImg";
}
//echo "<a href=../uploader/>Back</a>";
}else{
echo "Invalid file";
//echo $_FILES["file"]["type"];
}
if(!$myImg){
$myImg="../uploads/blank.png";
}
if(!$name){
$name="anonymous";
}
$sql= "INSERT INTO `$table` SET `name` = '$name', `notes`='$notes', `img`='$myImg'";
if (mysqli_query($sql)) {
echo '<p>Entry added</p>';
echo '<p>' . $title . ' Home </p>';
} else {
echo '<p>Error adding page: ' . mysqli_error() . '</p>';
}
}
//display results
$choices = mysqli_query("select * from " . $table);
if(!$choices){
// Create table
$sqlc="CREATE TABLE $table(`id` INT(5) AUTO_INCREMENT, `img` VARCHAR(50), `name` VARCHAR(25), `notes` TEXT(500), PRIMARY KEY (`id`))";
// Execute query
if (mysqli_query($connection, /*$db,*/ $sqlc)) {
} else {
echo "Error creating table: " . mysqli_error($connection/*, $db*/);
}
}
while($row = mysqli_fetch_array($choices)){
$img=$row['img'];
$note=$row['notes'];
$name=$row['name'];
echo "<p class='note'><img src='$img'><span class='name'>$name: </span>$note</p>";
}
?>
The problem I'm running into is that the page echos the error: "Error creating table: Table 'NDI' already exists" so my if statement if(!$choices) is returning true. This if statement is supposed to return false when the table already exists. I can't figure out what's wrong with it. Any feedback you guys could give would be greatly appreciated.
I would recommend using the PHP function mysqli_num_rows($choices) and changing if statement to:
if(mysqli_num_rows($choices) == 0) {
If you print_r the $choices variable as it is currently written, you will probably see that it is not empty. There was no error... There just were no rows returned. What you want to know is not if there was an error, but if there were any rows returned.
You were missing your $connection as the 1st parameter of mysqli_query -> $choices = mysqli_query("select * from " . $table);.
It should be -
//display results
$choices = mysqli_query($connection, "select * from " . $table);
if(!$choices){
...
}
You want to keep ! in if(!$choices) as now you are properly checking if your query failed/returned 0 rows, as mysql table $table does not exist.

trouble combining image upload and sql query

i am having an issue executing an SQL/SQLi query and uploading an image at the same time.
I am able to do one or the other but not sure how to combine the code.
The main code:
<?php
require('connect.php');
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("images/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"images/" . $_FILES["file"]["name"]);
echo "Stored in: " . "images/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
The above code works for image upload
<?php
$venuename=$_POST['venuename'];
$adress=$_POST['adress'];
$venuetype=$_POST['venuetype'];
$venuedesc=$_POST['description'];
if($venuename&&$adress&&$venuetype&&$venuedesc)
{
$query = mysql_query("INSERT INTO tbl_venues (venue_name,venue_description,venue_adress,venue_type) VALUES ('$venuename','$venuedesc','$adress','$venuetype')");
header("Location: created_venue.php?");
}
else
{
echo '<div id="venuevalidation">Please complete all fields!</div>';
}
?>
The above works for inserting data however my attempts to combine the two are unsuccessful, any suggestions?
Apologies for the large post! Thanks
All resolved, the issue was with brackets! the code was executing on one part and not moving to the next.

Syntax Error When Writing Data Into a Table - unexpected T_VARIABLE

Parse error: syntax error, unexpected T_VARIABLE in upload_file.php on line 44
The code worked until I added these lines :
Lines 42-44 :
$path = "uploads/" . $_FILES["file"]["name"];
$Link = mysql_connect($Host, $User, $Password);
$Query = "INSERT INTO $Table_7 VALUES ('0','"$path"')";
Thanks it sorta worked. The script is for uploading images into a folder. That part of works but I cannot write the image path into the table. I have a table with two fields :
picid - auto incrementing primary key
path - varchar(60)
Any idea what I'm doing wrong? I've added the full script.
UPDATE. FULL CODE
<?php
include "connect.php";
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 10000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("uploads/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"uploads/" . $_FILES["file"]["name"]);
echo "Stored in: " . "uploads/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
$path = "uploads/" . $_FILES["file"]["name"];
$Link = mysql_connect($Host, $User, $Password);
$Query = "INSERT INTO $Table_7 VALUES ('0','{$path}')";
?>
You are missing you concatenation operator on line 44:
$Query = "INSERT INTO $Table_7 VALUES ('0','"$path"')";
should be
$Query = "INSERT INTO $Table_7 VALUES ('0','".$path."')";
or
$Query = "INSERT INTO $Table_7 VALUES ('0','$path')";
or
$Query = "INSERT INTO $Table_7 VALUES ('0','{$path}')";

Posting list values as variables

I'm currently trying to create a gallery upload page that allows users to select a album along with the album id being the value in the dropdown menu. On selecting their chosen album, the image is then uploaded and the data such as the image URL, ID, date and album added to a table. I've managed to get up to the stage of adding the album ID to my table although I'm having trouble with posting the value defined by the user in the dropdown menu.
I receive this error upon uploading an image:
Could not run query: 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 '[album]' at line 1
Any help would be much appreciated as MySQL isn't really an area I'm knowledgeable in, thanks :)!
My form :
<form action="assets/includes/upload.php" method="post" enctype="multipart/form-data">
<select name="album">
<? uploadList(); ?>
</select><br>
<input type="file" name="file" id="file" style="margin-top:37px; margin-left: 3px;"><br>
<input type="submit" name="submit" value="Submit" class="btn btn-primary" style="margin-left: 57px;">
</form>
The function carried out on the upload.php page:
function imageUpload() {
$id = ('$_POST[album]'); /////////// Focus being on this section ///////////
$con = mysql_connect("localhost","$username","$password");
mysql_select_db("$dbname", $con);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$query2 = mysql_query("SELECT id,title,date FROM galleries WHERE id = $id");
if (!$query2) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($query2);
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("../../images/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
$file = $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"],
"../../images/" . $_FILES["file"]["name"]);
$sql="INSERT INTO images (url, gallery)
VALUES
('$file','$id')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
}
}
}
else
{
echo "Invalid file";
}
}
In the second line of your PHP you have $id = ('$_POST[album]');. What's happening here is just "filling" $id with the literal string '$_POST[album]'. You need to change it so it becomes:
$id = intval($_POST['album']);
Now you're reading the value of album from the global $_POST array.
Please note that your code is vulnerable to SQL Injection, please take the appropriate measures to mitigate it. I added intval() for you as a basic protection while you read more about the subject.

Categories