Loop / insertion image - php

I'm trying to insert images into mysql. The script currently insert one image.
I have put that in the form: name="uploadImage[]" (to make an array).
I understand something is wrong in my code.
I appreciate any help and thank you in advance! :)
<?php
if (isset($_POST['btnSubmit']))
{
$uploaded_images = array();
foreach($_FILES['uploadImage']['name'] as $key=>$val)
{
$upload_dir = "uploads/";
$upload_file = $upload_dir . $_FILES['uploadImage']['name'][$key];
$filename = $_FILES['uploadImage']['name'][$key];
if (move_uploaded_file($_FILES['uploadImage']['tmp_name'][$key], $upload_file))
{
$uploaded_images[] = $upload_file;
$img0 = $filename[0];
$img1 = $filename[1];
$img2 = $filename[2];
$img3 = $filename[3];
$img4 = $filename[4];
echo $filename."<br />";
$created = date("Y:m:d h:i:s");
global $bdd;
$stmt= $bdd->prepare("INSERT INTO annonces_pro(id,ref_member,titre,intro,texte,activite,country,favorite,valid,is_ribbon,date_inserted)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
$inserted = $stmt->execute(array('',$ref_member,$titre,$intro,$texte,$activite,$country,'','',$is_ribbon,$created));
$lastId = $bdd->lastInsertId();
global $bdd;
$stmt2 = $bdd->prepare("INSERT INTO annonces_pro_images(id,ref_member,image,is_cover,weight_image,date_published)
VALUES(?,?,?,?,?,?)");
$inserted2 =$stmt2->execute(array($lastId,$ref_member,$filename,'','',$created));
if ($inserted)
{
?>
<div class="alert alert-success" role="alert">
ok<br />
Insert another ad<br />
Back to homepage<br />
</div>
<?php
} else
{
?>
<div class="alert alert-danger" role="alert">Database error</div>
<?php
}
}
}
}
?>

removed global $bdd; as we are already in global scope, we don't need them
moved prepare statements out of the loop, as they only need to be prepared once.
added is_uploaded_file check to check if it's actually an uploaded file.
removed $img..=$filename[..]
changed foreach($_FILES['uploadImage']['name'] as $key => $file to foreach($_FILES['uploadImage'] as $file
for a better and secure version
<?php
if (isset($_POST['btnSubmit']))
{
$stmt= $bdd->prepare("INSERT INTO annonces_pro(id,ref_member,titre,intro,texte,activite,country,favorite,valid,is_ribbon,date_inserted) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
$stmt2 = $bdd->prepare("INSERT INTO annonces_pro_images(id,ref_member,image,is_cover,weight_image,date_published)
VALUES(?,?,?,?,?,?)");
$uploaded_images = array();
foreach($_FILES['uploadImage'] as $image)
{
$filename = $image['name'];
if (!is_uploaded_file($filename)) continue;
$upload_dir = "uploads/";
$upload_file = $upload_dir . $image['name'];
if (move_uploaded_file($image['tmp_name'], $upload_file))
{
$uploaded_images[] = $upload_file;
echo $filename."<br />";
$created = date("Y:m:d h:i:s");
$inserted = $stmt->execute(array('',$ref_member,$titre,$intro,$texte,$activite,$country,'','',$is_ribbon,$created));
$lastId = $bdd->lastInsertId();
$inserted2 =$stmt2->execute(array($lastId,$ref_member,$filename,'','',$created));
if ($inserted)
{
?>
<div class="alert alert-success" role="alert">
ok<br />
Insert another ad<br />
Back to homepage<br />
</div>
<?php
} else
{
?>
<div class="alert alert-danger" role="alert">Database error</div>
<?php
}
}
}
}
?>

Related

How to INSERT an array of uploaded filenames into a table and later display them?

I am working on a project where each item could have multiple images, I created a form that would accept the images and store them into an array. The problem is whenever I try inserting the images into a table row in the database it displays an error:
"Array to string conversion"
How can I fix this? And also how do I fetch each images on another page from the same database table. Below is my code.
-Form code
<form method="post" enctype="multipart/form-data" >
<input required type="text" name="name">
<input required type="text" name="location">
<input required type="text" name="status">
<select required name="category">
<option>Category</option>
<option value="construct">Construction</option>
<option value="promgt">Project Development</option>
<option value="archdesign">Architectural Designs</option>
</select>
<textarea required class="form-control" name="descrip" rows="5"></textarea>
<input style="text-align:left" type="file" name="imgs[]" multiple>
<button type="submit" name="submit" formaction="addaction.php">Add Project</button>
</form>
-Addaction.php code
<?php
$db=mysqli_connect("localhost","root","dbpassword","dbname");
if(!empty($_FILES['imgs']['name'][0])){
$imgs = $_FILES['imgs'];
$uploaded = array();
$failed = array();
$allowed = array('jpg', 'png');
foreach($imgs['name'] as $position => $img_name){
$img_tmp = $imgs['tmp_name'][$position];
$img_size = $imgs['size'][$position];
$img_error = $imgs['error'][$position];
$img_ext = explode('.',$img_name);
$img_ext = strtolower(end($img_ext));
if(in_array($img_ext, $allowed)) {
if($img_error === 0){
if($img_size <= 500000) {
$img_name_new = uniqid('', true) . '.' . $img_ext;
$img_destination = 'img/'.$img_name_new;
if(move_uploaded_file($img_tmp, $img_destination)){
$uploaded[$position] = $img_destination;
}else{
$failed[$position] = "[{$img_name}] failed to upload";
}
}else{
$failed[$position] = "[{$img_name}] is too large";
}
}else{
$failed[$position] = "[{$img_name}] error";
}
}else{
$failed[$position] = "[{$img_name}] file extension";
}
}
if(!empty($uploaded)){
print_r($uploaded);
}
if(!empty($failed)){
print_r($failed);
}
}
if(isset($_POST['submit'])){
$name = $_POST['name'];
$location = $_POST['location'];
$status = $_POST['status'];
$descrip = $_POST['descrip'];
$category = $_POST['category'];
$img_name_new = $_FILES['imgs']['name'];
if ($db->connect_error){
die ("Connection Failed: " . $db->connect_error);
}
$sql_u = "SELECT * FROM projects WHERE name='$name'";
$sql_e = "SELECT * FROM projects WHERE category='$category'";
$res_u = mysqli_query($db, $sql_u);
$res_e = mysqli_query($db, $sql_e);
if (mysqli_num_rows($res_u) && mysqli_num_rows($res_e) > 0) {
echo "<div style='margin: 0 80px' class='alert alert-danger' role='alert'> Error. Item Already exists </div>";
header("refresh:3 url=add.php");
}else{
$sql_i = "INSERT INTO items (name, location, status, descrip, imgs, category) VALUES ('$name','$location','$status,'$descrip','$img_name_new','$category')";
}
if (mysqli_query($db, $sql_i)){
echo "Project Added Successfully";
}else{
echo mysqli_error($db);
}
$db->close();
}
?>
$img_name_new = $_FILES['imgs']['name'] is an array of one or more image names.
You will need to decide how you wish to store the array data as a string in your database.
Here are a couple of sensible options, but choosing the best one will be determined by how you are going to using this data once it is in the database.
implode() it -- $img_name_new = implode(',', $_FILES['imgs']['name']);
json_encode() it -- $img_name_new = json_encode($_FILES['imgs']['name']);
And here is my good deed for the year...
Form Script:
<?php
if (!$db = new mysqli("localhost", "root", "", "db")) { // declare and check for a falsey value
echo "Connection Failure"; // $db->connect_error <-- never show actual error details to public
} else {
if ($result = $db->query("SELECT name FROM items")) {
for ($rows = []; $row = $result->fetch_row(); $rows[] = $row);
$result->free();
?>
<script>
function checkName() {
var names = '<?php echo json_encode($rows); ?>';
var value = document.forms['project']['name'].value;
if (names.indexOf(value) !== -1) { // might not work on some old browsers
alert(value + ' is not a unique name. Please choose another.');
return false;
}
}
</script>
<?php
}
?>
<form name="project" method="post" enctype="multipart/form-data" onsubmit="return checkName()">
Name: <input required type="text" name="name"><br>
Location: <input required type="text" name="location"><br>
Status: <input required type="text" name="status"><br>
Category: <select required name="category">
<?php
if ($result = $db->query("SELECT category, category_alias FROM categories")) {
while ($row = $result->fetch_assoc()) {
echo "<option value=\"{$row['category']}\">{$row['category_alias']}</option>";
}
}
?>
</select><br>
<textarea required class="form-control" name="descrip" rows="5"></textarea><br>
<input style="text-align:left" type="file" name="imgs[]" multiple><br>
<button type="submit" name="submit" formaction="addaction.php">Add Project</button>
</form>
<?php
}
*notice that I have made a separate category table for validation.
Submission Handling Script: (addaction.php)
<?php
if (isset($_POST['submit'], $_POST['name'], $_POST['location'], $_POST['status'], $_POST['descrip'], $_POST['category'], $_FILES['imgs']['name'][0])) {
$paths = [];
if (!empty($_FILES['imgs']['name'][0])) {
$imgs = $_FILES['imgs'];
$allowed = array('jpg', 'png');
foreach($imgs['name'] as $position => $img_name){
$img_tmp = $imgs['tmp_name'][$position];
$img_size = $imgs['size'][$position];
$img_error = $imgs['error'][$position];
$img_ext = strtolower(pathinfo($img_name)['extension']);
if (!in_array($img_ext, $allowed)) {
$errors[] = "File extension is not in whitelist for $img_name ($position)";
} elseif ($img_error) {
$errors[] = "Image error for $img_name ($position): $image_error";
} elseif ($img_size > 500000) {
$errors[] = "Image $image_name ($position) is too large";
} else {
$img_destination = 'img/' . uniqid('', true) . ".$img_ext";
if (!move_uploaded_file($img_tmp, $img_destination)) {
$errors[] = "Failed to move $img_name ($position) to new directory";
} else {
$paths[] = $img_destination;
}
}
}
}
if (!empty($errors)) {
echo '<ul><li>' , implode('</li><li>', $errors) , '</li></ul>';
} elseif (!$db = new mysqli("localhost", "root", "", "db")) { // declare and check for a falsey value
echo "Connection Failure"; // $db->connect_error <-- never show actual error details to public
} elseif (!$stmt = $db->prepare("SELECT COUNT(*) FROM categories WHERE category = ?")) {
echo "Prepare Syntax Error"; // $db->error; <-- never show actual error details to public
} elseif (!$stmt->bind_param("s", $_POST['category']) || !$stmt->execute() || !$stmt->bind_result($found) || !$stmt->fetch()) {
echo "Category Statement Error"; // $stmt->error; <-- never show actual error details to public
} elseif (!$found) {
echo "Category Not Found - Project Not Saved";
} else {
$stmt->close();
$cs_paths = (string)implode(',', $paths);
// Set the `name` column in `items` to UNIQUE so that you cannot receive duplicate names in database table
if (!$stmt = $db->prepare("INSERT INTO items (name, location, status, category, descrip, imgs) VALUES (?,?,?,?,?,?)")) {
echo "Error # prepare"; // $db->error; // don't show to public
} elseif (!$stmt->bind_param("ssssss", $_POST['name'], $_POST['location'], $_POST['status'], $_POST['category'], $_POST['descrip'], $cs_paths)) {
echo "Error # bind"; // $stmt->error; // don't show to public
} elseif (!$stmt->execute()) {
if ($stmt->errno == 1062) {
echo "Duplicate name submitted, please go back to the form and change the project name to be unique";
} else {
echo "Error # execute" , $stmt->error; // $stmt->error; // don't show to public
}
} else {
echo "Project Added Successfully";
}
}
}

how to import images from excel sheet to database in php

this is the code i Have used to insert the data from excel sheet to db.
but here i want to insert images from excel sheet to db.
but if i try the file which contain images it goes to the else part of the code.
is there any differnt functions there for upload the image into to db
<form action="" method="post" enctype="multipart/form-data">
<br>
<input type="file" name="file" id="file" accept=".xls,.xlsx">
<button type="submit" id="submit" name="import" class="btn-submit">Import</button>
</form>
<?php
//excel sheet data insert
$conn = mysqli_connect("localhost","root","","hep");
require_once('C:\xampp\phpMyAdmin\vendor\php-excel-reader\excel_reader2.php');
require_once('C:\xampp\phpMyAdmin\vendor\SpreadsheetReader.php');
if (isset($_POST["import"])){
$allowedFileType = ['application/vnd.ms-excel','text/xls','text/xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
//echo $_FILES["file"]["type"];
//exit;
if(in_array($_FILES["file"]["type"],$allowedFileType)==false){
echo "only Excel Files Supported";
} else {
$targetPath = 'import/'.$_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $targetPath);
$Reader = new SpreadsheetReader($targetPath);
$sheetCount = count($Reader->sheets());
// print_r($sheetCount);
//exit;
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]);
}
$email = "";
if(isset($Row[1])) {
$email = mysqli_real_escape_string($conn,$Row[1]);
}
if (!empty($name) || !empty($description)) {
$query = "insert into form(no,name) values('".$name."','".$email."')";
$result = mysqli_query($conn, $query);
if (! empty($result)) {
echo "Excel Data Imported into the Database";
} else {
echo "Problem in Importing Excel Data";
}
}
}
}
}
}
?>
if you have any idea please post your answers..
thanks in advance.

I can't display my blob pictures from mysql db in php

In my application, I store the pictures as blob in the mysql db.
Now I want to display the pictures in my web application.
Now the Problem is:
The images are not displayed. Just a small sign. I'm not getting any error message.
I don't know how to update my project, to display the pictures
Model function:
public function create($fileName, $fileType, $fileSize, $fileContent, $gallery){
$query = "INSERT INTO $this->tableName (name, type, size, content, gallery_ID) VALUES (?, ?, ?, ?, ?)";
$statement = ConnectionHandler::getConnection()->prepare($query);
$statement->bind_param('ssisi', $fileName, $fileType, $fileSize, $fileContent, $gallery);
$success = $statement->execute();
if (!$success) {
throw new Exception($statement->error);
}
}
public function listByID($galleryID){
$query = "SELECT * from $this->tableName where gallery_ID = ?";
$statement = ConnectionHandler::getConnection()->prepare($query);
$statement->bind_param('i', $galleryID);
$statement->execute();
$result = $statement->get_result();
if (!$result) {
throw new Exception($statement->error);
}
$rows = array();
while ($row = $result->fetch_object()) {
$rows[] = $row;
}
return $rows;
}
Controller Method:
public function doAddPhoto(){
$fileName = $_FILES['fileToUpload']['name'];
$fileSize = $_FILES['fileToUpload']['size'];
$fileType = $_FILES['fileToUpload']['type'];
$tmpName = $_FILES['fileToUpload']['tmp_name'];
$gallery = $_SESSION['gallery'];
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if($_FILES['fileToUpload']['size'] <= 0 ){
echo '<div class="alert alert-danger" id="messsage" role="alert">No Picture selected</div>';
}
else if ($_FILES["fileToUpload"]["size"] > 4194304) {
echo '<div class="alert alert-danger" id="messsage" role="alert">File to big</div>';
}
else if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo '<div class="alert alert-danger" id="messsage" role="alert">Sorry, only JPG, JPEG, PNG & GIF files are allowed.</div>';
}
else {
$fp = fopen($tmpName, 'r');
$fileContent = fread($fp, filesize($tmpName));
fclose($fp);
if(!get_magic_quotes_gpc()){
$fileName = addslashes($fileName);
}
$photoModel = new PhotoModel();
$photoModel->create($fileName, $fileType, $fileSize, $fileContent, $gallery);
}
header('location: /gallery/ListGalleriesPerUserOverview');
}
public function showPhotosPerUser(){
if (!isset($_SESSION ['loggedin']) || $_SESSION ['loggedin'] != true)
{
header('location: /');
return;
}
else{
$view = new View('gallery');
$galleryID = $_SESSION['gallery'];
$photoModel = new PhotoModel($galleryID);
$photos = $photoModel->listByID($galleryID);
$view->photos = $photos;
$view->display();
}
}
HTML:
<form action="/photo/doAddPhoto" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="uploadBtn">
</form>
<?php
foreach ($photos as $photo){
$content = $photo->content;
echo '<div class="col-md-3 portfolio-item">
<a href="#">
<img src="data:image/jpeg;base64,'. base64_encode($content) .'" />
</a>
</div>';
}
?>

Setting the result of an if statement

I am displaying a user's profile image. I have created an if statement to post a default profile image if a user has not updated their own. This is all working, but what I cannot figure out is how to echo or call for each without getting an error for the one not set.
For instance, if they do have a profile picture set, it posts fine, but then I get an error that the other variable is not defined and vise versa.
How should I be calling for this or what changes should I make in my code?
$pics = array();
while ($stmt->fetch()) {
$pics[] = $profilePic;
}
if ($profilePic === NULL) {
$default_profile_img = '<img class="welcome-pic" src="profile_images/default.jpg">';
} else {
$set_profile_img = '<img class="welcome-pic" src=" '.$profilePic.'">';
}
}
?>
<nav id="nav-panel">
<div id="nav-container">
<div id="welcome">
<?php echo $default_profile_img;
echo $set_profile_img; ?>
EDIT:
How profilepic gets defined:
$sql = "
SELECT *
FROM profile_img
WHERE user_id = ?
ORDER BY id DESC LIMIT 1
";
if ($stmt = $con->prepare($sql)) {
$stmt->bind_param("s", $user_id);
$stmt->execute();
if (!$stmt->errno) {
// Handle error here
}
$stmt->bind_result($id, $user_id, $profilePic);
Just add $default_profile_img = null; and $set_profile_img = null; at the top of php code.
$default_profile_img = null;
$set_profile_img = null;
$pics = array();
while ($stmt->fetch()) {
$pics[] = $profilePic;
}
if ($profilePic === NULL) {
$default_profile_img = '<img class="welcome-pic" src="profile_images/default.jpg">';
} else {
$set_profile_img = '<img class="welcome-pic" src=" '.$profilePic.'">';
}
}
?>
<nav id="nav-panel">
<div id="nav-container">
<div id="welcome">
<?php echo $default_profile_img;
echo $set_profile_img; ?>
You just need to initialize the variables before the if..else statements so that it won't be undefined when you try to echo both of them.
$profile_img = "";
$default_profile_img = "";
if (...
Try this code. There is no need to use two different variables. This way, you won't get the warning.
$pics = array();
while ($stmt->fetch()) {
$pics[] = $profilePic;
}
if (!isset($profilePic) OR $profilePic === NULL) {
$profile_img = '<img class="welcome-pic" src="profile_images/default.jpg">';
} else {
$profile_img = '<img class="welcome-pic" src=" '.$profilePic.'">';
}
}
?>
<nav id="nav-panel">
<div id="nav-container">
<div id="welcome">
<?php echo $profile_img; ?>

Mysql INSERT statement FAILING when POSTING large array

I've been searching the internet and "pulling my hair out" for days over this. It works fine on my XAMPP localhost and was working fine on my online testing server until I updated the PHP version and had to rewrite the code due to deprecated syntax.
Basically, I'm making a backend database for photography clients. One of the tables is designed to store image information. I haven't tried to store an actual image (BLOB of some sorts), I'm just looking to store "what and where".
What seems to be happening is if I try entering the contents of a shoot directory with several hundred images, when I hit input the screen changes, then instead of telling me how many were entered, it goes to a "418 unused" page saying
The server encountered an internal error or misconfiguration and was unable to complete your request.
I've been trying to narrow down which buffers to increase or variables like "max_allowed_packet", "max_input_vars"... still no luck. I've even tried comparing the phpinfo between the two servers to find out why one works and the other doesn't...
Here's what I'm doing... the listpage
<?php
// set page headers
$page_title = "Enter Images into Database";
include_once 'auth.php';
// get database connection
include_once 'config/fpaddb.php';
include_once 'objects/clients.php';
include_once 'objects/photoshoots.php';
include_once 'objects/images.php';
$database = new Database();
$db = $database->getConnection();
$colname_chk_Images = "-1";
if (isset($_GET['ShootId'])) {
$colname_chk_Images = $_GET['ShootId'];
}
$colname1_chk_Images = "NULL";
if (isset($_GET['ShootFolder'])) {
$colname1_chk_Images = $_GET['ShootFolder'];
}
$colname_get_Images = "-1";
if (isset($_SESSION['cID'])) {
$colname_get_Images = $_SESSION['cID'];
}
$entered=0; //check for already entered images
?>
<?php
$dirname=$_SESSION['cIFolder'];
$Clogin=$_SESSION['Clogin'];
$ClientID=$_SESSION['cID'];
$_SESSION['CURR_CLIENT_ID'] = $ClientID;
$maindir=$_GET['ShootFolder'];
$ShootId=$_GET['ShootId'];
$dir=$_SERVER['DOCUMENT_ROOT'].dirname($_SERVER['PHP_SELF'])."protect/clientfolders/".$Clogin."/users/".$Clogin."/images/".$maindir;
$_SESSION['dir']=$dir;
$dir2="/protect/clientfolders/".$Clogin."/users/".$Clogin."/images/".$maindir;
$dirt= "/phpThumb-master/";
$dirn= dirname($_SERVER['PHP_SELF']);
$filesArray=array_map('basename', glob($dir."/*.jpg"));
$lightbox_data= "FPAD_Lightbox";
$thumb = "$dir2/";
$notThumb = "$dir2/";
$ic = count($filesArray);
$_SESSION['SESS_TOTNUM'] = $ic;
$_SESSION['sID'] = $ShootId;
$sID = $_SESSION['sID'];
include_once 'header_a.php';
?>
<div class="container">
<?php
echo $_SESSION['SESS_TOTNUM']." images found ";
echo "for Shoot ID#: ".$_SESSION['sID']."<br>";
echo "*Note* - if input boxes come up GREEN, then images are already loaded into the database";
?>
<p>
<?php
$images1 = new Image($db);
$images1->ShootId = $colname_chk_Images;
$images1->directory = $colname1_chk_Images;
$images1->ClientID = $colname_get_Images;
$chk_Images = $images1->checkImages();
$get_Images = $images1->getImages();
$Images = array();
while ($row_get_Images = $get_Images->fetch(PDO::FETCH_ASSOC))
{
$Images[] = $row_get_Images['image_name'];
}
?></p>
<form method="POST" name="form1" id="form1" action="input.php">
<table id="clientshoots" class="table table-condensed table-bordered table-small">
<tr>
<th>image_id</th>
<th>image_name</th>
<th>image_path</th>
<th>image_path_root</th>
<th>image_size</th>
<th>directory</th>
<th width="auto">ShootId</th>
<th width="auto">ClientID</th>
<th>ClientName</th>
<th>login</th>
</tr>
<?php $ic=0;
for($i=0;$i<count($filesArray);$i++) {
$fileinfo = $filesArray[$i];
$fname=$dir."/".$fileinfo;
$fname2=$dir2."/".$fileinfo;
$size = filesize($fname);
$atime = date("F d, Y H:i:s", fileatime($fname));
$mtime= date("F d, Y H:i:s", filemtime($fname));
$perms=decoct(fileperms($fname) & 0777);
$type=filetype($fname);
$pth=realpath($fname);
$name=basename($fname);
$dn=dirname($fname2);
if (in_array($fileinfo, $Images)) {
$entered=1;
echo "<style type=\"text/css\">\n";
echo "input {\n";
echo "background-color:#00FF33;\n";
echo "}\n";
echo "</style>";
}
?>
<tr>
<td> </td>
<td><input type="text" name="image_name[]" value="<?php echo $fileinfo; ?>" readonly/></td>
<td><input type="text" name="image_path[]" value="<?php echo $dir; ?>" readonly/></td>
<td><input type="text" name="image_path_root[]" value="<?php echo $dir2; ?>" readonly/></td>
<td><input type="number" name="image_size[]" value="<?php echo $size; ?>" readonly/></td>
<td><input type="text" name="directory[]" value="<?php echo $maindir; ?>" readonly/></td>
<td><input type="number" name="ShootId[]" value="<?php echo $ShootId; ?>" readonly/></td>
<td><input type="number" name="ClientID[]" value="<?php echo $ClientID; ?>" readonly/></td>
<td><input type="text" name="ClientName[]" value="<?php echo $_SESSION['cName']; ?>" readonly/></td>
<td><input type="text" name="login[]" value="<?php echo $Clogin; ?>" readonly/></td>
</tr>
<?php next($filesArray);
$ic=$ic+1;
}
$_SESSION['SESS_IC'] = $ic;?>
</table>
<?php if ($entered == 1){
echo "Return";
} else {
echo "<input class=\"btn-primary\" style=\"background-color:\" id=\"Insert records\" type=\"submit\" value=\"Insert records\">";
}?>
<input type="hidden" name="MM_insert" value="form1">
<input type="hidden" name="sID" value="<?php echo $sID; ?>">
</form>
</div>
<br>
<!-- /container -->
<?php include 'footer_b.php'; ?>
and then the input.php page...
<?php
// set page headers
$page_title = "Enter Images into Database";
include_once 'auth.php';
// get database connection
include_once 'config/fpaddb.php';
include_once 'objects/clients.php';
include_once 'objects/photoshoots.php';
include_once 'objects/images.php';
include_once 'objects/ratings.php';
$database = new Database();
$db = $database->getConnection();
$sID = $_SESSION['sID'];
$ic = $_SESSION['SESS_IC'];
$ma = $_SESSION['SESS_CLIENT_MULTI'];
$gn = $_SESSION['SESS_CLIENT_GRPNO'];
$cID = $_SESSION['cID'];
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = filter_var(($str), FILTER_SANITIZE_STRING);
return ($str);
}
$image1 = new Image($db);
$count = count($_POST['image_name']);
$fileinfo = clean($_POST['image_name']);
//Check for duplicates
if($fileinfo != '') {
for($i=0;$i<$count;$i++) {
$fileinfo = clean($_POST['image_name'][$i]);
//echo $fileinfo;
$image1->image_name = $fileinfo;
$result = $image1->check4Dup();
if($result) {
if(count($result) > 0) {
$errmsg_arr[] = 'Image already entered into Database';
$errflag = true;
}
$result = NULL;
}
else {
die($e->getMessage());
}
next($count);
}
}
$image1->ic = $ic;
$num = $image1->create();
$colname_newImages = "-1";
if (isset($sID)) {
$colname_newImages = $sID;
}
$image1->ShootId = $sID;
$newImages = $image1->countOneShoot();
$row_newImages = $newImages->fetch(PDO::FETCH_ASSOC);
$totalRows_newImages = $newImages->rowCount();
$ic2 = $totalRows_newImages;
$_SESSION['SESS_TOTNUM_ENT'] = $ic2;
header("Location: rs_images.php");
include_once 'header_a.php';
?>
<div class="container">
<?php
echo "Success! Number of images entered is ".$ic2; ?>
<br><br>
<p><input name="Verify" type="button" value="Verify Inputs" onclick="MM_goToURL('parent','rs_images.php');return document.MM_returnValue"/></p>
</div>
<?php include 'footer_b.php'; ?>
And the Class file...
<?php
class Image{
// database connection and table name
private $dbh;
private $table_name = "images";
// object properties
public $image_id;
public $image_name;
public $image_path;
public $image_path_root;
public $image_size;
public $directory;
public $ShootId;
public $ClientID;
public $ClientName;
public $login;
public $ic;
public function __construct($db){
$this->dbh = $db;
}
// Clean Function
function clean($str){
$str = filter_var(($str), FILTER_SANITIZE_STRING);
return ($str);
}
// test function
function test(){
$ic = $this->ic;
$i=1;
$j=1;
foreach ($_POST['image_name'] as $row=>$iname)
{
$image_name = clean($iname);
$image_path = clean($_POST['image_path'][$row]);
$image_path_root = clean($_POST['image_path_root'][$row]);
$image_size = clean($_POST['image_size'][$row]);
$directory = clean($_POST['directory'][$row]);
$ShootId = clean($_POST['ShootId'][$row]);
$ClientID = clean($_POST['ClientID'][$row]);
$ClientName = clean($_POST['ClientName'][$row]);
$login = clean($_POST['login'][$row]);
$Clogin = $login."');";
$i=$i+1;
$j=$j+1;
$qry1st = "INSERT INTO `images` (image_name, image_path, image_path_root, image_size, directory, ShootId, ClientID, ClientName, login) VALUES ";
$sql_array = "('".$image_name."', '".$image_path."', '".$image_path_root."', ".$image_size.", '".$directory."', ".$ShootId.", ".$ClientID.", '".$ClientName."', '".$Clogin;
//$stmt = $this->dbh->prepare($qry1st.$sql_array);
//$stmt->execute();
echo $qry1st.$sql_array;
}
}
// create function
function create(){
$ic = $this->ic;
$qry1st = "INSERT INTO `images` (image_name, image_path, image_path_root, image_size, directory, ShootId, ClientID, ClientName, login) VALUES ";
$sql_array = array(); // This is where we'll queue up the rows
$queue_num = 50; // How many rows should be queued at once?
$i=1;
foreach ($_POST['image_name'] as $row=>$iname)
{
$image_name = clean($iname);
$image_path = clean($_POST['image_path'][$row]);
$image_path_root = clean($_POST['image_path_root'][$row]);
$image_size = clean($_POST['image_size'][$row]);
$directory = clean($_POST['directory'][$row]);
$ShootId = clean($_POST['ShootId'][$row]);
$ClientID = clean($_POST['ClientID'][$row]);
$ClientName = clean($_POST['ClientName'][$row]);
$login = clean($_POST['login'][$row]);
if ($i==($_SESSION['SESS_TOTNUM'])) {
$login_term = $login."');";
}
else
{
$login_term = $login."')";
$i=$i+1;
}
$sql_array[] = "('".$image_name."', '".$image_path."', '".$image_path_root."', ".$image_size.", '".$directory."', ".$ShootId.", ".$ClientID.", '".$ClientName."', '".$login_term;
// Add a new entry to the queue
$c=0;
if (count($sql_array) >= $queue_num)
{ // Reached the queue limit
$addImages = $this->dbh->query($qry1st . implode(', ', $sql_array)); // Insert those that are queued up
$addImages->execute();
$sql_array = array(); // Erase the queue
}//End if
}//end foreach
if (count($sql_array) > 0) // There are rows left over
{
$addImages = $this->dbh->query($qry1st . implode(', ', $sql_array));
$addImages->execute();
}
}
function checkImages(){
$query_chk_Images = "SELECT images.image_name FROM images WHERE ShootId = ? AND directory = ?";
$chk_Images = $this->dbh->prepare ($query_chk_Images);
$chk_Images->bindValue(1, $this->ShootId);
$chk_Images->bindValue(2, $this->directory);
$chk_Images->execute();
return $chk_Images;
}
// create function
function getImages(){
$query_get_Images = "SELECT * FROM images WHERE ClientID = ? ORDER BY image_name ASC";
$get_Images = $this->dbh->prepare ($query_get_Images);
$get_Images->bindValue(1, $this->ClientID);
$get_Images->execute();
return $get_Images;
}
// create function
function getImageID(){
$query_rsImageID = "SELECT * FROM images WHERE ShootId = ? ORDER BY image_id ASC";
$rsImageID = $this->dbh->prepare($query_rsImageID);
$rsImageID->bindValue(1, $this->ShootId);
$rsImageID->execute();
return $rsImageID;
}
// create function
function get_image_id(){
$q = "SELECT image_id FROM images WHERE ShootId = ? ORDER BY image_id ASC";
$stmt = $this->dbh->prepare($q);
$stmt->bindValue(1, $this->ShootId);
$stmt->execute();
return $stmt;
}
// create function
function countOneShoot(){
$query_newImages = "SELECT * FROM images WHERE ShootId = ?";
$newImages = $this->dbh->prepare($query_newImages);
$newImages->bindValue(1, $this->ShootId);
$newImages->execute();
return $newImages;
}
// create function
function check4Dup(){
$qry = "SELECT * FROM `images` WHERE image_name = ?";
$result = $this->dbh->prepare($qry);
$result->bindValue(1, $this->image_name);
$result->execute();
return $result;
}
}
I've striped out all the extra stuff I've tried, like entering the info one record at a time, binding the Values with colon prefixed field names instead of the ?'s. I've tried different loops. I think it comes down to trying to push too much through one query... but then why does it work on XAMPP and why was it working fine with PHP 5.2?
I appreciate any light that can be shed on this. This is my first ever post with regards to PHP, MySQL or anything site related, I've been learning this stuff as I go and had it 90% completed and debugged and when I put it online to do some real testing with the actual directories and client folders that's when I found out that between PHP 5.4 and 5.2, there have been a number of changes and I found myself rewriting almost every line to move up to either MySQLi or PDO/OOP. After doing a lot searching around the internet I've opted for the OOP approach and still need to rewrite even more of the code above to clean things up a ton, but right now I'm troubleshooting the INSERT failure which I have not been able to solve on my own or with the help of all the forums, posts and blogs I've read to date.

Categories