How to upload multiple images but with same last_id? - php

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
?>

Related

How to upload multiple files to a PHP file

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);
}
?>

Check to see if record exists before database insert [duplicate]

This question already has answers here:
How can I do 'insert if not exists' in MySQL?
(11 answers)
Closed 2 years ago.
I have a database that contains more than 640,000 records that I update every week with data from a JSON file. What I want to do is only load records into the database that do not currently exists. My script below works on small amounts of data but when I try to load a large file it times out (I get a 500 Internal Server Error). Is there a better way to do this?
<?php
set_time_limit(0);
ini_set('memory_limit','2000M');
$url = 'json/OERrecordstest.json';
$contents = file_get_contents($url);
$records = json_decode($contents, true);
include("../config.php");
echo "<div class='card card-body'>";
foreach($records as $record) {
$type = $record['type'];
$name = $record['title'];
$title = addslashes($name);
$creator = $record['author'];
$author = addslashes($creator);
$link = addslashes($record['link']);
$origin = $record['source'];
$source = addslashes($origin);
$description = addslashes($record['description']);
$base_url = $record['base_url'];
$isbn_number = $record['isbn_number'];
$e_isbn_number = $record['e_isbn_number'];
$publication_date = $record['publication_date'];
$license = $record['license'];
$subject = addslashes($record['subject']);
$image_url = $record['image_url'];
$review = $record['review'];
$language = $record['language'];
$license_url = $record['license_url'];
$publisher = addslashes($record['publisher']);
$publisher_url = $record['publisher_url'];
$query = $conn->prepare("SELECT * FROM oer_search WHERE title=:title AND author=:author AND source=:source");
$query->bindParam(":title", $name);
$query->bindParam(":author", $creator);
$query->bindParam(":source", $origin);
$query->execute();
if ($query->rowCount() == 0) {
$insert = $conn->prepare("INSERT INTO oer_search (type, title, author, link, source, description, base_url, isbn_number, e_isbn_number, publication_date, license, subject, image_url, review, language, license_url, publisher, publisher_url) VALUES ('$type', '$title', '$author', '$link', '$source', '$description', '$base_url', '$isbn_number', '$e_isbn_number', '$publication_date', '$license', '$subject', '$image_url', '$review', '$language', '$license_url', '$publisher', '$publisher_url')");
$insert->execute();
}
}
if($insert){
echo "<p><span class='recordInserted'><em>$name was successfully inserted into SOAR.</em></span></p>";
}
else {
echo "<p><span class='recordInserted'><em>Record(s) already exist in SOAR.</em></span></p>";
}
echo "</div>";
?>
I could not comment, I wrote as an answer because my score was not enough. can you change it like this and try it?
$query = $conn->prepare("SELECT id FROM oer_search WHERE title=:title AND author=:author AND source=:source limit 1");
or
<?php
if(!session_id()) session_start();
ini_set('memory_limit', '2000M');
$url = 'json/OERrecordstest.json';
$contents = file_get_contents($url);
$records = json_decode($contents, true);
include("../config.php");
echo "<div class='card card-body'>";
if (!$_SESSION["records"]) {
foreach ($records as $record) {
$_SESSION["records"][$record["id"]] = $records;
}
}
$i = 0;
foreach ($_SESSION["records"] as $record) {
$i++;
if ($i > 1000) break;
$type = $record['type'];
$name = $record['title'];
$title = addslashes($name);
$creator = $record['author'];
$author = addslashes($creator);
$link = addslashes($record['link']);
$origin = $record['source'];
$source = addslashes($origin);
$description = addslashes($record['description']);
$base_url = $record['base_url'];
$isbn_number = $record['isbn_number'];
$e_isbn_number = $record['e_isbn_number'];
$publication_date = $record['publication_date'];
$license = $record['license'];
$subject = addslashes($record['subject']);
$image_url = $record['image_url'];
$review = $record['review'];
$language = $record['language'];
$license_url = $record['license_url'];
$publisher = addslashes($record['publisher']);
$publisher_url = $record['publisher_url'];
$query = $conn->prepare("SELECT id FROM oer_search WHERE title=:title AND author=:author AND source=:source limit 1");
$query->bindParam(":title", $name);
$query->bindParam(":author", $creator);
$query->bindParam(":source", $origin);
$query->execute();
if ($query->rowCount() == 0) {
$insert = $conn->prepare("INSERT INTO oer_search (type, title, author, link, source, description, base_url, isbn_number, e_isbn_number, publication_date, license, subject, image_url, review, language, license_url, publisher, publisher_url) VALUES ('$type', '$title', '$author', '$link', '$source', '$description', '$base_url', '$isbn_number', '$e_isbn_number', '$publication_date', '$license', '$subject', '$image_url', '$review', '$language', '$license_url', '$publisher', '$publisher_url')");
$insert->execute();
unset($_SESSION["records"][$record["id"]]);
}
}
print "remaining data :". count($_SESSION["records"]);
?>
Tipps to speed up mass-imports:
Move your SQL prepare outside of the loop (you only have to do it once)
Collect data to insert into batches of 1000 (for example.. usually alot more possible)
Use transactions / disable Index calculation during insert
Find duplicates with a lookup array from existing data (don't query the database for each row of your import)
In general: Avoid SQL queries in Loops
hope that helps a bit

Finding the MAX id of a table and inputting elsewhere

So I'm trying to get the max id of a table which I can do using
SELECT * FROM forsale ORDER BY StockID DESC LIMIT 0,1
I then save the result so I can use it in another table for reference when displaying images. The only issue is when I print the result it shows the MAX id but no inputting it into the table? Does anyone have an suggestions? I have code prior to this inputting into the forsale table and I am then getting the ID of that record. Here's what I get in the table, here's the code:
if(isset($_POST['add'])){
include '../Login-System/db.php';
$make = mysqli_real_escape_string($conn, $_POST['Make']);
$model = mysqli_real_escape_string($conn, $_POST['Model']);
$variant = mysqli_real_escape_string($conn, $_POST['Variant']);
$year = mysqli_real_escape_string($conn, $_POST['Year']);
$mileage = mysqli_real_escape_string($conn, $_POST['Mileage']);
$fuel = mysqli_real_escape_string($conn, $_POST['Fuel']);
$doors = mysqli_real_escape_string($conn, $_POST['Doors']);
$trans = mysqli_real_escape_string($conn, $_POST['transmission']);
$enginesize = mysqli_real_escape_string($conn, $_POST['Enginesize']);
$price = mysqli_real_escape_string($conn, $_POST['Price']);
$description = mysqli_real_escape_string($conn, $_POST['description']);
$makeupper = strtoupper($make);
$modelupper =strtoupper($model);
$variantupper =strtoupper($variant);
$sqlcarinsert = "INSERT INTO forsale (make, model, variant, year, mileage, fuel, doors, trans, enginesize, price, description) VALUES ('$makeupper','$modelupper','$variantupper','$year','$mileage','$fuel','$doors','$trans','$enginesize','$price','$description');";
//Image Upload
//Find next StockID
$sql = "SELECT * FROM forsale ORDER BY StockID DESC LIMIT 0, 1";
$result = mysqli_query($conn, $sql);
$stockIDtable = mysqli_fetch_assoc($result);
$stockID = $stockIDtable['StockID'];
if(!empty($_FILES['files']['name'][0])){
$files = $_FILES['files'];
//File Extensions allowed
$allowed = array('jpg', 'jpeg', 'png');
foreach ($files['name'] as $position => $file_name) {
$file_tmp = $files['tmp_name'] [$position];
$file_size = $files['size'] [$position];
$file_error = $files['error'] [$position];
//Order
$orderimg = $position;
//Get file extension
$FileExt = explode('.', $file_name);
$endext = end($FileExt);
$fileActualExt = strtolower($endext);
if (in_array($fileActualExt, $allowed)) {
//Checks for Errors in uploading
if ($file_error === 0) {
//New name to remove possibilities of duplicates
$fileNameNew = uniqid('', true).".".$fileActualExt ;
$FileDestination = '../Photos/forsale/'.$fileNameNew;
$SQLDestination = 'Photos/forsale/'.$fileNameNew;
//Upload to Designated folder with name
move_uploaded_file($file_tmp, $FileDestination);
//Insert into forsaleimg
$sqlimginsert = "INSERT INTO forsaleimg (id, StockID, imgOrder, FileDestination) VALUES ('NULL', '$stockID', '$orderimg', '$SQLDestination');";
mysqli_query($conn, $sqlimginsert);
//echo "<pre>";
//print_r($sqlimginsert);
//echo "</pre>";
$orderimg++ ;
} else {
header("Location: ../salelist.php?upload=error");
exit();
}
} else {
header("Location: ../salelist.php?fucked");
exit();
}
}
}
mysqli_query($conn, $sqlcarinsert);
header("Location: ../salelist.php?added=".$make);
exit();
} else {
header("Location: ../salelist.php?add=notclicked");
exit();
}
Use the query as:-
$sql = "select * from forsale
where StockID = (select max(StockID) as 'StockID'
from forsale)
order by StockID" ;

Unable to store pic link into database

I am trying to upload my pic into folder and file link store into database although file store in folder but unfortunately doesn't store link in database. Please see where I am doing mistake.
<?php
include('dbconnection.php');
if(count($_FILES["file"]["name"]) > 0)
{
sleep(3);
for($count=0; $count<count($_FILES["file"]["name"]); $count++)
{
$file_name = $_FILES["file"]["name"][$count];
$tmp_name = $_FILES["file"]['tmp_name'][$count];
$file_array = explode(".", $file_name);
$file_extension = end($file_array);
if(file_already_uploaded($file_name, $connect))
{
$file_name = $file_array[0] . '-'. rand() . '.' . $file_extension;
}
$location = 'files/' . $file_name;
if(move_uploaded_file($tmp_name, $location))
{
$stmt= $connect->prepare("INSERT INTO tbl_image (image_name) VALUES (:image_name)");
$stmt->bindParam(':image_name', $file_name);
$stmt->execute();
}
}
}
function file_already_uploaded($file_name, $connect)
{
$statement = $connect->prepare("SELECT image_name FROM tbl_image WHERE image_name = '".$file_name."'");
$statement->execute();
$number_of_rows = $statement->rowCount();
if($number_of_rows > 0)
{
return true;
}
else
{
return false;
}
}
?>
store the image name as location with file name:
$location = 'files/' . $file_name;
if(move_uploaded_file($tmp_name, $location))
{
$stmt= $connect->prepare("INSERT INTO tbl_image (image_name) VALUES (:image_name)");
$stmt->bindParam(':image_name', $location.'/'.$file_name);
$stmt->execute();
}

Sql issues when trying to upload using php

I'm trying to upload a video to a folder which is working but, the relevant entry in the DB isn't occurring to match it. Really having trouble seeing what's wrong, as no errors are reported.
session_start();
require 'db.php';
$name = $_FILES['video']['name'];
$uploader = $_SESSION['first_name'].$_SESSION['last_name'];
$newstring = $_SESSION['last_name'].'_'.$_SESSION['first_name'].'_'.date('ymdhms').".mp4";
$extension = strtolower(substr($name, strpos($name, '.') + 1));
$size = $_FILES['video']['size'];
$max_size = '1073741824';
$type = $_FILES['video']['type'];
$id = $_SESSION['id'];
$date = date('Y-m-D');
$tmp_name = $_FILES['video']['tmp_name'];
if(!empty($name)){
$location = "uploads/";
if($extension=='mp4'&&$type == 'video/mp4'){
if($size <= $max_size){
if(move_uploaded_file($tmp_name, $location.$newstring)){
$sql = "INSERT INTO videos (file_name, upload_by, date) VALUES
('$newstring', '$id', '$date')";
mysqli_query($mysqli, $sql);
require('profile.php');
$_SESSION['message'] = "Upload Successful!";
header('Refresh:0; url=profile.php');
}else{
$_SESSION['message'] = "File failed to upload";
header("location: error.php");
}
I'm not getting a corresponding DB entry. Any help would be really appreciated.
Try this:
$sql = "INSERT INTO videos (file_name, upload_by, date) VALUES
('".$newstring."', '".$id."', '".$date."')";

Categories