Back again! So I'm trying to upload multiple images to a server and save the path and corresponding stock number in the database. Currently I have the car details, $sqlcarinsert, working and inserting into the relevant database, forsale.
The issue arises when I try save all of the image details. I have the images being given new names and uploading to the server but not being inputted into the database with the stockID, which links it to the advert, as well as the filepath. Along with this only one of the files is being inputted into the database not say all three that uploaded to the server. Is this possible to do?
Need anything else let me know I shall try my best to provide!
P.S Yes I know prepared statements, shoody code etc etc..
<?php
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']);
$sqlcarinsert = "INSERT INTO forsale (make, model, variant, year, mileage, fuel, doors, trans, enginesize, price, description) VALUES ('$make','$model','$variant','$year','$mileage','$fuel','$doors','$trans','$enginesize','$price','$description');";
//Image Upload
//Find next StockID (Surely not, right?)
$sql = "SELECT * FROM forsale ;";
$result = mysqli_query($conn, $sql);
$rowcount = mysqli_num_rows($result);
$stockID = $rowcount + 1;
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];
//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) {
include '../Login-System/db.php';
//New name to remove possibilities of duplicates
$fileNameNew = uniqid('', true).".".$fileActualExt ;
$FileDestination = '../Photos/forsale/'.$fileNameNew;
//Upload to Designated folder with name
move_uploaded_file($file_tmp, $FileDestination);
//Insert into forsaleimg
$sqlimginsert = "INSERT INTO forsaleimg (StockID, FileDestination) VALUES ('$stockID','$FileDestination');";
mysqli_query($conn, $sqlimginsert);
} else {
header("Location: ../salelist.php?upload=error");
exit();
}
}
}
}
mysqli_query($conn, $sqlcarinsert);
header("Location: ../salelist.php?added=".$make);
exit();
} else {
header("Location: ../salelist.php?add=notlcicked");
exit();
}
Related
values are not mapping in database table columns
this is my code
<?php
if (isset($_POST["import"])) {
ini_set('max_execution_time', 120); //300 seconds = 5 minutes
//$filename = $_FILES['file']['name'];
$file = $_FILES['file']['tmp_name'];
//$ext=substr($file,strrpos($file,"."),(strlen($file)-strrpos($file,".")));
//if($ext=="csv")
$handle = fopen($file, "r");
//$c = 0;
while(($filesop = fgetcsv($handle,",")) !== false)
{
$category = mysqli_real_escape_string($filesop[0]);
$tags = mysqli_real_escape_string($filesop[1]);
$title = mysqli_real_escape_string($filesop[2]);
$url = mysqli_real_escape_string( $filesop[3]);
$description = mysqli_real_escape_string($filesop[4]);
$date = mysqli_real_escape_string($filesop[5]);
//print_r($filesop);
var_dump($filesop);
//echo $filesop[0];
$sql = "insert into report(category,tags,title,url,description,date) values ('$category','$tags','$title','$url','$description','$date')";
//$c = $c + 1;
$result=mysqli_query($conn,$sql)or die($sql."<br/><br/>".mysql_error());
//echo $sql;
//echo $filesop[1];
//echo "success";
exit();
}
//if($result){
//echo " upload success";
//ini_set('auto_detect_line_endings',FALSE);
fclose($handle);
// }
//else
// echo "cannot upload csv file";
}
mysqli_close($conn);
?>
returns null in my output screen
var_dump($filesop);
my database sample screen shot
my csv file
Marketing & Customer Analytics,Trends & Product Updates,Segment Launches Segment Select,https://martechseries.com/analytics/customer-data-platforms/segment-launches-segment-select-new-program-help-companies-leverage-first-party-data-certified-partners/,"Segment, the customer data infrastructure company, launched Segment Select, a new program designed to help Channel and Technology Partners easily build and implement solutions for their customers that leverage Segment’s Customer Data Infrastructure (CDI).",2/24/2019
The issue in your code mysqli_real_escape_string, you missed parameters in mysqli_real_escape_string function. You need to pass the database object in mysqli_real_escape_string function.
Like example :
Your code : $category = mysqli_real_escape_string($filesop[0]);
New code : $category = mysqli_real_escape_string($conn,$filesop[0]);
also helpful code below please check it.
while(($filesop = fgetcsv($handle,",")) !== false)
{
$category = mysqli_real_escape_string($conn, $filesop[0]);
$tags = mysqli_real_escape_string($conn, $filesop[1]);
$title = mysqli_real_escape_string($conn, $filesop[2]);
$url = mysqli_real_escape_string($conn, $filesop[3]);
$description = mysqli_real_escape_string($conn, $filesop[4]);
$date = mysqli_real_escape_string($conn, $filesop[5]);
$sql = "insert into report(category,tags,title,url,description,date) values ('$category','$tags','$title','$url','$description','$date')";
$result=mysqli_query($conn,$sql)or die($sql."<br/><br/>".mysqli_error($conn));
exit();
}
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" ;
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."')";
I wrote a php script to extract data from a csv script and insert it into an mysql database. It does the job but does not extract data and insert into database for large csv files.(I tried extracting and inserting from a csv file with 40,000 rows. Did not work but worked when i tested it out with a far smaller (60 rows) size csv file). I get no error message. It just doesn't work. During debugging i realised even echoing a string after selecting a large csv file and clicking my upload button does not work. I've searched and tried all the possible configurations in php.ini as well as LimitRequestBody for apache config as well as setting configs directly in my code to no success. Some help would be greatly appreciated. My code is below.
<?php
include ("connection.php");
if(isset($_POST["submit"]))
{
ini_set('auto_detect_line_endings',TRUE);
$file_name = $_FILES['file']['tmp_name'];
$sql10 = "insert into upload (filename) values ('$file_name')";
if(mysqli_query($conn, $sql10)){
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " .$last_id;
}
//mysqli_close($conn);
$file = $_FILES['file']['tmp_name'];
//ini_set("auto_detect_line_endings", true);
$handle = fopen($file, "r");
$c = 0;
while(($filesop = fgetcsv($handle, ",")) !== false)
{
if ($c > 0) {
$event_id = $filesop[0];
$conf_session_id = $filesop[1];
$service_provider_id = $filesop[2];
$service_provider_id2 = $filesop[3];
$billed_flag = $filesop[4];
$offering_id = $filesop[5];
$time_start = $filesop[6];
$time_ended = $filesop[7];
$duration = $filesop[8];
$orig_calling_code = $filesop[9];
$orig_area_code = $filesop[10];
$termination_reason = $filesop[11];
$rtp_encoding = $filesop[12];
$rtp_clock_rate = $filesop[13];
$sip_from = $filesop[14];
$sip_to = $filesop[15];
$sip_call_id = $filesop[16];
$orig_nbr = $filesop[17];
$dest_nbr = $filesop[18];
$popd_account_number = $filesop[19];
$intl_dest_flag = $filesop[20];
$sip_status = $filesop[21];
$gw_ip_ingress = $filesop[22];
$gw_port_egress = $filesop[23];
$phone_number = $filesop[24];
$orig_flag = $filesop[25];
$subscriber_sip_caller_id = $filesop[26];
$orig_route_type = $filesop[27];
$term_route_type = $filesop[28];
$call_type = $filesop[29];
$mny_BasePrice = $filesop[30];
$call_cost = $filesop[31];
$uploadID = $last_id;
$sql11 = "insert into cdr (event_id, conf_session_id, service_provider_id, service_provider_id2, billed_flag, offering_id, time_start, time_ended, duration, orig_calling_code, orig_area_code, termination_reason, rtp_encoding, rtp_clock_rate, sip_from, sip_to, sip_call_id, orig_nbr, dest_nbr, popd_account_number, intl_dest_flag, sip_status, gw_ip_ingress, gw_port_egress, phone_number, orig_flag, subscriber_sip_caller_id, orig_route_type, term_route_type, call_type, mny_BasePrice, call_cost, uploadID, date_uploaded) values ('$event_id', '$conf_session_id', '$service_provider_id', '$service_provider_id2', '$billed_flag', '$offering_id', '$time_start', '$time_ended', '$duration', '$orig_calling_code', '$orig_area_code', '$termination_reason', '$rtp_encoding', '$rtp_clock_rate', '$sip_from', '$sip_to', '$sip_call_id', '$orig_nbr', '$dest_nbr', '$popd_account_number', '$intl_dest_flag', '$sip_status', '$gw_ip_ingress', '$gw_port_egress', '$phone_number', '$orig_flag', '$subscriber_sip_caller_id', '$orig_route_type', '$term_route_type', '$call_type', '$mny_BasePrice', '$call_cost', '$uploadID', CURRENT_DATE)";
if(mysqli_query($conn, $sql11)){
// $last_id = mysqli_insert_id($conn);
// echo "New record created successfully. Last inserted ID is: " .$last_id;
$updatequery = "UPDATE cdr JOIN client ON cdr.orig_nbr = client.phonenumber SET cdr.clientname = client.clientname";
mysqli_query($conn, $updatequery);
} else{
echo "error: ".mysqli_error($conn);
}
}
$c++;
}
fclose($handle) ;
}
?>
Hi i'm trying to receive my images from the database. I already can insert the images, but I don't know if it goes wrong overthere or that I do something wrong with getting the image.
The code for inserting the image:
public function Save(){
/*** check if a file was uploaded ***/
if(is_uploaded_file($_FILES['userfile']['tmp_name']) && getimagesize($_FILES['userfile']['tmp_name']) != false)
{
/*** get the image info. ***/
$size = getimagesize($_FILES['userfile']['tmp_name']);
/*** assign our variables ***/
$type = $size['mime'];
$imgfp = fopen($_FILES['userfile']['tmp_name'], 'rb');
$size = $size[3];
$name = $_FILES['userfile']['name'];
$maxsize = 99999999;
/*** check the file is less than the maximum file size ***/
if($_FILES['userfile']['size'] < $maxsize )
{
/*** connect to db ***/
$db = new Db();
/*** our sql query ***/
$sql = "INSERT INTO Foto (image_type ,image, image_size, image_name)
VALUES ('". $type ."',
'". $imgfp ."',
'". $size ."',
'". $name ."');";
$db->conn->query($sql);
$sql = "SELECT * FROM Foto ORDER BY id DESC LIMIT 1;";
$select = $db->conn->query($sql);
$numberofRows = $select->num_rows;
if($numberofRows == 1)
{
while ($oneSelect = $select->fetch_assoc())
{
return $oneSelect;
}
} else {
throw new Exception("Fout");
}
}
else
{
throw new Exception("Bestand is te groot");
}
}
else
{
throw new Exception("Dit extensie is niet ondersteund");
}
}
The code for loading the images:
<?php
include_once("classes/Db.class.php");
//$id = $_GET['id'];
$id = "33";
$db = new Db();
$sql = "SELECT image, image_type FROM Foto WHERE id = '". $id ."';";
$result = $db->conn->query($sql);
$row = $result->fetch_assoc();
if(sizeof($row) == 2)
{
header("Content-type: ".$row['image_type']);
echo $row['image'];
}
else
{
throw new Exception("Out of bounds Error");
}
?>
You're not actually inserting the image data. Read up on the fopen() function, it doesn't return the image data, but a file handle that can then be used for reading from or writing to a file (using, for example, fread() or fwrite()). Easy way out is using file_get_contents().
But take my advice, it's really bad practice to store images in the database. They're files and better off stored on the file system (hence the name). Makes serving them a lot faster too, as no PHP request has to be executed. Store the filename and maybe a relative path to the file in the database instead.