How to upload multiple files to a PHP file - php

I am currently creating this code for a website. I have this file upload working but I am needing to upload multiple files instead of one. I don't know the best way to do this with my current code. Any help is appreciated.
<?php
include "DbConnect.php";
$db = new DbConnect();
$conn = $db->connect();
//INSERT INTO account(AccountID, Username, Password, LastName, FirstName, Accountemail, phone) values(1, 'dsf', 'sdf', 'sdf','df','dsf', '')
$sql="INSERT INTO Product(sku, ItemName, ItemDescription, Quantity, PostDate, ItemPrice,
Accountemail, Category, Image) values(".$_POST["sku_no"].", '".$_POST["item_name"]."', '".$_POST["item_desc"]."',".$_POST["qty"].",'".$_POST["date_of_sale"]."', ".$_POST["price"].", '".$_POST["Accountemail"]."', '".$_POST["category"]."','')";
// Loop through each file
if ($conn->query($sql)) {
$photo = $_FILES["file"];
$filename = '';
if (!file_exists("images")) {
mkdir("images", 0777, true);
}
$filename = time().'_'. $photo['name'];
$file = "images/" . $filename;
$thumb_image = $photo;
if (move_uploaded_file($photo['tmp_name'], $file)) {
$sql_query = "UPDATE Product SET Image = '".$filename."' WHERE ProductID = $conn->insert_id";
$stmt = $conn->prepare($sql_query);
$stmt->execute();
$stmt->close();
}
$data = array(
'message' => "Product added successfully",
'success'=>"1"
);
//redirect to questionnaire page
//echo 0;
//echo $data;
echo json_encode($data);
}else{
$data = array(
'message' => "Product not added",
'success'=>"0"
);
echo json_encode($data);
}
?>

Related

File path with '/' is not inserting in DB

I need to check duplicate files from a path and need to insert the file name in a table if it is new and then insert all records of it accordingly into another table. Do not insert or step forward if file already exists.
Here is my code where i can't bring the file path with '/' into the DB. Can anyone assist? Thanks in advance.
File Path with '/' is not passing using $open = fopen('$cont[$x]','r');
<?php
//include ("connection.php");
$conn = new mysqli('localhost','root','','demo');
$path = _DIR_ . DIRECTORY_SEPARATOR ."*.{txt}";
$cont = glob($path, GLOB_BRACE);
//print_r($content);
$arrlength = count($cont);
for($x = 0; $x < $arrlength; $x++){
// $sql = "INSERT INTO `file_record` (`file_name`) VALUES ('$cont[$x]') ";
$dup = mysqli_query($conn,"SELECT * FROM file_record WHERE file_name = '$cont[$x]' ");
if(mysqli_num_rows($dup)>0)
{
echo "File already Exists";
}
else {
$insert = "INSERT INTO `file_record` (`file_name`) VALUES ('$cont[$x]') ";
// $conn->query($insert);
if (mysqli_query($conn,$insert)) {
$open = fopen('$cont[$x]','r');
while (!feof($open))
{
$content = fgets($open);
$carry = explode(",",$content);
list($name,$city,$postcode,$job_title) = $carry;
$sql = "INSERT INTO `employee` (`name`, `city`, `postcode`, `job_title`) VALUES ('$name','$city','$postcode','$job_title')";
$conn->query($sql);
}
fclose($open);
echo 'inserted';
} else {
echo 'Not inserted';
}
}
}
?>

inserting information and image in php and mysql

please help guys i have code for inserting name and etc.. and for inserting a image i cant combine the codes
here is the ouput in phpmyadmin i only insert one value thou...
thanks for your help guys
<---!THIS CODE BELOW IT INSERT ID,NAME AND ETC --->
<?php
require 'db.php';
$message = '';
$Error = '';
if (isset ($_POST['Attendee_id']) &&
isset($_POST['RFID_number']) &&
isset($_POST['Attendee_Name']) &&
isset($_POST['CourseOrDepartment']) &&
isset ($_POST['Status']) ) {
$Attendee_id = $_POST['Attendee_id'];
$RFID_number = $_POST['RFID_number'];
$Attendee_Name = $_POST['Attendee_Name'];
$CourseOrDepartment = $_POST['CourseOrDepartment'];
$Status = $_POST['Status'];
$sql = 'INSERT INTO tbl_listofregister(Attendee_id,
RFID_number,Attendee_Name,CourseOrDepartment,Status)
VALUES(:Attendee_id,
:RFID_number,:Attendee_Name,:CourseOrDepartment,:Status)';
$statement = $connection->prepare($sql);
if ($statement->execute([':Attendee_id' => $Attendee_id, ':RFID_number' =>
$RFID_number,':Attendee_Name' => $Attendee_Name,':CourseOrDepartment' =>
$CourseOrDepartment,':Status' => $Status])) {
$message = 'DATA INSERTED SUCCESSFULLY';
}
else
{
$Error = "ID SHOULD BE UNIQUE";
}
}
?>
<---! HERE IS FOR IMAGE --->
<?php
$msg = '';
if($_SERVER['REQUEST_METHOD']=='POST'){
$image = $_FILES['Image']['tmp_name'];
$img = file_get_contents($image);
$con = mysqli_connect('localhost','root','','dbattendancelibrary') or
die('Unable To connect');
$sql = "insert into tbl_listofregister (image) values(?)";
$stmt = mysqli_prepare($con,$sql);
mysqli_stmt_bind_param($stmt, "s",$img);
mysqli_stmt_execute($stmt);
$check = mysqli_stmt_affected_rows($stmt);
if($check==1){
$msg = 'Image Successfullly UPloaded';
}else{
$msg = 'Error uploading image';
}
mysqli_close($con);
}
?>
This would combine the two inserts into one action. But I would advise against storing the images in the db. Store the path relative to your site of the image instead.
<?php
require 'db.php';
$message = '';
$Error = '';
if(isset($_POST['Attendee_id']) &&
isset($_POST['RFID_number']) &&
isset($_POST['Attendee_Name']) &&
isset($_POST['CourseOrDepartment']) &&
isset($_POST['Status']) &&
isset($_FILES['Image']['tmp_name']) &&
$_SERVER['REQUEST_METHOD']=='POST') {
$Attendee_id = $_POST['Attendee_id'];
$RFID_number = $_POST['RFID_number'];
$Attendee_Name = $_POST['Attendee_Name'];
$CourseOrDepartment = $_POST['CourseOrDepartment'];
$Status = $_POST['Status'];
$image = $_FILES['Image']['tmp_name'];
$img = file_get_contents($image);
$sql = 'INSERT INTO tbl_listofregister(
Attendee_id,
RFID_number,
Attendee_Name,
CourseOrDepartment,
Status,
image)
VALUES(:Attendee_id,
:RFID_number,
:Attendee_Name,
:CourseOrDepartment,
:Status,
:Image)';
$statement = $connection->prepare($sql);
if($statement->execute(
[':Attendee_id' => $Attendee_id,
':RFID_number' => $RFID_number,
':Attendee_Name' => $Attendee_Name,
':CourseOrDepartment' => $CourseOrDepartment,
':Status' => $Status,
':Image' => $img]
)) {
$message = 'DATA INSERTED SUCCESSFULLY';
} else {
$Error = "ID SHOULD BE UNIQUE";
}
}
?>
$Attendee_id = $_POST['Attendee_id'];
$RFID_number = $_POST['RFID_number'];
$Attendee_Name = $_POST['Attendee_Name'];
$CourseOrDepartment = $_POST['CourseOrDepartment'];
$Status = $_POST['Status'];
After these lines , you can add this line for an img
move_uploaded_file($_FILES['file']['tmp_name'], "filename/".$_FILES['file']['name']);
Then, add it in the query as ( $_FILES['file']['name'] ).
in HTML file write this line ( ).
I hope it's work well <3

How to store audio file on server?

<?php
include("db.php");
$uploadDir = "../audioupload/";
$uid=$_POST['uid'];
$meeting_id=$_POST['meeting_id'];
$fileName = $_FILES['audio']['name'];
$tmpName = $_FILES['audio']['tmp_name'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
if($result)
{
$sql="INSERT INTO `audio`(`uid`,`meeting_id`,`audio`) VALUES ('".$uid."','".$meeting_id."','".$result."')";
$result1 = mysqli_query($conn,$sql);
if($result1)
{
$sql1="select * from `audio` where `uid`='$_POST[uid]'";
$result = mysqli_query($conn,$sql1);
$count = mysqli_num_rows($result);
}
if($count>0)
{
$emparray = array();
while($row = mysqli_fetch_array($result))
{
$emparray=array(
'success' => true,
'message' => "Audio saved Successfully!",);
}
}
}
else
{
$row = mysqli_fetch_array($result);
$emparray=array(
'success' => false,
'message' => "Incorrect Data!",
);
}
echo json_encode($emparray,JSON_PRETTY_PRINT,JSON_FORCE_OBJECT);
mysqli_close($conn);
?>
this is my code. im creating restful api for storing audio on server.im testing this link with postman tool. it gives me correct json response on postman. and audio saves in mysql database. But it not store in folder named audioupload that is subfolder in another folder. please help me with the same

How to upload multiple images but with same last_id?

I am trying to insert multiple images with the same last_id
But I am having a problem the code does not do exactly what am looking for
I have two tables one is user table and the image’s table so I want each user when he or she uploads images they should grab the last ids and use them in image’s table but also each image will be having a unique image Id . in the user table there user_id as primary key and in the image table there is user_id as a fk and image_d pk . bellow is my code .
<?php
$target = 'image_uploads/';
if(isset($_FILES['image_name'])===true){
$files = $_FILES['image_name'];
for($x = 0 ; $x < count($files['name']); $x++){
$name = $files['name'][$x] ;
$temp_name = $files['tmp_name'][$x];
#extention filter it takes only the extension want
$allowed ='gif,png,jpg,pdf';
$extension_allowed= explode(',',$allowed );
$file_extention = pathinfo($name, PATHINFO_EXTENSION);
if(array_search($file_extention,$extension_allowed)){
}else {
echo 'We only allow gif, png ,jpg';
exit();
} #extention filter ends here
#check the size of the image
$file_size = $files['size'][$x];
if($file_size > 2097152){
echo 'The file should be lesS than 2MB';
exit();
}
#check the size of the image ends here
#Rename images
$sub = substr(md5(rand()),0,7);
#the above generates char and numbesr
$rand = rand(0,100000);
$rename = $rand.$sub.$name;
#Rename images ends here
$move = move_uploaded_file($temp_name,$target.$rename);
#code to deal with the picture uploads ends here
}}
?>
<?php
try{
$query="INSERT INTO tish_user(username,Password,Previllage,date_created)
VALUES(:username,:Password,:Previllage,:date_created)";
$insert = $con->prepare($query);
$insert->execute(array(
':username'=>$user,
':Password'=>$Password,
':Previllage'=>$Previllage,
':date_created'=>$date_created));
#end of first table
################################################
#You select the first Id and put it in a variable then
$id_last = ("SELECT LAST_INSERT_ID()");
$result =$con->prepare($id_last);
$result->execute();
$last_id = $result->fetchColumn();
############################## Last Id query Ends here
#insert into clientinfo table
$clientinfor="INSERT INTO tish_clientinfo
(title, firstname, lastname, nickname, idnumber, client_code,
company, country, city, province, address, cell,
tel, webaddress, satifiedstatus, email, job_approval, cash_with_vat,
cash_paid, date_registered,user_id)
VALUES(:title,:firstname,:lastname,:nickname,:idnumber,:client_code,
:company,:country,:city,:province,:address,
:cell,:tel,:webaddress,:satifiedstatus, :email, :job_approval,
:cash_with_vat,:cash_paid, :date_registered,$last_id)";
$clientinfor_insert = $con->prepare($clientinfor);
$clientinfor_insert->execute(array(
':title'=>$title,
':firstname'=>$firstname,
':lastname'=>$lastname,
':nickname'=>$nickname,
':idnumber'=>$idnumber,
':client_code'=>$client_code,
':company'=>$company,
':country'=>$country,
':city'=>$city,
':province'=>$province,
':address'=>$address,
':cell'=>$cell,
':tel'=>$tel,
':webaddress'=>$webaddress,
':satifiedstatus'=>$satifiedstatus,
':email'=>$email,
':job_approval'=>$job_approval,
':cash_with_vat'=>$cash_with_vat,
':cash_paid'=>$cash_paid,
':date_registered'=>$date_registered
));
#end of clien infor
################################################
$security="INSERT INTO tish_security(ip_address,user_id)
VALUES(:ip_address,$last_id)";
$security_insert = $con->prepare($security);
$security_insert->execute(array(
':ip_address'=>$ip_address));
##########################end of security
############ images
$images ="INSERT INTO tish_images(user_id,image_name,date_registered)
VALUES($last_id,:image_name,:date_registered)";
$images_insert = $con->prepare($images);
$images_insert->execute(array(
':image_name'=>$rename,
':date_registered'=>$date_created));
##############################category
$cats = $vals = array();
foreach ((array) $_POST['category_name'] as $cat) {
if ('' !== ($cat = trim($cat))) {
$cats[] = $cat;
$vals[] = "({$last_id}, ?)";
}
}
################################################
$sql = 'INSERT INTO tish_catigory (user_id, category_name) VALUES'. join(',', $vals);
$sth = $con->prepare($sql);
foreach ($cats as $i => $cat) {
$sth->bindValue($i+1, $cat, PDO::PARAM_STR);
}
$sth->execute();
}catch(PDOException $e){
echo $e->getMessage();
}
var_dump($last_id);
?>
That should work I tested it and it worked
<?php
try{
$query="INSERT INTO tish_user(username,Password,Previllage,date_created)
VALUES(:username,:Password,:Previllage,:date_created)";
$insert = $con->prepare($query);
$insert->execute(array(
':username'=>$user,
':Password'=>$Password,
':Previllage'=>$Previllage,
':date_created'=>$date_created));
#end of first table
################################################
#You select the first Id and put it in a variable then
$id_last = ("SELECT LAST_INSERT_ID()");
$result =$con->prepare($id_last);
$result->execute();
$last_id = $result->fetchColumn();
############################## Last Id query Ends here
#insert into clientinfo table
$clientinfor="INSERT INTO tish_clientinfo
(title, firstname, lastname, nickname, idnumber, client_code,
company, country, city, province, address, cell,
tel, webaddress, satifiedstatus, email, job_approval, cash_with_vat,
cash_paid, date_registered,user_id)
VALUES(:title,:firstname,:lastname,:nickname,:idnumber,:client_code,
:company,:country,:city,:province,:address,
:cell,:tel,:webaddress,:satifiedstatus, :email, :job_approval,
:cash_with_vat,:cash_paid, :date_registered,$last_id)";
$clientinfor_insert = $con->prepare($clientinfor);
$clientinfor_insert->execute(array(
':title'=>$title,
':firstname'=>$firstname,
':lastname'=>$lastname,
':nickname'=>$nickname,
':idnumber'=>$idnumber,
':client_code'=>$client_code,
':company'=>$company,
':country'=>$country,
':city'=>$city,
':province'=>$province,
':address'=>$address,
':cell'=>$cell,
':tel'=>$tel,
':webaddress'=>$webaddress,
':satifiedstatus'=>$satifiedstatus,
':email'=>$email,
':job_approval'=>$job_approval,
':cash_with_vat'=>$cash_with_vat,
':cash_paid'=>$cash_paid,
':date_registered'=>$date_registered
));
#end of clien infor
################################################
$security="INSERT INTO tish_security(ip_address,user_id)
VALUES(:ip_address,$last_id)";
$security_insert = $con->prepare($security);
$security_insert->execute(array(
':ip_address'=>$ip_address));
##########################end of security
############ images
#code to deal with the picture uploads
#target folder
$target = 'image_uploads/';
if(isset($_FILES['image_name'])===true){
$files = $_FILES['image_name'];
for($x = 0 ; $x < count($files['name']); $x++){
$name = $files['name'][$x] ;
$temp_name = $files['tmp_name'][$x];
#extention filter it takes only the extension want
$allowed ='gif,png,jpg,pdf';
$extension_allowed= explode(',',$allowed );
$file_extention = pathinfo($name, PATHINFO_EXTENSION);
if(array_search($file_extention,$extension_allowed)){
}else {
echo 'We only allow gif, png ,jpg';
exit();
} #extention filter ends here
#check the size of the image
$file_size = $files['size'][$x];
if($file_size > 2097152){
echo 'The file should be lesS than 2MB';
exit();
}
#check the size of the image ends here
#Rename images
$sub = substr(md5(rand()),0,7);
#the above generates char and numbesr
$rand = rand(0,100000);
$rename = $rand.$sub.$name;
#Rename images ends here
$move = move_uploaded_file($temp_name,$target.$rename);
#code to deal with the picture uploads ends here
$images ="INSERT INTO tish_images(user_id,image_name,date_registered)
VALUES($last_id,:image_name,:date_registered)";
$images_insert = $con->prepare($images);
$images_insert->execute(array(
':image_name'=>$rename,
':date_registered'=>$date_created));
}}
##############################category
$cats = $vals = array();
foreach ((array) $_POST['category_name'] as $cat) {
if ('' !== ($cat = trim($cat))) {
$cats[] = $cat;
$vals[] = "({$last_id}, ?)";
}
}
################################################
$sql = 'INSERT INTO tish_catigory (user_id, category_name) VALUES'. join(',', $vals);
$sth = $con->prepare($sql);
foreach ($cats as $i => $cat) {
$sth->bindValue($i+1, $cat, PDO::PARAM_STR);
}
$sth->execute();
############# property table##########################################################
/*$property ="INSERT INTO tish_propertyinfo(user_id,date_registered)
VALUES($last_id,:date_registered)";
$property_insert = $con->prepare($images);
$property_insert->execute(array(':date_registered'=>$date_created));
*/}catch(PDOException $e){
echo $e->getMessage();
}
#for the insert check boxes
var_dump($last_id);
#images
?>

Unexpected result after file upload

This code is to update database. it updates everything even uploads image sucessfully but after image upload the whole page gets blank and only "Array()" is displayed at top. Why is that?
<?php
if(!isset($_GET["prid"])){
header("Location: prjedit.php");
}
else {
$prid = intval($_GET["prid"]);
$sqlprj = "SELECT * FROM projects WHERE id = ? LIMIT 1";
$statement = $db->prepare($sqlprj);
$statement->execute(array($prid));
$project = $statement->fetchObject();
//submitted form
if( (isset($_POST["title"])) && (isset($_POST["details"])) ) {
$title = $_POST['title'];
$desc = $_POST['descr'];
$details = $_POST['details'];
if(!empty($_FILES['image']['name'])) {
//update image
$file = basename($_FILES['image']['name']);
$dir = "projects/";
$target_path = $dir . basename($_FILES['image']['name']);
$tempname = $_FILES['image']['tmp_name'];
if(!file_exists($target_path)) {
if(move_uploaded_file($tempname, $target_path)) {
$sqlimg = "UPDATE projects SET image = ? WHERE id = ?";
$statement = $db->prepare($sqlimg);
$statement->execute(array($file, $prid));
if($statement->rowCount() > 0) {
try {
chdir('./projects/');
unlink($project->image);
chdir('..');
}
catch (Exception $e) {
$message = "Sorry image delete failed ";
echo $e->getMessage();
}
}
else {
die ($db->errorInfo());
}
}
else {
$message = "Sorry Image update failed";
}
}
else {
$message = "Sorry this image already exists but text";
}
}
// update project texts
$sqlupd = "UPDATE projects SET title = ?, descinfo = ?, details = ? WHERE id = ?";
$statement = $db->prepare($sqlupd);
$statement->execute(array($title, $desc, $details, $prid));
if($statement->rowCount()) {
$message = " Saved successfully";
}
else {
die($db->errorInfo());
}
}
}
?>
Looking at Pdo::codeInfo documentation, it returns an array.
When you write die($db->errorInfo()); it will try to display this array.
As suggested by the documentation itself, you could try print_r($db->errorInfo()); die; and see what happens.

Categories