I need to upload multiple images with php and MySQL but every time I try to upload it's only upload 1 image to database but in the file (uploads\companies) it shown me 4 images
I tried, but I don't find any solution so if anyone can help me
This is my code
$name = $_POST['name'];
$field = $_POST['field'];
$address = $_POST['address'];
$email = $_POST['email'];
$description = $_POST['description'];
$phone = $_POST['phone'];
$mobile = $_POST['mobile'];
$mapLink = $_POST['maplink'];
// Image Details
$images = $_FILES['images'];
$imageName = $images['name'];
$imageSize = $images['size'];
$imageTmpName = $images['tmp_name'];
$imageType = $images['type'];
// Image Count
$imagecount = count($imageName);
// Check For Errors
$formErrors = [];
if(empty($name)) { $formErrors[] = 'Name Can Not Be Empty'; }
if(empty($address)) { $formErrors[] = 'Address Can Not Be Empty'; }
if(empty($description)) { $formErrors[] = 'Description Can Not Be Empty'; }
if(empty($field)) { $formErrors[] = 'Field Can Not Be Empty'; }
if(empty($email)) { $formErrors[] = 'Email Can Not Be Empty'; }
if(empty($phone)) { $formErrors[] = 'Phone Can Not Be Empty'; }
if(empty($mobile)) { $formErrors[] = 'Mobile Can Not Be Empty'; }
if(empty($mapLink)) { $formErrors[] = 'Map Link Can Not Be Empty'; }
// Loop Through Images
for($i = 0;$i < $imagecount;$i++) {
// Images Allowed Extension
$allowedExtension = ['jpg','jpeg','png'];
$imageExtensionExp = explode('.', $imageName[$i]);
$imageExtension = end($imageExtensionExp);
// Check Errors
if(empty($imageName[$i])) {
$formErrors[] = 'Image Can Not be Empty';
}
if(!empty($imageName[$i]) && !in_array($imageExtension, $allowedExtension)) {
$formErrors[] = 'This Extension Is Not Allowed';
}
if($imageSize[$i] > 5242880) { $formErrors[] = 'Size Can\'t be More 5 MB'; }
// Generate A Random Name
$imageNameStore = rand(0,10000000) . '_' . $imageName[$i];
move_uploaded_file($imageTmpName[$i], 'uploads\companies\\' . $imageNameStore);
}
// Print All Errors
if(!empty($formErrors)) {
echo '<div class="error-container">';
foreach ($formErrors as $error) {
echo '<h4>' . $error . '</h4>';
}
echo '</div>';
}
// Add To Database
if(empty($formErrors)) {
// Add Items To Database
/* $stmt = $conn->prepare("INSERT INTO
companies(Name, Field, Address, Email, Mobile, Phone, Description, Map,Images)
VALUES(?,?,?,?,?,?,?,?,?)");
$stmt->execute(array($name, $field,$address,$email,$mobile,$phone,$description,$mapLink, $imageNameStore));
*/
// Print Success Message
?>
<div class="container">
<div class="alert alert-success mt-5 text-center">Success, Company Added Successfully</div>
</div>
<?php
}
Initialize the following variable before the start of FOR Loop:
$imageNameStoreForDB='';
Add the following line code after your move_uploaded_file function before your for loop ends to concatenate all images' names:
$imageNameStoreForDB .= $imageNameStore." , ";
Replace the Query as below to use the new variable:
$stmt->execute(array($name, $field,$address,$email,$mobile,$phone,$description,$mapLink, $imageNameStoreForDB));
Note: It will save all images names in the DB separated by "," comma and if you wanna fetch the record then use explode function for images to separate each image.
Related
I tried a tutorial here in https://phppot.com/php/import-excel-file-into-mysql-database-using-php/ to import XLSX file to my database (using PHP)
But the problem is, if the column value started with leading zero, after import, I found out that the leading zero was removed.
How to prevent this?
By the way, my phpmyadmin table for that particular column to be imported is structured as Text column, not integer
I've tried adding '' to treat the file as string but shows no success
$conn = mysqli_connect("localhost","root","test","phpsamples");
require_once('vendor/php-excel-reader/excel_reader2.php');
require_once('vendor/SpreadsheetReader.php');
if (isset($_POST["import"]))
{
$allowedFileType = ['application/vnd.ms-excel','text/xls','text/xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
if(in_array($_FILES["file"]["type"],$allowedFileType)){
$targetPath = 'uploads/'.$_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $targetPath);
$Reader = new SpreadsheetReader($targetPath);
$sheetCount = count($Reader->sheets());
for($i=0;$i<$sheetCount;$i++)
{
$Reader->ChangeSheet($i);
foreach ($Reader as $Row)
{
$name = "";
if(isset($Row[0])) {
$name = mysqli_real_escape_string($conn,$Row[0]);
}
$description = "";
if(isset($Row[1])) {
$description = mysqli_real_escape_string($conn,$Row[1]);
}
if (!empty($name) || !empty($description)) {
$query = "insert into tbl_info(name,description) values('".$name."','".$description."')";
$result = mysqli_query($conn, $query);
if (! empty($result)) {
$type = "success";
$message = "Excel Data Imported into the Database";
} else {
$type = "error";
$message = "Problem in Importing Excel Data";
}
}
}
}
}
else
{
$type = "error";
$message = "Invalid File Type. Upload Excel File.";
}
}
Add a leading apostrophe (only if $description starts with a 0, of course), it will force Excel to read the cell as a text.
if ($description[0] === '0') {
$description = "'" . $description;
}
I have a weird problem. First of all, before I did form validation via PHP, I could insert and display data ( I have at least 30 fields). Then after I did validation and sanitizing, suddenly I cannot insert and display data. After I remove some fields and columns in the database, which left me a few, now I can insert data and display data, but if I add more than lets say 5 or 6 fields, I cannot insert data. Please tell me what's wrong?
<?php
echo var_dump($_POST);
echo var_dump($_FILES);
print_r($_SESSION);
error_reporting(E_ALL);
ini_set("display_errors",1);
//define variables and define to null.
$adtitleError = $dcrptnError = $rmError = $advertnameError = $apE = "";
$adtitle = $dcrptn = $rm = $advertname = $ap = "";
//Retrieve the field values from registration form.
$adtitle = !empty($_POST ['adtitle']) ? trim($_POST['adtitle']) : null;
$dcrptn = !empty($_POST ['dcrptn']) ? trim($_POST['dcrptn']) : null;
$rm = !empty($_POST ['rm']) ? trim($_POST['rm']) : null;
$advertname = !empty($_POST ['advertname']) ? trim($_POST['advertname']) : null;
$ap = !empty($_POST ['adphone']) ? trim($_POST['adphone']) : null;
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$formValid = true;
if(isset($_POST["submit"])){
//insert record
if($conn->connect_error)
{die("Connection failed:".$conn->connect_error);}
$id=isset($_POST['id'])?$_POST['id']:"";
//insert data
$statement = $conn->prepare("INSERT INTO useradvert(id,image1,adtitle,dcrptn,rm,advertname,adphone)VALUES (?,?,?,?,?,?,?)");
//bind param
$statement->bind_param("issssss",$id,$target_file,$adtitle,$dcrptn,$rm,$advertname,$ap);
$target_file=isset($_FILES['image'])?$_FILES['image']:"";
$adtitle=isset($_POST['adtitle'])?$_POST['adtitle']:"";
$dcrptn=isset($_POST['dcrptn'])?$_POST['dcrptn']:"";
$rm=isset($_POST['rm'])?$_POST['rm']:"";
$advertname=isset($_POST['advertname'])?$_POST['advertname']:"";
$ap=isset($_POST['adphone'])?$_POST['adphone']:"";
//bind the variables to be called at other places
if (empty($adtitle)){
$adtitleError = "Ad title is required. Select category to activate form.";
$formValid = false;
}else{
$adtitle = test_input($_POST["adtitle"]);
// check name only contains letters and whitespace
if (!preg_match('/^[a-zA-Z\s]{3,50}+$/', $adtitle)) {
$adtitleError = "Letters only & spaces,(min 3),e.g: a, A)";
$formValid = false;
}
}
if (empty($dcrptn)){
$dcrptnError = "Decsription is required. Select category to activate form.";
$formValid = false;
}
if (empty($rm)){
$rmError = "A value is required, e.g: 123000 or 12,300.00. Select category to activate form.";
$formValid = false;
}
else{
$rm = test_input($_POST["rm"]);
// check name only contains letters and whitespace
if (!preg_match('/^[0-9]+(?:\.[0-9]{1,13})?$/',$rm)) {
$rmError = "Invalid value.E.g: 123000.45. Select category to activate form.";
$formValid = false;
}
}
if (empty($advertname)){
$advertnameError = "Name is required. Select category to activate form.";
$formValid = false;
}
else{
$advertname = test_input($_POST["advertname"]);
// check name only contains letters and whitespace
if (!preg_match('/^[a-zA-Z\s]{3,50}+$/',$advertname)) {
$advertnameError = "Letters only & spaces,(min 3),(e.g: a, A). Select category to activate form.";
$formValid = false;
}
}
if (empty($ap)){
$apE = "Tel number is required. Select category to activate form.";
$formValid = false;
}
else{
$ap= test_input($_POST["adphone"]);
// check name only contains letters and whitespace
if (!preg_match('/^\d{9,11}+$/',$ap)) {
$apE = "Invalid tel no format.( E.g:0123456789). Select category to activate form.";
$formValid = false;
}
}
//image
$target_dir="uploads/";
$target_file=$target_dir.basename($_FILES["image1"]["name"]);
$uploadOk=1;
$imageFileType=pathinfo($target_file,PATHINFO_EXTENSION);
//script for targetfile -image
// Check if image or not
$check=getimagesize($_FILES["image1"]["tmp_name"]);
if($check!==false){
echo "File is an image - ".$check["mime"].".";
$uploadOk=1;
}else{
echo "File is not an image.";
$uploadOk=0;
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk=0;
}
// Check file size
if ($_FILES["image1"]["size"]>500000) {
echo "Sorry, your file is too large.";
$uploadOk=0;
}
// Allow certain file formats
if($imageFileType!="jpg"&&$imageFileType!="png"&&$imageFileType!="jpeg"
&&$imageFileType!="gif")
{
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk=0;
}
// 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{
if (move_uploaded_file($_FILES["image1"]["tmp_name"],$target_file)) {
echo "The file ".basename($_FILES["image1"]["name"])."has been uploaded.";
}else{
echo "Sorry, there was an error uploading your file.";
}
}
if ($formValid){
$statement->execute();
header('Location: userpppp.php');
exit;
}
}
?>
I have a simple form for submitting some data into the MySQL DB. On local machine works just fine, but inside a Wordpress page template doesn't work anymore, without getting me any error. The form is inside a page "sitename.com/upload" and i get redirected after submit to the same page (as shown in the link bar), but with 404 page content. I tried without get_header();and get_footer();tags because I thought it may conflict with some variables from wp, but I got the same result.
Here is the code:
<?php function renderForm($name, $price, $error)
{
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
***** LONG HTML FORM IS HERE *****
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$name = mysqli_real_escape_string($connection, htmlspecialchars($_POST['name']));
$price = mysqli_real_escape_string($connection, htmlspecialchars($_POST['price']));
$shortdesc = mysqli_real_escape_string($connection, htmlspecialchars($_POST['shortdesc']));
$longdesc = mysqli_real_escape_string($connection, htmlspecialchars($_POST['longdesc']));
$current_version = mysqli_real_escape_string($connection, htmlspecialchars($_POST['current-version']));
$content_rating = $_POST['contentrating'];
if(isset($_POST['category'])) {
$category = implode(",", $_POST['category']);
} else {
$category = "";
}
if(isset($_POST['platform'])) {
$platform = implode(",", $_POST['platform']);
} else {
$platform = "";
}
if(isset($_POST['devices'])) {
$devices = implode(",", $_POST['devices']);
} else {
$devices = "";
}
if(isset($_POST['gamemodes'])) {
$gamemodes = implode(",", $_POST['gamemodes']);
} else {
$gamemodes = "";
}
//FILE UPLOAD
$images = array();
if(isset($_FILES['files'])){
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name =$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
$desired_dir="uploads/images";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==true){
move_uploaded_file($file_tmp,"uploads/images/".$file_name);
}else{ //rename the file if another one exist
$file_name = time()."-".$file_name;
$new_dir="uploads/images/".$file_name;
rename($file_tmp,$new_dir) ;
}
$images[] = $file_name;
}else{
print_r($errors);
}
}
if(empty($error)){
$imglinks = implode(" | ", $images);
}
}
//FILE UPLOAD END
// check to make sure both fields are entered
if ($name == '' || $price == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($name, $price, $error);
}
else
{
$sql = "INSERT INTO vr_submitted_apps ". "(name, price, shortdesc, longdesc, crtvers, rating, category, platform, devices, gamemodes, images, dtime) ". "VALUES('$name','$price','$shortdesc','$longdesc','$current_version','$content_rating','$category','$platform','$devices','$gamemodes', '$imglinks', NOW())";
// save the data to the database
mysqli_query( $connection, $sql )
or die(mysql_error());
$itemId = mysqli_insert_id($connection);
setcookie("last-inserted-id", $itemId, time() + (86400 * 3), "/"); // 86400 = 1 day
// once saved, redirect back to the view page
header("Location: uploader.html");
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','');
}
Problem solved: Wordpress has something important internal reserved for "name" parameter.
I made simple upload system with using class.upload.php and it works great while adding new into database. But i have problem when i need to edit my entry. While editing entry i don't want to edit image but it sent it blank, also if i select image again it sent it blank too. Here is my code.
Can explain my problem.
<?php require_once("conn.php");
require_once ("class.upload.php");
$catid = $_POST['catid'];
$title = $_POST['title'];
$descc = $_POST['descc'];
$keyw = $_POST['keyw'];
$message = $_POST['message'];
$Image = $_FILES['Image'];
$randnum = rand();
$foo = new upload($Image);
$filee = './Image';
if ($foo->uploaded) {
$foo->image_resize = true;
$foo->file_new_name_body = $randnum;
$foo->image_x = 550;
$foo->image_y = 440;
$foo->process($filee);
if ($foo->processed) {
echo 'Image uploaded.';
echo $foo->file_dst_name;
$foo->clean();
} else {
echo 'Error. : ' . $foo->error;
}
}
$Image7 = $foo->file_dst_name;
if($_GET[pass] == 1)
{
if(!isset($_POST[catid]) || empty($_POST[catid])){
$hata = "Required area.";
}
if(!isset($_POST[title]) || empty($_POST[title])){
$hata = "Required area.";
}
if(!isset($_POST[descc]) || empty($_POST[descc])){
$hata = "Required area.";
}
if(!isset($_POST[keyw]) || empty($_POST[keyw])){
$hata = "Required area.";
}
if(!isset($_POST[message]) || empty($_POST[message])){
$hata = "Required area.";
}
if(!$hata){
mysql_query("UPDATE product SET
catid='$_POST[catid]',
title='$_POST[title]',
descc='$_POST[descc]',
keyw='$_POST[keyw]',
message='$_POST[message]',
Image='$_POST[Image]'
WHERE id='$_POST[id]'
");
$mesaj = "OK!";
}
}
$sonuc = mysql_query("select * from product WHERE id='$_GET[product]'");
$edit = mysql_fetch_array($sonuc);
$sonuc1 = mysql_query("select * from category");
$edit1 = mysql_fetch_array($sonuc1);
?>
try to change the update query
at Image='$_POST[Image]'
with Image='$Image7'
Fatih you can use a variable (i.e. $saved_image_name) instead of $POST[Image] at sql query. Set this variable to new name if uploaded else old value of db field.
...
...
$foo = new upload($Image);
$filee = './Image';
$saved_image_name = " Image "; // name of db field.
if ($foo->uploaded) {
$foo->image_resize = true;
$foo->file_new_name_body = $randnum;
$foo->image_x = 550;
$foo->image_y = 440;
$foo->process($filee);
if ($foo->processed) {
echo 'Image uploaded.';
echo $foo->file_dst_name;
// Note the quotes
$saved_image_name = " '$foo->file_dst_name' ";
$foo->clean();
} else {
echo 'Error. : ' . $foo->error;
}
}
// no use anymore $Image7 = $foo->file_dst_name;
...
...
if(!$hata){
mysql_query("UPDATE product SET
catid='$_POST[catid]',
title='$_POST[title]',
descc='$_POST[descc]',
keyw='$_POST[keyw]',
message='$_POST[message]',
Image= $saved_image_name // note the quotes
WHERE id='$_POST[id]'
");
...
...
Hello everyone i'm able to display my record by passing an id by query string to another page, but i'm not able to update it, the problem is that when i click on update nothing happen, it return me a blank page, and there is no printed error, can someone help me please?
<?php
require 'db2.php';
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
$dbc = mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die ('Could not connect to MySQL: ' . mysqli_connect_error() );
$q = mysqli_query($dbc,"SELECT * FROM movie WHERE MovieID = '$id' ");
while($r=mysqli_fetch_array($q))
{
$title = $r["Title"];
$tag = $r["Tag"];
$year = $r["YEAR"];
$cast = $r["Cast"];
$comment = $r["Comment"];
$IDBM = $r["IMDB"];
}
}
At this stage, the code display every information i need , the stage below is where i'm having a problem, i'm not able to get the id against and make the update when click on update button
elseif (!empty($_POST) and !empty($_GET['id']) ) {
// keep track post values
$cast = $_POST['cast'];
$title = $_POST['title'];
$comment =$_POST['comment'];
$year = $_POST['year'];
$tag = $_POST['tags'];
$IDBM = $_POST['idbm'];
$cast = htmlspecialchars($cast);
$title = htmlspecialchars($title);
$comment = htmlspecialchars($comment);
// validate input
$valid = true;
if (empty($cast)) {
$castError = 'Please enter Cast';
$valid = false;
}
if (empty($title)) {
$titleError = 'Please enter Title';
$valid = false;
}
if (empty($comment)) {
$commentError = 'Please enter Comment';
$valid = false;
}
if ($valid) {
$id = $_REQUEST['id'];
$valid_formats = array("jpg", "png", "gif", "bmp");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysqli_query($dbc,"UPDATE movie SET Title='$title',Year = '$year',Cast='$cast',Cover='$actual_image_name',Tag='$tag',Comment='$comment',IMDB ='$IDBM' WHERE MovieID=".$id);
header ("Location: index.php");
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
}
}
First thing, when you get a blank page, check your error log. Or if you're lazy, add this at the begining of your file to get error messages.
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
?>
It's hard to say, but just looking at your code quickly, I see a problem with your mixup of $_GET and $_POST. From what I gather, since your SELECTworks, you send data in $_GET, and your UPDATE block is only executed if you have $_POST data.
Change your html <form method="get"> for <form method="post">
And change your select block to check if( !empty($_POST['id'])) {