Uploading images and inserting filename to MySQL - php

xxxHow can I fix this script so that it actually posts 3 separate images rather than the same image 3 times. Any help would be much appreciated. I will provide the code html code to encase that's relevant.
html:
<form method="post" action="insert.php" enctype="multipart/form-data">
<input type="text" name="caseName"><br>
<input type="file" name="upload[]"/>
<input type="file" name="upload[]"/>
<input type="file" name="upload[]"/>
<input type="submit" value="Submit" >
</form>
php:
if ( isset( $_FILES['upload'] ) ) {
$name_array = $_FILES['upload']['name'];
$tmp_name_array = $_FILES['upload']['tmp_name'];
for ( $i = 0; $i < count( $name_array ); $i++ ) {
if ( move_uploaded_file( $tmp_name_array[$i], "uploaded/" . $name_array[$i] ) ) {
echo $name_array[$i];
} else {
echo "failed";
}
}
$dsn = 'mysql:host=localhost;dbname=GLO12408958DB';
$username = 'root';
$password = 'yt987210d';
//
// DB connection was made
//
$pdo = new PDO($dsn, $username, $password);
//loop over array to get names. Make sure we have actual content.
if ( count( $name_array ) > 0 && $name_array !== false ) {
//Prepare query
$statement = $pdo->prepare( 'INSERT INTO caseStudies(caseImage,caseImage2,caseImage3) VALUES (?,?,?)' );
//use a different index in the event that the numeric keys in the name array are not ordered correctly
$index = 1;
foreach ( $name_array as $key => $filename ) {
$statement->bindParam( $index, $filename, PDO::PARAM_STR );
$index++;
}
$statement->execute();
//etc....
}
}

According to the manual, bindParam() "Binds a PHP variable to a corresponding named or question mark placeholder in the SQL statement that was used to prepare the statement. Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called."

Related

How to upload files from two html input fields in the same form using php?

Hi I am facing a problem while uploading two files using php.
I have this html input form with two files field
<form class="form-group" method="post" enctype="multipart/form-data">
<input type="file" accept=".jpg, .jpeg, .png" id="img" name="displaypic" required/>
<input type="file" accept=".pptx" name="presentation" required>
<button name="submit>Submit</submit>
</form>
This is my php code. Here I take the file data from the form but only the first one is uploaded, second file is not.
<?php
if(isset($_POST['submit'])){
$file = $_FILES['displaypic'];
$fileName = $_FILES['displaypic']['name'];
$tempName = $_FILES['displaypic']['tmp_name'];
$size = $_FILES['displaypic']['size'];
$error = $_FILES['displaypic']['error'];
$format = $_FILES['displaypic']['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg','png');
if(in_array($fileActualExt, $allowed)) {
if ($error === 0) {
if ($size<2e6) {
$newname = $tid.".".$fileActualExt;
$location = 'displays/'.$newname;
move_uploaded_file($tempName,$location);
}}}
Similarly when I write the same code for file two it doesn't work. Only the first file is uploaded not the second file.
$file_ppt = $_FILES['presentation'];
$fileName = $_FILES['presentation']['name'];
$tempName = $_FILES['presentation']['tmp_name'];
$size = $_FILES['presentation']['size'];
$error = $_FILES['presentation']['error'];
$format = $_FILES['presentation']['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('pptx');
if(in_array($fileActualExt, $allowed)) {
if ($error === 0) {
if ($size<10e6) {
$newname = $tid.".".$fileActualExt;
$location = 'presentations/'.$newname;
move_uploaded_file($tempName,$location);
}}}
}
?>
If you use the same name for the file input field but use the array style syntax for the name you can assign your own identifier within the square braces which will be available in the POST / FILES array later. This identifier can be used to separate the different types of files so you can fork the logic as appropriate to your needs.
The following shows a basic usage of this methodology - it might prove of interest but it might not.
<?php
$field='xfiles'; // Whatever you wish to name your file input elements
$errors=array();
$status=array();
$maxfs=pow(1024,2) * 5; //5Mb or whatever.... 10e6?
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_FILES[ $field ] ) ){
$obj=$_FILES[ $field ];
foreach( $obj['name'] as $index => $void ){
$name=$obj['name'][ $index ];
$tmp=$obj['tmp_name'][ $index ];
$error=$obj['error'][ $index ];
$type=$obj['type'][ $index ];
$size=$obj['size'][ $index ];
$ext=strtolower(pathinfo($name,PATHINFO_EXTENSION));
$allowed=(object)array(
'displaypic' => array('jpg','jpeg','png'),
'presentation' => array('ppt','pptx')
);
if( $error!==UPLOAD_ERR_OK )$errors[]=sprintf('An error [code:%d] occurred with file %s',$error,$name);
if( !in_array( $ext, $allowed->$index ) )$errors[]=sprintf('Incorrect file extension %s for %s',$ext,$name);
if( $size > $maxfs )$errors[]=sprintf('The file %s is too large #%d',$name,$size);
if( empty( $errors ) ){
$status[]=sprintf('<div>%s uploaded successfully - save to db, do a happy little dance or whatever else you need to do!</div>', $name );
#move_uploaded_file($tmp,'/path/to/new/folder/'.$name);
#$sql='insert into ....';
}
}
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<title>PHP: Multiple file uploads</title>
<meta charset='utf-8' />
</head>
<body>
<form class='form-group' method='post' enctype='multipart/form-data'>
<label>Display - [accept:jpg,png]<input type='file' accept='.jpg, .jpeg, .png' name='xfiles[displaypic]' required /></label>
<label>Presentation - [accept:ppt,pptx] <input type='file' accept='.ppt, .pptx' name='xfiles[presentation]' required /></label>
<input type='submit' />
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $status ) ){
echo '<h1>Success</h1>';
foreach($status as $msg)printf('<div>%s</div>',$msg);
}
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $errors ) ){
echo '<h1>Error</h1>';
foreach($errors as $error)printf('<div>%s</div>',$error);
}
?>
</form>
</body>
</html>

Upload CSV and Import into MySQL Database

I am trying to create a form that uploads a CSV file that then inserts the data into a MYSQL database. with my code, I don't get any error message, it just doesn't insert. Here is my code:
Here is the form code:
<!DOCTYPE html>
<html>
<head>
<title>CSV Upload</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data" action="import.php">
<div align="center">
<p>Select CSV file: <input type="file" name="file" /></p>
<p><input type="submit" name="csv_upload_btn" value="Upload" /></p>
</div>
</form>
</body>
</html>
//Process form
if(isset($_POST["csv_upload_btn"])){
if($_FILES['file']['name']){
$filename = explode("",$_FILES['file']['name']);
if($filename[1] == "csv"){
$handle = fopen($_FILES['file']['tmp_name'], "r");
while($data = fgetcsv($handle)){
$item1 = mysqli_real_escape_string($connection, $data[0]);
$item2 = mysqli_real_escape_string($connection, $data[1]);
$item3 = mysqli_real_escape_string($connection, $data[2]);
$item4 = mysqli_real_escape_string($connection, $data[3]);
$item5 = mysqli_real_escape_string($connection, $data[4]);
$query = " INSERT INTO data(softwareID,districtID,statusID,date_approved,date_expired) VALUES('$item1', '$item2', '$item3', '$item4', '$item5') ";
$run_query = mysqli_query($connection, $query);
}
fclose($handle);
if($run_query == true){
echo "File Import Successful";
}else{
echo "File Import Failed";
}
}
}
}
//Close Connection
mysqli_close($connection);
?>
Your current code would be vulnerable to SQL Injections, I suggest using prepared statements or parameterized queries and it would probably fix your problem also. Ill show you an example on how I connect to databases (using PDO):
# You can also set this up in a function, but this is how I use it as it works best for me.
# Also best if you keep this class (or function if you choose to change it) out of the `public_html` folder and just include/require it.
class DB extends PDO{
public $connect;
public function __construct(string $db_name){
try{
# Declare your mysql credentials
$cred = [
"db_user" => "localhost",
"db_user" => "root",
"db_pass" => "xxx"
];
$this->connect = new \PDO("mysql:host=".$cred['db_host'].";dbname=".$db_name, $cred['db_user'], $cred['db_pass']);
$this->connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
# You can include the $e variable from above in the echo below to show the error, but I chose not to
# just incase someone is trying to attack your website. That error can give them a lot of information
# about your SQL query, which can be very useful to an attacker; giving them an idea on how to formulate
# an injection (if possible).
echo("Error");
}
}
}
# Start a connection to the declared database name
$db = new DB("database_name");
# Prepare the query but refrain from inputting variables directly into it. Instead put a :placeholder in its spot like so:
$queryPrep = $db->connect->prepare("INSERT INTO `data` (softwareID, districtID, statusID, date_approved, date_expired) VALUES (:softwareID, :districtID, :statusID, :date_approved, :date_expired)");
# You then bind your value(s) into your query like so (make sure to declare what datatype your variable is in the 3rd parameter):
$queryPrep->bindValue(':softwareID', $softwareID, PDO::PARAM_STR);
$queryPrep->bindValue(':districtID', $districtID, PDO::PARAM_STR);
$queryPrep->bindValue(':statusID', $statusID, PDO::PARAM_STR);
$queryPrep->bindValue(':date_approved', $date_approved, PDO::PARAM_INT);
$queryPrep->bindValue(':date_expired', $date_expired, PDO::PARAM_INT);
# Full list of PDO::PARAM_ Predefined Constants
# https://www.php.net/manual/en/pdo.constants.php
# Now you can finally execute your query
$queryPrep->execute();
# Check to see if any rows have been added to the database from the last SQL statement
if($queryPrep->rowCount() > 0) echo "true - Row Added";
else echo "false - Row Not Added";
I also have a function that I created a while back to parse CSV files/strings into an easier useable array (always assuming the first line will be the column names though):
function csvParse($input, $callback = false){
$results = [];
$raw_array = (is_file($input)) ? array_map('str_getcsv', file($input)) : array_map('str_getcsv', explode("\n", $input));
$array = array_splice($raw_array, 1, count($raw_array));
foreach($raw_array[0] as $c) $columns[] = $c;
foreach($array as $key0 => $val0) foreach($val0 as $key1 => $val1) $results[$key0][$columns[$key1]] = $val1;
if(is_callable($callback) && !empty($results)) call_user_func_array($callback, array($results));
elseif(!empty($results)) return $results;
else throw new Exception("Results Empty: Can not read the string or open file.");
}
# Can also be file location
$input = "animal,name,age\n
goat,crimin4l,24\n
deer,henry,11\n
bear,teddy,15";
csvParse($input, function ($arr){
print_r($arr);
});
Output:
Array
(
[0] => Array
(
[animal] => goat
[name] => crimin4l
[age] => 24
)
[1] => Array
(
[animal] => deer
[name] => henry
[age] => 11
)
[2] => Array
(
[animal] => bear
[name] => teddy
[age] => 15
)
)
You could put both of them together to complete your task successfully like so:
$db = new DB("database_name");
if(isset($_POST["csv_upload_btn"]) && !empty($_FILES['file'])){
$file['base'] = basename($_FILES['file']['name']);
$file['path'] = $_FILES['file']['tmp_name'];
$file['mime'] = strtolower(pathinfo($file['base'], PATHINFO_EXTENSION));
if($file['mime'] === "csv" || $file['mime'] === "txt"){
csvParse($file['path'], function ($arr){
# Start the $queryPrep here;
# If for each CSV row you want to add a MySQL row then
# you will need a foreach loop to iterate through each
# of the array(s).
});
}else echo("Error: File must be .CSV or .TXT");
}

When send sql query with form Access to this resource on the server is denied

I'm trying to submit a query to the database via the form. I'm running the query that comes with php on the database. But I'm getting the error in the picture
The query i am trying to send
The error i got
But if I send single line it works.
Example:
update uretim10dk set mesai_durumu='Mesai dışı' where saat between '00:00' and '08:00';
Example2:
update uretim10dk set mesai_durumu='Mesai içi' where saat >= '08:00';
but not working together.
Example:
update uretim10dk set mesai_durumu='Mesai dışı' where saat between '00:00' and '08:00';update uretim10dk set mesai_durumu='Mesai içi' where saat >= '08:00';
<form action="" method="post">
<textarea name="sorgularMesai" id="sorgularMesai" cols="30" rows="10"></textarea>
<br>
<input type="submit" value="gonder" id="gonder" />
</form>
function GenelMesaiAyarla( $sorgular_mesai_sql ) {
$yol = $_SESSION[ 'kok_dizin' ] . "DatabaseOperations/ConnectionOperations.php";
require_once( $yol );
$connect = new Connection();
$connect->BaglantiyiAc();
$connect = new Connection();
$bolunmus_mesai_sql = explode( ";", $sorgular_mesai_sql );
for ( $i = 0; $i < count( $bolunmus_mesai_sql ); $i++ ) {
$connect->BaglantiyiAc();
$queryMesaiGuncelleResult = $connect->connectionKey->query( $bolunmus_mesai_sql[ $i ] );
if ( $queryMesaiGuncelleResult ) {
$connect->BaglantiyiKapat();
$mesaiGuncellemeDurum = true;
} else {
$mesaiGuncellemeDurum = false;
}
echo $i.":".$bolunmus_mesai_sql[ $i ]."<br>";
}
return $mesaiGuncellemeDurum;
}
if ( $_POST ) {
$sorgular_mesai = $_POST[ "sorgularMesai" ];
$genel_mesai_durum = "İşlem Başarısız!";
$genel_mesai_durum = GenelMesaiAyarla( $sorgular_mesai );
if ( $genel_mesai_durum == true ) {
echo "Mesai güncellendi";
} else {
$genel_sonuc = "Mesai Durumu ayarlarken bir sorun oluştuğu için,tüm işlemler durduruldu!";
}
}

Receiving a Fatal Error on multiple file upload [duplicate]

This question already has an answer here:
Adding multiple files with PDO
(1 answer)
Closed 7 years ago.
I have made a script to upload multiple files using a form:
<form action="upload_image.php" id="form_img" method="POST" enctype="multipart/form-data">
<div align="center">
<div class="fileUpload btn btn-primary">
<span>Carica immagini nella galleria</span>
<input type="file" name="immagini[]" multiple="multiple" id="file_img" class="upload"/>
<script>
document.getElementById("file_img").onchange = function() {
document.getElementById("form_img").submit();
};
</script>
</div>
</div>
</form>
The javascript code is supposed to submit the form when user have chosen a file and here is the php I am using to process the upload:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
$where = dirname(__FILE__);
include($where . "/config/db.php");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
foreach ($_FILES as $file) {
$nome_file_temporaneo = $file["tmp_name"];
$nome_file_vero = $file["name"];
$tipo_file = $file["type"];
$not_profilo = '1';
for($i=0;$i<sizeof($tipo_file);$i++) {
$dati_file = file_get_contents($nome_file_temporaneo[$i]);
$query = "INSERT INTO ".$_SESSION['id']." (immagine,type,profilo) values (?,?,?)";
$stmt = $dbh->prepare($query);
$stmt->bindParam(1, $dati_file, PDO::PARAM_LOB);
$stmt->bindParam(2, $tipo_file[$i],PDO::PARAM_STR);
$stmt->bindParam(3, $not_profilo, PDO::PARAM_STR);
$stmt->execute();
}
}
header("location: profile_set.php");
?>
This gives me an error:
Fatal error: in C:\xampp\htdocs\tp\upload_image.php on line 24
Line 24 is the line that contains: $stmt->execute()
Any help would be appreciated.
Try binding using an array inserted into the ->execute(array()). If you want to make sure that values are what they should be, just do some validation in the foreach() loop. One last thing, you say your form does multiple uploading but you have only one input and you have it upload as soon as the input changes, so that is a tad confusing:
// I am just saving your connection to a function just to clean it up a bit
function connection()
{
include(__DIR__."/config/db.php");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
// I like to reogranize my $_FILES array so each file is in it's own array
function organize($array = false)
{
if(!is_array($array) || empty($array))
return $array;
foreach($array['name'] as $key => $value) {
if($array['error'][$key] != 0) {
$files[$key] = false;
continue;
}
$files[$key] = array(
"name" => $array['name'][$key],
"tmp_name" => $array['tmp_name'][$key],
"type" => $array['type'][$key],
"error" => $array['error'][$key],
"size" => $array['size'][$key]
);
}
return $files;
}
// This will return an array of bind values and statement values
function CompileUpload($use_name = 'immagini')
{
// If empty, do nothing
if(empty($_FILES[$use_name]))
return false;
//Reorganize array
$FILES = organize($_FILES[$use_name]);
$return = false;
foreach ($FILES as $i => $file) {
if($file["error"] !== 0)
continue;
// I would suggest just saving the name and location of
// the file(s) instead of saving them to the database.
$temp = $file["tmp_name"];
$name = $file["name"];
$type = $file["type"];
$data = file_get_contents($temp);
// Create a bind array
$bind[":".$i."name"] = $name;
$bind[":".$i."type"] = $type;
$bind[":".$i."data"] = $data;
// Create the append values for the sql statement
$bCols[$i][] = ":".$i."name";
$bCols[$i][] = ":".$i."type";
$bCols[$i][] = ":".$i."data";
// Implode and save to a master row array
$iCols[] = "(".implode(",",$bCols[$i]).")";
}
// If there is no bind array (errors in file array)
// just return false
if(empty($bind))
return false;
// assign bind
$return['bind'] = $bind;
// Implode rows
$return['cols'] = implode(",",$iCols);
// return the final data array
return $return;
}
To use:
// Make sure to include the above functions here....
// Get the uploads
$uploads = CompileUpload();
// If there are uploads and the user is logged in
if(!empty($uploads) && !empty($_SESSION['id'])) {
// Is this really correct? Do you have a table for each user?
// Compile your statement
$statement = "INSERT into `".$_SESSION['id']."` (`immagine`,`type`,`profilo`) VALUES ".$uploads['cols'];
// Get connection and prepare
// You may need to do $con = connection(); $con->prepare...etc.
// but this should work
$query = connection()->prepare($statement);
// Execute with bind values
$query->execute($uploads['bind']);
}
The sql statement would look something like this:
INSERT into `whatever` (`immagine`,`type`,`profilo`) VALUES (:0name,:0type,:0data)
Multiple uploads would be:
INSERT into `whatever` (`immagine`,`type`,`profilo`) VALUES (:0name,:0type,:0data),(:1name,:1type,:1data)

Image file not inserting into database

I'm trying to get an image file to send to a file I have in my host server called productpics/ and then send the file's name into my database with all of my other data in my form. I'm getting the image file to send to the productpics folder, but then my prepared statement breaks and nothing else happens. Nothing is sent to the db. I believe it is because of the way I'm trying to send the image file to the db.
The line I believe is breaking this is....
I'm getting this error with it when I submit the form, but regardless I'm not sure if I am trying to send this to the db correctly. Am I doing this the proper way or based on what I have, how can I structure this?
Fatal error: Function name must be a string in /home4/pfarley1/public_html/addproduct.php on line 110
//Create
$filename = $_FILES['file']['name'];
//$filesize = $_FILES['file']['size'];
//$filetype = $_FILES['file']['type'];
$tmp_name = $_FILES['file']['tmp_name'];
$file_error = $_FILES['file']['error'];
if (isset($filename )) {
if (!empty($filename)) {
$destinationFolder = 'productpics/';
if (move_uploaded_file($tmp_name, $destinationFolder.$filename)) {
echo 'Uploaded!';
} else {
echo 'There was an error!';
}
} else {
echo 'Please choose a file.';
}
}
if($validation->passed()) {
if(isset($_POST['create'])){
$product_id = trim( $_POST['product_id'] );
$product_name = trim( $_POST['product_name'] );
$price = trim( $_POST['price'] );
$saleprice = trim( $_POST['saleprice'] );
$final_price = trim( $_POST['final_price'] );
$shippingprice = trim( $_POST['shippingprice'] );
$category = trim( $_POST['category'] );
$item_details = trim( $_POST['item_details'] );
$item_details2 = trim( $_POST['item_details2'] );
$description = trim( $_POST['description'] );
$viewproduct_type = trim( $_POST['viewproduct_type'] );
$file = $_POST ($filename['img']);
}else {
foreach($validation->errors() as $error) {
echo $error, '<br>';
}
//Connection
$con = mysqli_connect("localhost","root","","bfb");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* create a prepared statement */
if ($stmt = mysqli_prepare($con, "INSERT INTO products (product_id, product_name, price, saleprice, final_price, shippingprice, category, item_details, item_details2, description, viewproduct_type, date_created, img) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?)")) {
/* bind parameters for markers */
$stmt->bind_param('isiiiissssss', $product_id, $product_name, $price, $saleprice, $final_price, $shippingprice, $category, $item_details, $item_details2, $description, $viewproduct_type, $file);
/* execute query */
$stmt->execute();
//if(!$stmt->execute()){trigger_error("there was an error....".$con->error, E_USER_WARNING);}
/* close statement */
mysqli_stmt_close($stmt);
echo "Success!";
} else {
echo "Failed!";
}
}
With all of that said, I am not getting anything to echo with my else statement for my prepared statement's query. I am not getting a 'Success!' or 'Failed!'. Why aren't any results of that showing?
My form for this(the img file part is at the bottom of it...
<form action="" method="POST" enctype="multipart/form-data">
<div class="field">
<label for="product_id">Product ID</label>
<input type="text" name="product_id" class="smallinputbar" required>
</div>
<div class="field">
<label for="product_name">Product Name</label>
<input type="text" class="inputbar" name="product_name" required>
</div>
<div class="field">
<label for="price">Product Price</label>
<input type="text" class="smallinputbar" name="price" required>
</div>
<div class="field">
<label for="saleprice">Sale Price</label>
<input type="text" class="smallinputbar" name="saleprice">
</div>
<div class="field">
<label for="final_price">Final Price</label>
<input type="text" class="smallinputbar" name="final_price" required>
</div>
<div class="field">
<label for="shippingprice">Shipping Price</label>
<input type="text" class="smallinputbar" name="shippingprice" required>
</div>
<div class="field">
<label for="category">Category</label>
<input type="text" class="inputbar" name="category" required>
</div>
<div class="field">
<label for="item_details">Item Details</label>
<input type="message" class="messageinput" name="item_details" required>
</div>
<div class="field">
<label for="item_details2">Item Details 2</label>
<input type="message" class="messageinput" name="item_details2">
</div>
<div class="field">
<label for="description">Description</label>
<input type="message" class="messageinput" name="description" required>
</div>
<div class="field">
<label for="viewproduct_type">View Product Type</label>
<select class="optionbar" name="viewproduct_type">
<option value="Not Selected">Not Selected</option>
<option value="a href='./viewProduct.php?view_product=$id">Standard</option>
<option value="Option">Option</option>
</select>
</div>
<span class="floatright">
<input type="file" name="file" class="inputbarfile">
<!--<input type="submit" name="create" id="signinButton" value="Upload">-->
</span>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<label for="button">
<input type="submit" id="button" name="create" value="Create New Product">
</label>
</form>
UPDATE:
//Create
$filename = $_FILES['file']['name'];
//$filesize = $_FILES['file']['size'];
//$filetype = $_FILES['file']['type'];
$tmp_name = $_FILES['file']['tmp_name'];
$file_error = $_FILES['file']['error'];
if (isset($filename )) {
if (!empty($filename)) {
$destinationFolder = 'productpics/';
if (move_uploaded_file($tmp_name, $destinationFolder.$filename)) {
echo 'Uploaded!';
} else {
echo 'There was an error!';
}
} else {
echo 'Please choose a file.';
}
}
if($validation->passed()) {
if(isset($_POST['create'])){
$product_id = trim( $_POST['product_id'] );
$product_name = trim( $_POST['product_name'] );
$price = trim( $_POST['price'] );
$saleprice = trim( $_POST['saleprice'] );
$final_price = trim( $_POST['final_price'] );
$shippingprice = trim( $_POST['shippingprice'] );
$category = trim( $_POST['category'] );
$item_details = trim( $_POST['item_details'] );
$item_details2 = trim( $_POST['item_details2'] );
$description = trim( $_POST['description'] );
$viewproduct_type = trim( $_POST['viewproduct_type'] );
$file = $filename;
FULL PHP code for this question.
//Validation
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'product_id' => array(
'required' => true,
'min' => 1,
'max' => 50,
'unique' => 'products'
),
'product_name' => array (
'required' => true,
'min' => 2,
'max' => 50
),
'price' => array (
'required' => true,
'min' => 1,
'max' => 50
),
'saleprice' => array (
'min' => 1,
'max' => 50
),
'final_price' => array (
'required' => true,
'min' => 1,
'max' => 50
),
'shippingprice' => array (
'max' => 50
),
'category' => array (
'required' => true,
'min' => 2,
'max' => 50
),
'item_details' => array (
'required' => true,
'min' => 2,
'max' => 1550
),
'item_details2' => array (
'max' => 1550
),
'description' => array (
'required' => true,
'min' => 2,
'max' => 1550
)
)
);
//Create
if($validation->passed()) {
$filename = $_FILES['file']['name'];
//$filesize = $_FILES['file']['size'];
//$filetype = $_FILES['file']['type'];
$tmp_name = $_FILES['file']['tmp_name'];
$file_error = $_FILES['file']['error'];
if (isset($filename )) {
if (!empty($filename)) {
$destinationFolder = 'productpics/';
if (move_uploaded_file($tmp_name, $destinationFolder.$filename)) {
echo 'Uploaded!';
} else {
echo 'There was an error!';
}
} else {
echo 'Please choose a file.';
}
}
if(isset($_POST['create'])){
$product_id = trim( $_POST['product_id'] );
$product_name = trim( $_POST['product_name'] );
$price = trim( $_POST['price'] );
$saleprice = trim( $_POST['saleprice'] );
$final_price = trim( $_POST['final_price'] );
$shippingprice = trim( $_POST['shippingprice'] );
$category = trim( $_POST['category'] );
$item_details = trim( $_POST['item_details'] );
$item_details2 = trim( $_POST['item_details2'] );
$description = trim( $_POST['description'] );
$viewproduct_type = trim( $_POST['viewproduct_type'] );
$file = $filename;
$file = $_POST['img'];
}else {
foreach($validation->errors() as $error) {
echo $error, '<br>';
}
//Connection
$con = mysqli_connect("localhost","root","","bfb");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* create a prepared statement */
if ($stmt = mysqli_prepare($con, "INSERT INTO products (product_id, product_name, price, saleprice, final_price, shippingprice, category, item_details, item_details2, description, viewproduct_type, date_created, img) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?)")) {
/* bind parameters for markers */
$stmt->bind_param('isiiiissssss', $product_id, $product_name, $price, $saleprice, $final_price, $shippingprice, $category, $item_details, $item_details2, $description, $viewproduct_type, $file);
/* execute query */
$stmt->execute();
//if(!$stmt->execute()){trigger_error("there was an error....".$con->error, E_USER_WARNING);}
/* close statement */
mysqli_stmt_close($stmt);
echo "Success!";
} else {
echo "Failed!";
}
}
}
}
}
Commenting back and forth is getting to be too long at this point and am submitting the following answer, since it is too long to be a comment.
Although this may not be a solution (or possibly could, or it may lead to one), is nonetheless an answer to the problem/error message you posted.
The problem is with this line $file = $_POST ($filename['img']); and I have no idea what you're trying to do here.
You told me earlier in comments "The column I have for 'img' is text".
POST has nothing to do with a column.
POST arrays use this syntax $_POST[] using square brackets, and not $_POST() with round brackets.
That is why you're getting the following error:
Fatal error: Function name must be a string in /home4/pfarley1/public_html/addproduct.php on line 110
It's looking for a "function()" and you're trying to use $_POST as a function.
$_POST is a superglobal (pre-defined/built-in variable), and not a function.
http://php.net/manual/en/language.variables.superglobals.php
I don't know if you want to insert that uploaded file as a binary in your column, or a text-based pointer to that file, only you know the exact intention for it.
If you want to enter it as a binary, then you will need to set the associated column for it as a BLOB.
When using BLOB as a column type, then that data needs to be escaped, otherwise it will throw an error.
You will also want to check what your upload max size is set/allowed in your system files.
By default, PHP sets it to 2M. If the file exceeds that size, it will fail; increase it and anything else relative to it such as max timeout time.
You're also not doing anything with error checking in:
$file_error = $_FILES['file']['error'];
it's a stray/unused variable.
Consult:
http://php.net/manual/en/features.file-upload.errors.php
to check for errors and to use it.
As far as I'm concerning, I would get rid of $file = $_POST ($filename['img']); and use $filename for the variable you're wanting to enter in your database, since it is going inside the img column as you've set it in your query.
Check your column length to see if it's long enough to accommodate the entry.
"The column I have for 'img' is text."
You may also want to change it from TEXT to VARCHAR and set a long enough length for it. MySQL may be failing silently because of it.
Another thing I suggest you do, is to place your $filename = $_FILES['file']['name']; and other variables below that, inside your conditional statement.
If you want to use similar syntax to replace $file = $_POST ($filename['img']);, then you could add an additional input and give it the img name attribute and then do:
$file = $_POST['img'];
which would be valid.
Another thing I spotted in your first piece of code, and if that is your entire code, you're missing a closing brace } for your if($validation->passed()) { conditional statement.
The final/last brace } is associated with this block of code:
else {
foreach($validation->errors() as $error) {
echo $error, '<br>';
}
Therefore, you will need to check the bracing matches/pairs.
Edit:
In this line that you added in an edit:
$file = $filename;
$file = $_POST['img'];
You're overwriting your first variable, and you stated in comments that you do not have a form element name img.
But that is a file not text. Use $file = $_FILES['img']; or $file = $_FILES['file']; - at this point, I've no idea what your file input in the form is called.
If it still gives you trouble, use $file = $_FILES['file']['name'];
MySQL and PHP are two different animals and do not know which column is to be used for insertion.
You cannot rely on a POST array to determine the column it is to be inserted in. You need to specify that in your query.
Make sure the img column does in fact exist, and then use the $_FILES array with its related variable as the value in VALUES, being $file.
However, use $filename in your VALUES, instead of $file. Or, whatever variable; I am very confused at this point as to which variable and/or input name you're using.
and you may need to add that parameter in your $validation = $validate->check($_POST, array(... function/array.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.

Categories