PHP result row as an object not set - php

I have this PHP code in which I try to edit a row in the database
$sql="SELECT * FROM `event` where `EId`='".$_GET['EId']."'";
$res=$conn->query($sql);
$numrows=mysqli_num_rows($res);
if ($numrows>0)
{
$obj = mysqli_fetch_object($res);
}
if ($_REQUEST["mode"]=="save")
{
if ($_FILES['image']['name']!="")
{
del_img("event/",$obj->Picture);
$Picture=post_img($_FILES['image']['name'], $_FILES['image']['tmp_name'],"event");
}
else
$Picture = $obj->Picture;
$sqlu="update event set Picture='".$Picture."' where EId='".$_POST['EId']."'";
$conn->query($sqlu);
header("refresh:1; url=event_view.php");
die();
}
function post_img($fileName,$tempFile,$targetFolder)
{
if ($fileName!="")
{
if(!(is_dir($targetFolder)))
mkdir($targetFolder);
$counter=0;
$NewFileName=$fileName;
if(file_exists($targetFolder."/".$NewFileName))
{
do
{
$counter=$counter+1;
$NewFileName=$counter."".$fileName;
}
while(file_exists($targetFolder."/".$NewFileName));
}
$NewFileName=str_replace(",","-",$NewFileName);
$NewFileName=str_replace(" ","_",$NewFileName);
copy($tempFile, $targetFolder."/".$NewFileName);
return $NewFileName;
}
}
function del_img($targetfolder,$filname)
{
if (file_exists($targetfolder.$filname))
{
unlink($targetfolder.$filname);
}
}
When this is executed without uploading a new image it removes the present image and saves the row without any image. When uploading a new image it does not delete the current image.
I checked with isset and it tells me that the variable $obj->Picture is not set. I used this code in an older version of PHP and it still works but I can't seem to get it to work in the current one.
I am quite sure that the problem lies with $obj but I can't seem figure out what it is.
The HTML is just a form with file upload input and I have already set up a connection to the database with $conn being a new mysqli. The reason I am taking the entire row is because I am editing other stuff too
It feels like I am committing a fundamental mistake? What am I missing?

I'd bet there is some Problem with the num_rows_function.
Try to structure the code differently or at least make sure you have obj defined and initialised when the part of your code where the object is required is reached.
Do something like this for xample:
if ($_REQUEST["mode"]=="save" && isset($obj))
{
if (($_FILES['image']['name']!=""))
{
del_img("event/",$obj->Picture);
$Picture=post_img($_FILES['image']['name'], $_FILES['image']['tmp_name'],"event");
}
else
$Picture = $obj->Picture;
$sqlu="update event set Picture='".$Picture."' where EId='".$_POST['EId']."'";
(...)

Well, here's how I would fix this up. Your whole logic was messed up; now we have only the two conditions we need: is a valid EId sent, and is a file attached?
Database API is updated to something a tiny bit more modern, queries are prepared and parameterized for security, and we are properly sanitizing user input before using it to name files.
<?php
$conn = new PDO("mysql:host=localhost;dbname=database", "user", "password");
$stmt = $conn->prepare("SELECT Picture FROM event WHERE EId = ?");
$result = $stmt->execute([$_POST["EId"]]);
if ($obj = $stmt->fetch(\PDO::FETCH_OBJ)) {
if (!empty($_FILES["image"])) {
del_img("event/", $obj->Picture);
$Picture = post_img($_FILES['image'], "event");
$stmt = $conn->prepare("UPDATE event SET Picture = ? WHERE EId = ?");
$result = $stmt->execute([$Picture, $_POST["EId"]]);
}
header("Location: event_view.php");
die();
}
function post_img($file, $targetFolder)
{
if (!(is_dir($targetFolder))) {
mkdir($targetFolder);
}
$fileName = $file["name"];
$tempFile = $file["tmp_name"];
$NewFileName = str_replace([",", " "], ["-", "_"], basename($fileName));
$counter = 0;
while(file_exists($targetFolder . "/" . $NewFileName)) {
$counter += 1;
$NewFileName = $counter . $fileName;
}
move_uploaded_file($tempFile, $targetFolder . "/" . $NewFileName);
return $NewFileName;
}
function del_img($targetfolder,$filname)
{
if (file_exists($targetfolder . $filname)) {
unlink($targetfolder.$filname);
}
}

Related

How to hard code a file's name in the database while saving an image to the server in php?

I'm working on getting images from the database, which I've been saving as an url from the server it's been getting saved on.
There's this upload image section on the form, which is saving the images on a server and its url is getting saved in the database.
Here's the code:
$fileName = "";
$target_dir="/home/web/newsletter/uploads/";
$target_file_cv = $target_dir . basename($_FILES['fileToUpload']['name']);
if(!empty($_FILES['fileToUpload']['name']))
{
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file_cv)) {
$fileName= $target_file_cv;
} else {
echo $twig->render("App/error.twig");
}
}
$conn = DB::databaseConnection();
$conn->beginTransaction();
$sqlInsert = "INSERT INTO dbo.form (photo) VALUES (:fileToUpload)";
$stmt = $conn->prepare($sqlInsert);
$stmt->bindParam(':fileToUpload', $fileName);
if ($stmt->execute()) {
$conn->commit();
return true;
} else {
return false;
}
?>
Here, I want to edit the file Name before it goes to the database. Like now it is saving as "/home/web/newsletter/uploads/pic.jpg" but I want it to be saved as "newsletter/uploads/pic.jpg".
I referred to a few questions here and got everything else working but just got stuck at hard coding the file's name here. Any help would be appreciated. TIA
$fileName = implode(array_slice(explode("/",$target_file_cv),3),"/");
Okay I got it:
Changed the code to:
$fileName = "";
$target_dir="/home/web/newsletter/uploads/";
$target_file_cv = $target_dir . basename($_FILES['fileToUpload']['name']);
if(!empty($_FILES['fileToUpload']['name']))
{
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file_cv)) {
$fileName= "newsletter/uploads/" . $_FILES['fileToUpload']['name'];
} else {
echo $twig->render("App/error.twig");
}
}
$conn = DB::databaseConnection();
$conn->beginTransaction();
$sqlInsert = "INSERT INTO dbo.form (photo) VALUES (:fileToUpload)";
$stmt = $conn->prepare($sqlInsert);
$stmt->bindParam(':fileToUpload', $fileName);
if ($stmt->execute()) {
$conn->commit();
return true;
} else {
return false;
}
?>

Data Not Going Into Database

I'm not sure why but in my image upload script none of my data is being entered into the database. This is the same script I've been using, but I recently added to if(isset)) statements to see if certain checkboxs were checked. The images are being uploaded to the server, but the database table remains empty. Any clues? I'm not getting any errors.
if(isset($_POST['submit'])) {
$count = count($_FILES['img_file']['name']);
for($i = 0; $i < $count; ++$i){
$img_name = $_POST['img_name'];
$img_name = str_replace(' ', '_', $img_name);
$img_album = $_POST['img_album'];
$img_album = str_replace(' ', '_', $img_album);
$img_photographer = $_POST['img_photographer'];
$img_location = $_POST['img_location'];
if(isset($_POST['horror'])) { $horror = "1"; } else { $horror = "0"; }
if(isset($_POST['occult'])) { $occult = "1"; } else { $occult = "0"; }
if(isset($_POST['goth'])) { $goth = "1"; } else { $goth = "0"; }
if(isset($_POST['industrial'])) { $industrial = "1"; } else { $industrial = "0"; }
if(isset($_POST['fashion'])) { $fashion = "1"; } else { $fashion = "0"; }
if(isset($_POST['fetish'])) { $fetish = "1"; } else { $fetish = "0"; }
if(isset($_POST['avante-garde'])) { $avanteGarde = "1"; } else { $avanteGarde = "0"; }
if(isset($_POST['cosplay'])) { $cosplay = "1"; } else { $cosplay = "0"; }
if(isset($_POST['nude'])) { $nude = "1"; } else { $nude = "0"; }
$file_name = $_FILES["img_file"]["name"][$i];
$file_ext = end((explode(".", $file_name)));
$target = $_SERVER['DOCUMENT_ROOT']."/gallery/";
$img_rename = $img_name . '_' . $i . '.' . $file_ext;
$target = $target . $img_rename;
if(move_uploaded_file($_FILES['img_file']['tmp_name'][$i], $target)){
mysqli_query($conn, "INSERT INTO gallery_img (img_name, img_album, img_photographer, img_location, horror, occult, goth, industrial, fashion, fetish, avante-garde, cosplay, nude, file_location) VALUES ('$img_name', '$img_album', '$img_photographer', '$img_location', '$horror', '$occult', '$goth', '$industrial', '$fashion', '$fetish', '$avanteGarde', '$cosplay', '$nude', '$img_rename')") ;
echo '<div class="alert alert-success margin-top">Image "'.$file_name.'" successfully uploaded and renamed to '.$img_rename.'.</div>';
}else {
echo '<div class="alert alert-danger margin-top">Sorry, there was a problem uploading your images.</div>';
}
}
}
You obviously weren't checking for errors in your query.
Notice the hyphen for one of your columns? It seems that others may have not scrolled over to the right (enough) to see it and to inform you about it.
avante-garde
MySQL is interpreting that as:
avante minus garde and thinking you wanted to do math. It should either be renamed using an underscore as you did for some of your other columns, or wrap it with ticks.
I.e.:
`avante-garde`
Btw, (and I'm not criticizing); that word is actually spelled "avant-garde", so make sure it is in fact that actual name. In either case, it would have failed you.
Note: I'm really hoping that that wasn't a typo on your part and that you are/were using an underscore after all.
Using error checking on the query in a conditional statement would have helped.
I.e. and assign a variable to it:
$query = mysqli_query($conn, "INSERT INTO gallery_img (...) VALUES (...)");
then
if($query){
echo "Success";
} else {
echo "Error: " . mysqli_error($conn);
}
http://php.net/manual/en/mysqli.error.php
Another thing. Make sure the column types are correct and of the right length. MySQL can fail silently if the lengths aren't long enough to accommodate the data.
Do use a prepared statement; your code is presently open to an SQL injection.
https://en.wikipedia.org/wiki/Prepared_statement
Footnotes:
You may want to look into using a ternary operator instead of some/all those if{...} else{...} statements, plus it's a lot shorter code.
http://php.net/manual/en/language.operators.comparison.php
Example from the manual:
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
Of course, you can replace empty with isset.
There is something worth noting and that could (also) prevent your query from executing, and that is its location for the query.
You have it inside the following condition. If your upload fails, so will the query.
if(move_uploaded_file($_FILES['img_file']['tmp_name'][$i], $target)){
mysqli_query($conn, "INSERT INTO gallery_img (...) VALUES (...)");
echo '<div class="...">Success...</div>';
}else {
echo '<div class="...">Error...</div>';
}
A few possible reasons why the upload failed, and could be one of any of the following:
File(s) is(are) too large
Permissions are not set for the folder to write to.
Typo(s) for the file(s) inputs(s)
Other
Reference for upload error codes/messages:
http://php.net/manual/en/features.file-upload.errors.php

PHP OOPs dynamic insert update delete data

I am not very much familiar with the OOPs in PHP. Just getting some simple lessons from the net i have tried to make a class to dynamically insert,delete update , upload data from the form to the database tables...
I am not sure if it is really object oriented.. Anybody could help me locate the errors or just make it better....
To use this class...Here are some rules or necessity:
1. The fields in the form should have same name as that of the fields in database..
2. The name of 'Submit' button should be same as that of the TABLE the form is going to insert data into.
3. No field in form(table) should have a same name as that of ANY TABLE in database.(except submit button)
To insert use function INSERTDB..
and
If there is an image upload use IMAG...
Here's the code:
db.class.php
<?php class database{
var $user,$host,$pass,$db;
public function connect($user,$host,$pass,$db){
$this->user=$user;
$this->host=$host;
$this->pass=$pass;
$this->db=$db;
$this->mysqli=new mysqli($this->user,$this->host,$this->pass,$this->db);
if ($this->mysqli->connect_error) {
die('Error : ('. $this->mysqli->connect_errno .') '. $this->mysqli->connect_error);
}
}
function imag($path,$tb){
define ("MAX_SIZE","400");
$errors=0;
$imag =$_FILES["image"]["name"];
$j=date("Y.m.d");
$image=$j.$imag;
$uploadedfile = $_FILES['image']['tmp_name'];
if ($image)
{
$filename = stripslashes($_FILES['image']['name']);
$extension =substr($image,-3);
echo "<br>".$extension."<br>".$image;
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg")
&& ($extension != "png") && ($extension != "gif"))
{
echo ' Unknown Image extension ';
$errors=1;
}
else
{
$size=filesize($_FILES['image']['tmp_name']);
if ($size > MAX_SIZE*1024)
{
echo "You have exceeded the size limit";
$errors=1;
}
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['image']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['image']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
list($width,$height)=getimagesize($uploadedfile);
$newwidth=800;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
$newwidth1=150;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,
$width,$height);
imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,
$width,$height);
$filename = "../images/".$path."/". $image;
$filename1 = "../images/".$path."/s/". $image;
imagejpeg($tmp,$filename,100);
imagejpeg($tmp1,$filename1,100);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}
}
//If no errors registred, print the success message
if(!$errors)
{
// mysql_query("update SQL statement ");
$this->insertdb($tb);
echo "Image Uploaded Successfully!";
}
}
function insert($tb,$field,$value){
$in= mysqli_query($this->mysqli,"INSERT INTO $tb ($field) values ($value)");
if(!$in){
die("Insert Query Failed" .mysqli_error($this->mysqli) );
}
}
function insertdb($tb){
echo $tb;
$f="";
$v="";
foreach($_POST as $key=>$value){
echo $key . " = " . $value. "<br>";
}
foreach($_POST as $key=>$value){
if(($key!==$tb)&&($key!=="image_y")){
$f=$f.mysqli_real_escape_string($this->mysqli,$key).",";
$v=$v."'".mysqli_real_escape_string($this->mysqli,$value)."',";
echo "<hr> there is no image<hr>";
}
if($key=="image_y"){
$f=$f."image,";
$v=$v."'".$_FILES['image']['name']."',";
echo "<hr> there is an image<hr>";
}
}
$f1=rtrim($f,",");
$v1=rtrim($v,",");
echo $f1 ."<br>".$v1;
$this->insert($tb,$f1,$v1);
}
function del($tb,$field,$value){
$d= mysqli_query($this->mysqli,"DELETE FROM $tb where $field = '$value' ");
if(!$d){
die("Delete Query Failed" );
}
}
function up($tb,$field,$value,$o_field,$o_value){
$u= mysqli_query($this->mysqli,"UPDATE $tb SET $field= '$value' where $o_field= '$o_value' ");
if(!$u){
die("Update Query Failed".mysqli_error($this->mysqli) );
}
}
function show($tb,$field,$value,$condition,$ans){
$s= mysqli_query($this->mysqli,"Select * from $tb where $field $condition '$value' ");
$s2=mysqli_fetch_assoc($s);
echo $s2[$ans];
if(!$s){
die("Select Query Failed".mysqli_error($this->mysqli) );
}
}
}
?>
process.php
<?php
include"../includes/db.class.php";
$o=new database();
$o->connect("localhost","root","","saycheese");
if(isset($_POST['category'])){
$tb="category";
$o->insertdb($tb);
}
if(isset($_POST['magzine'])){
$tb="magzine";
$o->insertdb($tb);
}
if(isset($_POST['writer'])){
$tb="writer";
$folder="wr";
$o->imag($folder,$tb);
}
if(isset($_POST['images'])){
$tb="images";
$folder="mag";
$o->imag($folder,$tb);
}
?>
`
Foreword
You're on the right track, but you're only half way there. you have to format your data before you can insert anything to the database.
This means, you must map your $_POST values to the the arrays $field and $value, the former being the database columns and the latter being the data you wish to insert.
The insert() method takes 3 inputs. $tb $field and $value
$tb is easy its a string. $field and $value are most likely arrays, depending on your table structure. even if your table contains a single column, it would still be best to use arrays. there are two syntax for working with arrays. the first being [] (only supported on newer php installations), and the older but more supported 'array()' method.
Addressing the problem
In your code, you are incorrectly using the insertdb method which is only for tables that have the same column name as post fields. otherwise, this method will not work. instead, you should focus on using the insert() method, and correctly mapping the values.
say you have a table structure like so
TABLE user_info
user_name (VARCHAR(25)
pass_word VARCHAR(255)
user_id PRIMARY, AI INT(11)
As you can see, for a successful insert, you must provide values for user_name and pass_word while user_id is your primary index and will autoincrement.
Now, say you have a post like so
$username = $_POST['user'];
$password = $_POST['pass'];
Knowing this, we have to somehow map this information to our database.
PRESTO! We can map them like so
$tb = 'user_info';
$field = ['user_name','pass_word'];
$value = [$username,$password];
now, we have all the prerequisites for inserting with our db class.
$o->insert($tb,$field,$value);
It's very messy at the moment. You need to abstract more to really make this OO. I would stick the connection stuff in another file and then turn this into a callable object.
What do I mean by this? Well, you can return the whole file as an object by returning $this in every function. For example, let's look at a where function.
//Db would hold your connection details and connect to the DB
class Query_Builder extends Db {
//Declare your instance variables here, we are just doing where for the purposes of this
protected $_where;
public function where($column, $field)
{
//Encaps in single quotes
$encapsField = '\'' . $field . '\'';
$newWhere = str_replace('?', $encapsField, $column);
$this->_where = 'WHERE ' . $newWhere;
return $this;
}
Note: You don't need public on the function, as it is declared implicitly anyway, but it is considered good practice to always declare functions explicitly.
This function will return $this->_where set to something like 'WHERE id = '1';'. Using this, you can build whole queries by repeating this process. This is a lot more object orientated and will give you good grounding to expand your class to incorporate these design patterns.

How to properly send HTML Link tag to database as entry?

I have a a multifile upload script that converts uploaded files to zip. It works flawlessly.Only problem that I have is uploading data to the database. I tried everything and the databse still doesn't get any of the data. Two things: 1: I want to send the file path within a html link tag to be displayed as a link on the page I will be loading to and 2: the rest of the data as is submitted on the form. Any help would be great. Here is the code:
<?php
set_time_limit(0); // Make sure php doesnt end script after 30 seconds
ini_set('memory_limit','128M');
ini_set( 'upload_max_filesize', '100M' );
ini_set( 'post_max_size', '100M' );
$project = $_POST['project'];
$assignto = $_POST['assignto'];
$asdate = $_POST['asdate'];
$chdate = $_POST['chdate'];
$ddate = $_POST['ddate'];
$timestamp = time();
if (isset ($_POST['submit']))
{
$filesArray= $_FILES["files"];
for ($num=0; $num<count($filesArray["name"]);$num++)
{
$fileName = $filesArray["name"][$num];
$tempName= $filesArray["tmp_name"][$num];
move_uploaded_file($tempName,"tmp/".$fileName);
}
$archiveName= $timestamp.".zip";
$filesArrayNames= $_FILES["files"]["name"];
$zipsDir= scandir ("uploads/");
$error = false;
foreach($zipsDir as $zipDirfile)
{
if($zipDirfile == $archiveName)
{
$error= true ;
break;
}
}
if ($error== false)
{
$tmpDir = scandir ("tmp/");
$zip = new ZipArchive;
$zip->open("uploads/".$archiveName, ZipArchive::CREATE);
for ($num =0; $num<count($filesArray["name"]);$num++)
{
$fileName = $filesArray["name"][$num];
foreach($tmpDir as $tmpDirfile)
{
if($tmpDirfile == $fileName)
{
$zip->addFile("tmp/".$fileName);
echo " Adding: ".$fileName."<br/>";
}
}
}
$zip->close();
for ($num=0; $num<count($filesArray["name"]);$num++)
{
$fileName = $filesArray["name"][$num];
foreach($tmpDir as $tmpDirFile)
{
if($tmpDirfile == $fileName)
{
unlink("tmp/".$fileName);
}
}
}
}
else
{
echo "Name already exists";
}
}
$filepath= "<a href='"'http://www.amadastage.com/uploads/ '"'.$archiveName.'"'>Files</a>';
mysql_connect("webcontrolcenter.com","dude","usa") or die ('Error:' .mysql_error());
//database connection
mysql_select_db("mediamanagement");
mysqli_query("INSERT INTO demo (name, id_continent, lastvisit,cdate,ddate,email)
VALUES ('project', 'assignto','asdate','chdate','ddate')");
Like nvanesch said use mysqli for creating connection.
Also you have to put the variable values into quotes:
Try like this:
$sql = "INSERT INTO demo (`name`, `id_continent`, `lastvisit`, `cdate`, `ddate`, `email`)
VALUES ('".$project."', '".$assignto."','".$asdate."','".$chdate."','".$ddate."')";
mysqli_query($sql);
You are connecting with mysql_ and next querying with mysqli_
You should either have all with mysql_ (not recommended as mysql_ is deprecated) or use mysqli_ everywhere.

PHP: Duplicate/Blank values when Inserting image names into the DB

I am currently storing in MySQL database image names for easier way to retrieve the actual images. I am having problems with the php code I created that stores the names. Duplicate and blank insertions are being made into the DB without my permission.
Is there a way to avoid this issue of duplicate or blank values being inserted when the page refreshed?
<?
$images = explode(',', $_GET['i']);
$path = Configuration::getUploadUrlPath('medium', 'target');
if (is_array($images)) {
try {
$objDb = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$objDb->exec('SET CHARACTER SET utf8');
} catch (PDOException $e) {
echo 'There was a problem';
}
$sql = "INSERT INTO `urlImage` (`image_name`) VALUES ";
foreach ($images as $image) {
$value[] = "('" . $image . "')"; // collect imagenames
}
$sql .= implode(',', $value) . ";"; //build query
$objDb->query($sql);
}
?>
First, you should be checking for blank names in your foreach statement, as such:
foreach ($images as $image) {
if($image!='') {
$value[] = "('".$image."')"; // collect imagenames
}
}
Secondly, you should look into header("Location: ..."); to prevent users from refreshing the page.
Thirdly, you could also set a session variable or cookie to prevent a user from uploading the same image twice.
Lastly, if the image names are unique, you can set a UNIQUE index on the image name. Then use INSERT IGNORE and that will remove all of your duplicates.
I reformatted things into what I think should be slightly more readable and more easily separate what's going on in the code. I also updated your queries to show how you can properly "sanitize" your input.
I still think the process by which you're going about sending the data to the server is wrong, but hopefully this code helps you out a little bit. I'd also do this more object orientedly.. but I feel that leaves the scope of your question just a little bit =P. It's kind of like everyone else is saying though, the logic for your code was only off just slightly.
As for the duplication thing, look into checking if the file already exists before adding it to the database.
<?php
$_GET['i'] = 'file1.png, file2.png, file3.png'; // This is just for testing ;].
$images = retrieve_images();
insert_images_into_database($images);
function retrieve_images()
{
//As someone else pointed out, you do not want to use GET for this and instead want to use POST. But my goal here is to clean up your code
//and make it work :].
$images = explode(',', $_GET['i']);
return $images;
}
function insert_images_into_database($images)
{
if(!$images)//There were no images to return
return false;
$pdo = get_database_connection();
foreach($images as $image)
{
$sql = "INSERT INTO `urlImage` (`image_name`) VALUES ( ? )";
$prepared = $pdo->prepare($sql);
$prepared->execute(array($image));
}
}
function get_database_connection()
{
$host = 'localhost';
$db = 'test';
$user = 'root';
$pass = '';
try {
$pdo = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$pdo->exec('SET CHARACTER SET utf8');
} catch(PDOException $e) {
die('There was a problem');
}
return $pdo;
}
The easiest way to avoid duplicates upon refresh is to re-direct the page after the POST, so just doing header("Location: {$_SERVER['PATH_INFO']}"); should solve that for you.
To avoid empty entries try is_array($images) && count($images)
You probably should change the following line:
if(is_array($images)){
to this:
if(!empty($images) && is_array($images)){
explode() returns an empty array even if no "i" parameter is provided
Try setting a session variable and tell it to exit or redirect when session variable is not set.
For example
if (!isset($_SESSION['session_name']))
{
exit();
}

Categories