PHP update work on PHP but didnt update on mysql database - php

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.

Related

PHP script returns success but does not save a new row in MySQL

I wrote a PHP script that gets an audio file with additional information which will be uploaded on my server and inserts the new data in my MySQL database as a new row.
Uploading the file on my server works and my script returns a success (true for execute()) when the SQL Query insert has been done. However, I will not find the new data in my database.
I tried a couple of things and I know it had worked already some time ago... but for some reason nothing happens anymore to my database.
My PHP script
error_reporting(E_ALL);
ini_set('display_errors', '1');
require 'PostAudio_dbconnection.php';
$title = $_REQUEST['audioTitle'];
$user = $_REQUEST['audioAuthor'];
$language = $_REQUEST['audioLanguage'];
$playlist = $_REQUEST['audioPlaylist'];
$description = $_REQUEST['audioDescription'];
$genre = $_REQUEST['audioGenre'];
$response = array();
$target_dir = "uploads/" . $user . "/audios" . "/" . $playlist . "/" ;
if(isset($_GET['apicall'])){
switch($_GET['apicall']) {
case 'upload':
$message = "Params";
$is_error = false;
if(!isset($_POST['audioDescription'])){
$is_error = true;
$message .= " desc, ";
}
if(!isset($_FILES['audio']['name'])){
$is_error = true;
$message .= "audio is required";
}
if(!isset($_FILES['audio']['name'])){
$response['error'] = true;
$response['message'] = $message;
} else {
$target_file = $target_dir . $title . '.' . pathinfo($_FILES['audio']['name'], PATHINFO_EXTENSION);
$third = $target_dir . $_FILES['audio']['name'];
$anothertry = basename($_FILES["audio"]["name"]);
if (move_uploaded_file($_FILES['audio']['tmp_name'], "$target_dir/$anothertry")){
$sql = "INSERT INTO AllAudios (`title`,`author`,`language`,`playlist`, `description`,`path`,`genre`) VALUES (?,?,?,?,?,?,?);";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)){
echo "\n jungää";
} else {
#$stmt->bind_param("sssssss", "an audio", "an author", "denglish", "Weekend", $_POST['desc'], $target_file, "Funny");
mysqli_stmt_bind_param($stmt, "sssssss", strval($title), strval($user), strval($language), strval($playlist), strval($description), strval($target_dir), strval($genre));
}
if($stmt->execute()){
$response['error'] = false;
$response['message'] = "Audio uploaded successfully";
$response['audio'] = getBaseURL() . $target_file;
$response['title'] = $title;
$response['playlist'] = $playlist;
$response['genre'] = $genre;
$response['description'] = $description;
mysqli_close($conn);
} else {
//echo gettype(strval($playlist));
$response['error'] = true;
$response['message'] = "Try afain öater...";
}
} else {
$response['error'] = true;
$response['message'] = "Try again later...";
$response['playlist'] = $playlist;
$response['joja'] = $target_dir;
$response['cur'] = $_FILES['audio']['name'];
}
}
break;
My PHP connection script
<?php
$db_name = "AudioUploads";
$mysql_username = "root";
$mysql_password = "DataBaba1";
$server_name = "localhost";
$conn = mysqli_connect($server_name, $mysql_username, $mysql_password, $db_name);
if($conn->connect_error){
die("Connection Failed :" . $conn->connect_error);
}
My database structure
# Name Type Collation Attributes Null Default Extra
1 aID int(15) No None AUTO_INCREMENT
2 title text latin1_swedish_ci Yes NULL
3 author text latin1_swedish_ci Yes NULL
4 language text latin1_swedish_ci Yes NULL
5 playlist text latin1_swedish_ci Yes NULL
6 description varchar(500) latin1_swedish_ci Yes NULL
7 path varchar(300) latin1_swedish_ci Yes NULL
8 genre varchar(50) latin1_swedish_ci Yes NULL
This is what my PostMan is showing me
{
"error": false,
"message": "Audio uploaded successfully",
"audio": "http://_/uploads/Uwe/audios/Everything/Bitte .3gp",
"title": "Bitte ",
"playlist": "Everything",
"genre": "Fun",
"description": "Wie soll man es bewältigen"
}
Not sure if either of these things will help, I would rather comment but I'm waiting on 50 rep.
Most people (in my experience) use PHP in the object-oriented fashion, and therefore I believe you will find better resources if you follow along with an article like this.
Another thing that will be important is closing the statement, again as shown in that article.
Some languages/libraries give a stmt.commit() method, I wonder if closing the statement has a similar effect. They do this so that you can do batch/bulk inserts and efficiently call the same query a large number of times.
One last thing, you should close the connection in all cases, not just the successful ones so that errors don't crash your database with a connection limit reached error.
It should be easy to convert to OOP syntax, but if I missed something, feel free to comment on this and clarify.
Jeeezuz I live up to my username... I didnt know that phpmyadmin only displays 25 rows at a time as default.... So I always looked at the last row and expected to see a new one while it was added to the second page...This kept me busy for a week at least. Maaaan hope you have a good laugh about it and other lost people feel less bad. Keep going!!!

I would like to create separate image folder based on registration id during register in php

Here I want to create one more folder inside upload folder and that folder will be unique like based on registration id.
In database I want to save path like ../upload/userid/image_name.jpg
Here is my PHP code:-
session_start();
include 'db.php';
$target_dir = "../upload/";
$target_file = $target_dir . basename($_FILES["photo"]["name"]);
$uploadOk = 1;
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
move_uploaded_file($_FILES["photo"]["tmp_name"], $target_file);
}
$name = $_POST["name"];
$email = $_POST["email"];
$sql = "SELECT email FROM register where email='$email'";
$qur = $connection->query($sql);
if(mysqli_num_rows($qur)==0)
{
$password = md5($_POST["password"]);
$phone = $_POST["phone"];
$sql = "INSERT INTO register(name,email,password,photo,phone)
VALUES ('$name','$email','$password','$target_file','$phone')";
$success = $connection->query($sql);
if (!$success) {
die("Couldn't enter data: ".$connection->error);
}else{
echo "Thank You For registration <br>";
}
}else{
echo "Email-id already exist";
}
$connection->close();
Try this code.
if($uploadOk == 0){
echo "Sorry, your file was not uploaded.";
}else{
mkdir($target_dir.$id);
//The variable $id is your registration id.
move_uploaded_file($_FILES["photo"]["tmp_name"], $target_dir.$id."/");
}
You can use php function mkdir("/path/to/my/dir"); You would need to move use of function move_uploaded_file after record has been inserted in database [in case of new registration]. After record is inserted you would need to get last inserted id from mysql and use it in mkdir function with full path of the folder where you want to keep the uploaded file.

TXT to SQL that automatically removes that line of txt once complete

I have a wordpress plugin that exports form entries to a txt file. So I need to write a php script to add them to a sql database as I want the submissions added to a database on a different domain (otherwise I’d just get the plugin to do it for me). I’m fine about how I get it to connect to the database, it’s just how I code it to interpret the data as the column names are always next to the field as shown.
{"Entry_ID":"235","Name":"matt","Email":"matt#gmail.com","Date":"03/10/2017"}{"Entry_ID":"236","Name":"matt","Email":"matt#btinternet.com","Date":"10/10/2017"}
Is there a way to get it to ignore the column name and only interpret the data within the “” after the : ?
Once these have been added to the sql database I would then need to get the lines removed from the txt
So far I have this but it isn't working...
$file= fopen('http://mpcreations.staging.wpengine.com/wp-content/themes/red-seal-resources/test.txt', 'r');
while (($data = fgetcsv($file)) !== FALSE) {
$object = json_encode($data[0]);
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$query = "INSERT INTO 'wp_forms' LINES TERMINATED BY '\n';
if (mysqli_multi_query($conn, $query)) {
echo "New records created successfully";
} else {
echo "Error: " . $query . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
Any help would be greatly appreciated.
Thank you
Each line in the txt file has JSON data? Process the txt file, parse the data and INSERT it into the database table.
$file= fopen('file.txt', 'r');
while (($data = fgetcsv($file)) !== FALSE) {
$object = json_encode($data[0]);
// Prepare INSERT query here...
}

Data not being submited to SQL Database using MySQLi and PHP

Here's my original post: Why is data I upload getting renamed, and corresponding data added to different rows?
I was able to edit the code a little bit (using the solution I was given) so that the image that was submitted to the server via the insert form had the same name as the file I uploaded.
Example: I upload turtle.jpg into the form and click Insert. The file
"turtle.jpg" would be written into the database where it is located at
on the server (images/turtle.jpg). And then a success message would
pop up.
But everytime I sent data, the image and the other data would be inserted into the database on 2 SEPERATE rows. I have no idea why. I also tried modifying my code so that it used mysqli instead of mysql and nothing works anymore. No errors but no data is sent into the database.
Here's my new php code:
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Create connection
$conn = new mysqli('$host', '$user', '$pass', '$databasename');
// Check connection
if (mysqli_connect_error()) {
die("Database connection failed: " . mysqli_connect_error());
}
if (!empty($_FILES["uploadedimage"]["name"])) {
$file_name=$_FILES["uploadedimage"]["name"];
$temp_name=$_FILES["uploadedimage"]["tmp_name"];
$imgtype=$_FILES["uploadedimage"]["type"];
$ext= GetImageExtension($imgtype);
$imagename= $_FILES['uploadedimage']['name'];
$target_path = "images/".$imagename;
$result = $mysqli->query("INSERT INTO charts ( charts_URL ) VALUES ('".$target_path."')");
or die(mysqli_error($mysqli));
} else {
echo "<p> It is not working </p>";
}
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$date = $_POST['date'];
$retrace = $_POST['retrace'];
$start_of_swing_trade = $_POST['start_of_swing_trade'];
$end_of_swing_trade = $_POST['end_of_swing_trade'];
$bull_flag = $_POST['bull_flag'];
$bear_flag = $_POST['bear_flag'];
$ema_crossover = $_POST['ema_crossover'];
$trading_instrument = $_POST['trading_instrument'];
if($date !=''||$trading_instrument !=''){
//Insert Query of SQL
$sql = "INSERT into charts (charts_date, charts_retrace, charts_start_of_swing_trade, charts_end_of_swing_trade, charts_bullflag, charts_bearflag, charts_ema_crossover, charts_trading_instrument) VALUES ('$date', '$retrace', '$start_of_swing_trade', '$end_of_swing_trade', '$bull_flag', '$bear_flag', '$ema_crossover', '$trading_instrument')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
mysqli_close($conn); // Closing Connection with Server
The only time that data is inserted into the database is when I use the old mysql_query code. But my database says it supports the mysqli extension.
Database server
Server: Localhost via UNIX socket
Server type: MySQL
Server version: 5.5.35-cll-lve - MySQL Community Server (GPL)
Protocol version: 10
User: cpses_msLpFymSYl#localhost
Server charset: UTF-8 Unicode (utf8)
Web Server
cpsrvd 11.48.1.2
Database client version: libmysql - 5.1.73
PHP extension: mysqli Documentation
phpmyadmin
Version information: 4.0.10.7, latest stable version: 4.4.2
Here's a snippet of the my current PHP code (which is basically the code you posted in your solution) with the GetImageExtension function added:
if(isset($_POST['submit'])){
$conn = new mysqli($host, $user, $pass, $databasename);
// Check connection can be established
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
function GetImageExtension($imagetype)
{
if(empty($imagetype)) return false;
switch($imagetype)
{
case 'image/bmp': return '.bmp';
case 'image/gif': return '.gif';
case 'image/jpeg': return '.jpg';
case 'image/png': return '.png';
default: return false;
}
}
$target_path = '';
if (!empty($_FILES["uploadedimage"]["name"])) {
$file_name=$_FILES["uploadedimage"]["name"];
$temp_name=$_FILES["uploadedimage"]["tmp_name"];
$imgtype=$_FILES["uploadedimage"]["type"];
$ext= GetImageExtension($imgtype);
$imagename= $_FILES['uploadedimage']['name'];
$target_path = "images/".$imagename;
$date = $_POST['date'];
$retrace = $_POST['retrace'];
$start_of_swing_trade = $_POST['start_of_swing_trade'];
$end_of_swing_trade = $_POST['end_of_swing_trade'];
$bull_flag = $_POST['bull_flag'];
$bear_flag = $_POST['bear_flag'];
$ema_crossover = $_POST['ema_crossover'];
$trading_instrument = $_POST['trading_instrument'];
You might need to check the variable names and adjust it to your liking. Use prepared statement to prevent sql injection.
if(isset($_POST['submit'])){
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection can be established
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$target_path = '';
if (!empty($_FILES["uploadedimage"]["name"])) {
$file_name=$_FILES["uploadedimage"]["name"];
$temp_name=$_FILES["uploadedimage"]["tmp_name"];
$imgtype=$_FILES["uploadedimage"]["type"];
$ext= GetImageExtension($imgtype);
$imagename= $_FILES['uploadedimage']['name'];
$target_path = "images/".$imagename;
}
$date = $_POST['date'];
$retrace = $_POST['retrace'];
$start_of_swing_trade = $_POST['start_of_swing_trade'];
$end_of_swing_trade = $_POST['end_of_swing_trade'];
$bull_flag = $_POST['bull_flag'];
$bear_flag = $_POST['bear_flag'];
$ema_crossover = $_POST['ema_crossover'];
$trading_instrument = $_POST['trading_instrument'];
if($date !=''||$trading_instrument !=''){
$sql = "INSERT into charts (charts_URL, charts_date, charts_retrace, charts_start_of_swing_trade, charts_end_of_swing_trade, charts_bullflag, charts_bearflag, charts_ema_crossover, charts_trading_instrument) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
// s = string, i = integer, d = double, b = blob
//preparing statement
$stmt = $conn->prepare($sql);
if(!$stmt){ exit("prepare failed");}
//binding param
$bind = $stmt->bind_param('sssssssss',$target_path, $date, $retrace, $start_of_swing_trade, $end_of_swing_trade, $bull_flag, $bear_flag, $ema_crossover, $trading_instrument);
if(!$bind){ exit("bind failed");}
//will return 0 if fail
if($stmt->execute() != 0){
echo "New record created successfully";
}else{ echo "Failed to insert new record";}
}
//close connection
$conn->close();
}
But everytime I sent data, the image and the other data would be inserted into the database on 2 SEPERATE rows. I have no idea why.
Why would you expect it to land in the same row? You perform two different insert queries. If you do want to use two queries, the second one would have to be an update of the previously inserted row. But obviously, that's not the preferred way, just use one query.
Combine your if (!empty($_FILES["uploadedimage"]["name"])) and if(isset($_POST['submit'])) and then use something like this, where you insert the URL at the same time into the same row as all the other values:
INSERT into charts (charts_URL, charts_date, charts_retrace, charts_start_of_swing_trade, charts_end_of_swing_trade, charts_bullflag, charts_bearflag, charts_ema_crossover, charts_trading_instrument) VALUES (?,?,?,?,?,?,?,?)
Security
Please note that your code is extremely unsecure. $imagename is user controlled, so your first query is open to SQL injection. The values in your second query are obviously user controlled, that too is vulnerable. SQL injection can take place in all sorts of queries, including on inserts. It makes it possibly to leak data, DOS you, and possibly execute code or change data. Use prepared statements to protect against SQL injection. It's simple to use and results in nice code, there is no reason not to use it.
Note also that $_FILES["uploadedimage"]["type"] is user controlled as well and independent of the actual file type or extension. You should not trust it when deciding on the extension of the image on your server (if you do, an attacker could eg upload a PHP script).

Form To Upload Multiple Images & Data To MySQL DB Via 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 ;)

Categories