I try to understand how to use multiple uploads in PDO.
So I have my post.php:
$database = new Database();
$db = $database->getConnection();
$media = new Media($db);
if($_POST){
$image = !empty($_FILES["image"]["name"]) ? sha1_file($_FILES['image']['tmp_name']) . "-" . time() . "-" . basename($_FILES["image"]["name"]) : "";
$media->image = $image;
if ($media->create()) {
echo $media->uploadPhoto();
$_POST=array();
}
}
<input name="image[]" type="file" />
And my media.php with pdo query and some upload validations:
public $image;
public $created;
public function create(){
//write query
$query = "INSERT INTO " . $this->table_name . "
SET image=:image,
created=:created";
$stmt = $this->conn->prepare($query);
$this->image=htmlspecialchars(strip_tags($this->image));
$stmt->bindParam(":image", $this->image);
if($stmt->execute()){
return true;
}
print_r($stmt->errorInfo());
return false;
}
function uploadPhoto(){
$result_message="";
if(!empty($_FILES["image"]["tmp_name"])){
$target_directory = "../uploads/";
$target_file = $target_directory . $this->image;
$file_type = pathinfo($target_file, PATHINFO_EXTENSION);
$file_upload_error_messages="";
$check = getimagesize($_FILES["image"]["tmp_name"]);
if($check!==false){
}else{
$file_upload_error_messages.="<div></div>";
}
$allowed_file_types=array("jpg", "JPG", "jpeg", "JPEG", "png", "PNG", "gif", "GIF");
if(!in_array($file_type, $allowed_file_types)){
$file_upload_error_messages.="<div></div>";
}
if(file_exists($target_file)){
}
if($_FILES['image']['size'] > (10485760)){
$file_upload_error_messages.="<div></div>";
}
if(!is_dir($target_directory)){
mkdir($target_directory, 0777, true);
}
if(empty($file_upload_error_messages)){
if(move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)){
}else{
$result_message.="<div></div>";
}
}
else{
$result_message.="{$file_upload_error_messages}";
}
}
return $result_message;
}
So I need to store the values in different mysql records and upload them all to the server.
What is the best way to do this and where to place the foreach?
I struggle with the right place of the foreach ...
$x=0;
foreach ( $_FILES['image']['name'] AS $key => $value ){
// ...
$x++;
}
so if this is your foreach loop and you want to insert different records for each uploaded file then use mysqli_multi_query
$x=0;
$query = "";
foreach ( $_FILES['image']['name'] AS $key => $value ){
$query .= 'insert into tableName (col1,col2,col3,image)VALUES("a","b","c","'.$value.'");';
$x++;
}
$query = rtrim($query,";");
mysqli_multi_query($connectionObj,$query);
Your query will look somthing like this
insert into tableName (col1,col2,col3,image)VALUES("a","b","c","a.jpg");
insert into tableName (col1,col2,col3,image)VALUES("a","b","c","b.jpg");
Related
I am using the below code for importing the excel sheet and inserting the data into the database and it's working. There is no issue with it.
Now, I have a column name called content. I am uploading the content in it. so below is the example of the content.
Now after importing the data I am getting the output like. so it's removing the strong part and spacing etc.
I am using the rich text editor and I am displaying the data in it.
function listImport($pdo){
if($_FILES["emplist"]["name"] != '')
{
$allowed_extension = array('csv');
$file_array = explode(".", $_FILES["emplist"]["name"]);
$file_extension = end($file_array);
if(in_array($file_extension, $allowed_extension))
{
$file_name = time() . '.' . $file_extension;
move_uploaded_file($_FILES['emplist']['tmp_name'], $file_name);
$file_type = \PhpOffice\PhpSpreadsheet\IOFactory::identify($file_name);
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($file_type);
$spreadsheet = $reader->load($file_name);
unlink($file_name);
$data = $spreadsheet->getActiveSheet()->toArray();
$isheader = 0;
foreach($data as $row)
{
if($isheader > 0) {
$insert_data = array(
':name' => $row[0],
':email' => $row[1],
':content' => $row[2]
);
$query = "INSERT INTO `employee`(`name`, `email`, `content`) VALUES (:name,:email,:content)";
$statement = $pdo->prepare($query);
$statement->execute($insert_data);
}
else {
$isheader = 1;
}
} // foreach
$message = '<div class="alert alert-success">Data Imported Successfully</div>';
} //in_array
else
{
$message = '<div class="alert alert-danger">Only .csv file allowed</div>';
}
}
else
{
$message = '<div class="alert alert-danger">Please Select File</div>';
}
echo $message;
}
I am trying to save a picture into my database along with the path file. But what it does now is incorrect. It only saves the image into the database and not the entire image path. What's wrong?
I do the exact same thing with this code in another project and can't wrap my head around the problem here.
$userPic = '';
$date_time = date('Y-m-d_H-i-s');
if(!empty($userLoggedIn)) {
if (isset($_FILES['fileToUpload'])) {
$errors = array();
$file_name = $_FILES['fileToUpload']['name'];
$file_size = $_FILES['fileToUpload']['size'];
$width = 1500;
$height = 1500;
$file_tmp = $_FILES['fileToUpload']['tmp_name'];
$file_type = $_FILES['fileToUpload']['type'];
$tmp = explode('.', $_FILES['fileToUpload']['name']);
$file_ext = strtolower (end ($tmp));
$extensions = array("jpeg", "jpg", "png", "gif");
if(in_array($file_ext, $extensions) === false) {
$errors[] = "extension not allowed. Please choose a JPEG or PNG file.";
}
if ($file_size > 8097152) {
$errors[] = 'File size must be 2 MB';
}
if ($width > 1500 || $height > 1500) {
echo"File is to large";
}
if(!$errors) {
$userPic = md5($_FILES["fileToUpload"]["name"]) . $date_time . " " . $file_name;
move_uploaded_file($file_tmp, "assets/images/profile_pics/" . $userPic);
$stmt = $con->prepare("UPDATE users SET profile_pic = ? WHERE username = ?");
$stmt->bind_param('ss', $userPic, $username);
$stmt->execute();
$stmt->close();
}
}
}
else {
echo "Invalid Username";
}
You can assign another variable that contains both the path and the variable for the image you used, and then use that variable in your query:
$file_path = "assets/images/profile_pics/".$userPic;
Your code:
if(!$errors) {
$userPic = md5($_FILES["fileToUpload"]["name"]) . $date_time . " " . $file_name;
move_uploaded_file($file_tmp,"assets/images/profile_pics/" . $userPic);
$imag_path = "assets/images/profile_pics/" . $userPic;
$stmt = $con->prepare("UPDATE users SET profile_pic = ? WHERE username = ?");
$stmt->bind_param('ss', $imag_path, $username);
$stmt->execute();
$stmt->close();
}
Try this:
You save only the new image name, not path.
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();
}
I have an app that I can upload and delete photos from. Right now I am either able to upload a photo, or I'm able to delete it. But I can't do both for some reason and here's what I mean:
In the code below, in the Photograph class, the variable $db_fields is an array of the columns in the photograph database. If I leave the id field out of the $db_fields array, I am able to upload a photo. But I cannot delete a photo. If I include the id field, I am able to then delete a photo, but now I can't upload one.
What do I need to do here? And if you need to see anything else please let me know.
Thanks,
CM
photograph.php
<?php
require_once(LIB_PATH . DS . 'database.php');
class Photograph extends DatabaseObject {
protected static $table_name = "photographs";
protected static $db_fields = array('id','filename', 'type', 'size', 'caption');
public $id;
public $filename;
public $type;
public $size;
public $caption;
private $temp_path;
protected $upload_dir = "images";
public $errors = array();
protected $upload_errors = array(
UPLOAD_ERR_OK => "No errors.",
UPLOAD_ERR_INI_SIZE => "Larger than upload_max_filesize.",
UPLOAD_ERR_FORM_SIZE => "Larger than form MAX_FILE_SIZE.",
UPLOAD_ERR_PARTIAL => "Partial upload.",
UPLOAD_ERR_NO_FILE => "No file.",
UPLOAD_ERR_NO_TMP_DIR => "No temporary directory.",
UPLOAD_ERR_CANT_WRITE => "Can't write to disk.",
UPLOAD_ERR_EXTENSION => "File upload stopped by extension."
);
public function attach_file($file) {
if (!$file || empty($file) || !is_array($file)) {
$this->errors[] = "No file was uploaded.";
return false;
} elseif ($file['error'] != 0) {
$this->errors[] = $this->upload_errors[$file['error']];
return false;
} else {
$this->temp_path = $file['tmp_name'];
$this->filename = basename($file['name']);
$this->type = $file['type'];
$this->size = $file['size'];
return true;
}
}
public function save() {
if (isset($this->id)) {
$this->update();
} else {
if (!empty($this->errors)) {
return false;
}
if (strlen($this->caption) > 255) {
$this->errors[] = "The caption can only be 255 characters long.";
return false;
}
if (empty($this->filename) || empty($this->temp_path)) {
$this->errors[] = "The file location was not available.";
return false;
}
$target_path = SITE_ROOT . DS . 'public' . DS . $this->upload_dir . DS . $this->filename;
if (file_exists($target_path)) {
$this->errors[] = "The file {$this->filename} already exists.";
return false;
}
if (move_uploaded_file($this->temp_path, $target_path)) {
if ($this->create()) {
unset($this->temp_path);
return true;
}
} else {
$this->errors[] = "The file upload failed, possibly due to incorrect permissions on the upload folder.";
return false;
}
}
}
public function destroy() {
if ($this->delete()) {
$target_path = SITE_ROOT . DS . 'public' . DS . $this->image_path();
return unlink($target_path) ? true : false;
} else {
return false;
}
}
public function image_path() {
return $this->upload_dir . DS . $this->filename;
}
public function size_as_text() {
if ($this->size < 1024) {
return "{$this->size} bytes";
} elseif ($this->size < 1048576) {
$size_kb = round($this->size / 1024);
return "{$size_kb} KB";
} else {
$size_mb = round($this->size / 1048576, 1);
return "{$size_mb} MB";
}
}
public function comments() {
return Comment::find_comments_on($this->id);
}
public static function count_all() {
global $database;
$sql = "SELECT COUNT(*) FROM ".self::$table_name;
$result_set = $database->query($sql);
$row = $database->fetch_array($result_set);
return array_shift($row);
}
}
?>
database_object.php
require_once(LIB_PATH . DS . 'database.php');
class DatabaseObject {
private static $table_name;
public static function find_all() {
global $database;
$query = "SELECT * FROM ".static::$table_name;
return static::find_by_sql($query);
}
public static function find_by_id($id=0) {
global $database;
$query = "SELECT * FROM " . static::$table_name . " WHERE id =".$database->escape_value($id)." LIMIT 1";
$result_array = static::find_by_sql($query);
return !empty($result_array) ? array_shift($result_array) : false;
}
public static function find_by_sql($sql = "") {
global $database;
$result_set = $database->query($sql);
$object_array = array();
while ($row = $database->fetch_array($result_set)) {
$object_array[] = static::instantiate($row);
}
return $object_array;
}
private static function instantiate($record) {
$object = new static();
foreach ($record as $attribute => $value) {
if ($object->has_attribute($attribute)) {
$object->$attribute = $value;
}
}
return $object;
}
private function has_attribute($attribute) {
$object_vars = $this->attributes();
return array_key_exists($attribute, $object_vars);
}
protected function attributes() {
$attributes = array();
foreach (static::$db_fields as $field) {
if (property_exists($this, $field)) {
$attributes[$field] = $this->$field;
}
}
return $attributes;
}
protected function sanitized_attributes() {
global $database;
$clean_attributes = array();
foreach ($this->attributes() as $key => $value) {
$clean_attributes[$key] = $database->escape_value($value);
}
return $clean_attributes;
}
public function save() {
return isset($this->id) ? $this->update() : $this->create();
}
public function create() {
global $database;
$attributes = $this->attributes();
$sql = "INSERT INTO ".static::$table_name." (";
$sql .= join(", ", array_keys($attributes));
$sql .= ") VALUES ('";
$sql .= join("', '", array_values($attributes));
$sql .= "')";
if($database->query($sql)) {
$this->id = $database->insert_id();
return true;
} else {
return false;
}
}
public function update() {
global $database;
$attributes = $this->sanitized_attributes();
$attribute_pairs = array();
foreach ($attributes as $key => $value) {
$attribute_pairs[] = "{$key}='{$value}'";
}
$sql = "UPDATE " . static::$table_name . " SET ";
$sql .= join(", ", $attribute_pairs);
$sql .= " WHERE id=" . $database->escape_value($this->id);
$database->query($sql);
return ($database->affected_rows() == 1) ? true : false;
}
public function delete() {
global $database;
$sql = "DELETE FROM " . static::$table_name;
$sql .= " WHERE id=" . $database->escape_value($this->id);
$sql .= " LIMIT 1";
$database->query($sql);
return ($database->affected_rows() == 1) ? true : false;
}
}
?>
photo_upload.php
<?php
require_once('../../includes/initialize.php');
if (!$session->is_logged_in()) {
redirect_to("login.php");
}
?>
<?php
$max_file_size = 10485760; // expressed in bytes
// 10240 = 10 KB
// 102400 = 100 KB
// 1048576 = 1 MB
// 10485760 = 10 MB
//2e+6
$message="";
if (isset($_POST['submit'])) {
$photo = new Photograph();
$photo->caption = $_POST['caption'];
$photo->attach_file($_FILES['file_upload']);
if ($photo->save()) {
// Success
$session->message("Photograph uploaded successfully.");
redirect_to('list_photos.php');
} else {
// Failure
$message = join("<br />", $photo->errors);
}
}
?>
<?php include_layout_template('admin_header.php'); ?>
<h2>Photo Upload</h2>
<?php echo output_message($message); ?>
<form action="photo_upload.php" enctype="multipart/form-data" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size; ?>" />
<p><input type="file" name="file_upload" /></p>
<p style="font-color:#000;">Caption: <input type="text" name="caption" value="" /></p>
<input type="submit" name="submit" value="Upload" />
</form>
<?php include_layout_template('admin_footer.php'); ?>
from 'database_object.php'
public function create() {
global $database;
$attributes = $this->attributes();
$sql = "INSERT INTO ".static::$table_name." (";
$sql .= join(", ", array_keys($attributes));
$sql .= ") VALUES ('";
$sql .= join("', '", array_values($attributes));
$sql .= "')";
if($database->query($sql)) {
$this->id = $database->insert_id();
return true;
} else {
return false;
}
}
A summary of the temporary solution, so you can file this question completed.
In the method of create, you would grab all attributes (fields) using $attributes = $this->attributes();, then use the array keys and values to generate the SQL statement.
This would also include the id field.
The problem then occurred from trying to do an INSERT operation and including the id field (which appears to be an auto_increment unique indexed field). This was causing a big problem on create.
A temporary solution, was to drop that field from the $attributes you use to build the query, using unset($attributes['id']); after $attributes = $this->attributes(); would accomplish this, but its not pretty and can be developed better later at your leisure.
I hope I helped, and merry coding ;)
Hello everyone i'm taking a value from a URL by get and pass it into an update statement, when i put WHERE ID= 1 , it work fine but when i put the ID=$id, the code work but there is no update, the record remain the same, can some help me to resolve this problem 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"];
}
}
if (!empty($_POST) ) {
if ( !empty($_GET['id'])) {
$id = $_REQUEST['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) {
$path = "uploads/";
$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;
}
}
}
echo"error";
}
How about this:
$id = strip_tags(intval($_GET['id']));
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}';");
To verify if $id have same value:
echo $id;
It sounds like maybe your MovieID isn't defined as an integer but we can't tell for sure because you haven't told us the error message that mysqli_query is throwing.
You need to be checking the error message created by mysqli_query to know. See http://www.php.net/manual/en/mysqli.error.php
try this
$id = $_GET['id']; // taking the value from URL
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); // the sql statement of the query
and best you protect the get by using intval() to prevent injections
$id = intval($_GET['id']); // taking the value from URL