PHP Explode and updata data to each colomn in mysql database - php

I have a form where I want a user to upload one or more images. I've used only one file field for this. The issue is when I submit the form only the "itemImageOne" field will be update. But the echo part( echo $pieces[0], echo $pieces[1] ) is shows the correct result. Bellow is part of my code.
<?php
error_reporting(E_ALL & ~E_NOTICE);
#ini_set('post_max_size', '64M');
#ini_set('upload_max_filesize', '64M');
/* * *********************************************** */
// database constants
define('DB_DRIVER', 'mysql');
define('DB_SERVER', 'localhost');
define('DB_SERVER_USERNAME', 'root');
define('DB_SERVER_PASSWORD', '');
define('DB_DATABASE', 'ibs');
$dboptions = array(
PDO::ATTR_PERSISTENT => FALSE,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
$DB = new PDO(DB_DRIVER . ':host=' . DB_SERVER . ';dbname=' . DB_DATABASE, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, $dboptions);
} catch (Exception $ex) {
echo $ex->getMessage();
die;
}
if (isset($_POST["add"])) {
// include resized library
//require_once('./php-image-magician/php_image_magician.php');
$msg = "";
$pieces = "";
$valid_image_check = array("image/gif", "image/jpeg", "image/jpg", "image/png", "image/bmp");
if (count($_FILES["user_files"]) > 0) {
$folderName = "uploads/";
//$sql = "UPDATE module_course SET itemImage='$filename' WHERE id=1";
//$sql = "UPDATE SET module_course(itemImage) VALUES (:img)";
//$stmt = $DB->prepare($sql);
for ($i = 0; $i < count($_FILES["user_files"]["name"]); $i++) {
if ($_FILES["user_files"]["name"][$i] <> "") {
$image_mime = strtolower(image_type_to_mime_type(exif_imagetype($_FILES["user_files"]["tmp_name"][$i])));
// if valid image type then upload
if (in_array($image_mime, $valid_image_check)) {
$ext = explode("/", strtolower($image_mime));
$ext = strtolower(end($ext));
$filename = rand(10000, 990000) . '_' . time() . '.' . $ext;
$filepath = $folderName . $filename;
$pieces = explode(" ", $filename);
$imageOne = $pieces[0];
$imageTwo = $pieces[1];
echo $pieces[0]."<br/>"; // piece1
echo $pieces[1]."<br/>"; // piece2
$sql = "UPDATE module_course SET itemImageOne = $imageOne, itemImageTwo = $date WHERE id='1'";
$stmt = $DB->prepare($sql);
if (!move_uploaded_file($_FILES["user_files"]["tmp_name"][$i], $filepath)) {
$emsg .= "Failed to upload <strong>" . $_FILES["user_files"]["name"][$i] . "</strong>. <br>";
$counter++;
} else {
$smsg .= "<strong>" . $_FILES["user_files"]["name"][$i] . "</strong> uploaded successfully. <br>";
/* * ****** insert into database starts ******** */
try {
$stmt->bindValue(":img", $filename);
$stmt->execute();
$result = $stmt->rowCount();
if ($result > 0) {
// file uplaoded successfully.
} else {
// failed to insert into database.
}
} catch (Exception $ex) {
$emsg .= "<strong>" . $ex->getMessage() . "</strong>. <br>";
}
/* * ****** insert into database ends ******** */
}
} else {
$emsg .= "<strong>" . $_FILES["user_files"]["name"][$i] . "</strong> not a valid image. <br>";
}
}
}
$msg .= (strlen($smsg) > 0) ? successMessage($smsg) : "";
$msg .= (strlen($emsg) > 0) ? errorMessage($emsg) : "";
} else {
$msg = errorMessage("You must upload atleast one file");
}
}
?>

Try
UPDATE module_course
SET itemImageOne = $imageOne, itemImageTwo = $imageTwo
WHERE id = '1'; # Changed
Changed - Edit 01
$stmt = $DB->prepare("UPDATE module_course
SET itemImageOne = ?, itemImageTwo = ?
WHERE id = 1");
$stmt->bindValue(1, $imageOne, PDO::PARAM_STR);
$stmt->bindValue(2, $imageTwo, PDO::PARAM_STR);
$stmt->execute();
Error Bcz of you are binding one parameter $stmt->bindValue(":img", $filename);

Related

How to print out individual field data on the page instead of the entire table contents

So I have this php code that gets results from a MySQL database and cache them using Memcached. I need help taking control of how I print the results on the page.
From the code below, i need help on how I can print something like this:
echo "<br> id: ". $row["product_id"]
. " - Name: ". $row["product_name"]. " "
. " - Price: ". $row["retail_price"] . "<br>";
This is the code I need to be modified :
<?php
header("Content-Type:application/json");
try {
$db_name = 'test_db';
$db_user = 'test_db_user';
$db_password = 'EXAMPLE_PASSWORD';
$db_host = 'localhost';
$memcache = new Memcache();
$memcache->addServer("127.0.0.1", 11211);
$sql = 'SELECT
product_id,
product_name,
retail_price
FROM products
';
$key = md5($sql);
$cached_data = $memcache->get($key);
$response = [];
if ($cached_data != null) {
$response['Memcache Data'] = $cached_data;
} else {
$pdo = new PDO("mysql:host=" . $db_host . ";dbname=" . $db_name, $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $pdo->prepare($sql);
$stmt->execute();
$products = [];
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)) !== false) {
$products[] = $row;
}
$memcache->set($key, $products, false, 5);
$response['MySQL Data'] = $products;
}
echo json_encode($response, JSON_PRETTY_PRINT) . "\n";
} catch(PDOException $e) {
$error = [];
$error['message'] = $e->getMessage();
echo json_encode($error, JSON_PRETTY_PRINT) . "\n";
}
Just like you normally would print results of SELECT query. Although here it seems there's an ajax call invovled.
header("Content-Type:application/json");
try {
$db_name = 'test_db';
$db_user = 'test_db_user';
$db_password = 'EXAMPLE_PASSWORD';
$db_host = 'localhost';
$memcache = new Memcache();
$memcache->addServer("127.0.0.1", 11211);
$sql = 'SELECT
product_id,
product_name,
retail_price
FROM products
';
$key = md5($sql);
$cached_data = $memcache->get($key);
$response = [];
$result = null;
if ($cached_data != null) {
$response['Memcache Data'] = $cached_data;
$result = $cached_data;
} else {
$pdo = new PDO("mysql:host=" . $db_host . ";dbname=" . $db_name, $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $pdo->prepare($sql);
$stmt->execute();
$products = [];
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)) !== false) {
$products[] = $row;
}
$memcache->set($key, $products, false, 5);
$response['MySQL Data'] = $products;
$result = $products;
}
// echo json_encode($response, JSON_PRETTY_PRINT) . "\n";
$html = "";
foreach ($result as $row) {
$html .= "<br> id: ". $row["product_id"]
. " - Name: ". $row["product_name"]. " "
. " - Price: ". $row["retail_price"] . "<br>";
}
// return as HTML (won't work in ajax)
echo $html;
// or for ajax:
echo json_encode($html, JSON_PRETTY_PRINT) . "\n";
// or
echo json_encode(["html" => $html], JSON_PRETTY_PRINT) . "\n";
} catch(PDOException $e) {
$error = [];
$error['message'] = $e->getMessage();
echo json_encode($error, JSON_PRETTY_PRINT) . "\n";
}

Call to undefined function mysqli_begin_transaction() error

I am using a php script that handles the backup & restore of my databases. There are several problems with it but I shall post 1 error at a time. When I click restore backup button I am getting the error in the title.
I am not experienced enough to troubleshoot this error and would appreciate some help from the experts. I have posted my code where the error occurs, but if you need to see anything else please let know. The error occurs at line 109. Thanks
PHP V5.3.13
MYSQL V5.5.24
APACHE V2.2.22
<?php
function restoredata($uploadedfile, &$ustartindex, &$uti, &$ulen, &$ucount, &$name, &$limit, $restoremethod)
{
global $host, $username, $passwd, $charset, $port, $upload_path, $backup_path;
$sql = '';
$zip = new ZipArchive();
$filename = $upload_path . '/' . $uploadedfile;
if (!is_file($filename)) {
$filename = $backup_path . '/' . $uploadedfile;
}
if ($zip->open($filename) !== TRUE) {
return "Cannot open file\n.";
}
try {
$dbName = $zip->getFromName('database.txt');
if ($restoremethod == '0') {
$conn = mysqli_connect($host, $username, $passwd, $dbName, $port);
}
else {
if ($uti == 0 && $ustartindex == 0) {
$conn = mysqli_connect($host, $username, $passwd, 'mysql', $port);
}
else {
$conn = mysqli_connect($host, $username, $passwd, $dbName, $port);
}
}
if (!$conn) {
return 'Could not connect ' . mysqli_error($conn);
}
if (!mysqli_set_charset($conn, $charset)) {
mysqli_query($conn, 'SET NAMES ' . $charset);
}
$tables = $zip->getFromName('tables.txt');
if ($tables === false) {
$zip->close();
return "Could'nt find tables";
}
$limit = intval($zip->getFromName('limit_info.txt'));
$tables = explode(',', $tables);
$ulen = count($tables);
if ($uti < $ulen) {
if ($uti == 0 && $ustartindex == 0) {
if ($restoremethod == '1') {
$sql = $zip->getFromName($dbName . '.sql');
if ($sql !== false) {
$sql = explode(';' . chr(10) , $sql);
for ($i = 0; $i < count($sql) - 1; $i++) {
$result = mysqli_query($conn, $sql[$i] . ';');
if (!$result) {
mysqli_close($conn);
$zip->close();
return 'Could not run query 1: ' . mysqli_error($conn);
}
}
}
mysqli_close($conn);
$conn = mysqli_connect($host, $username, $passwd, $dbName, $port);
if (!$conn) {
$zip->close();
return 'Could not connect ';
}
for ($i = 0; $i < $ulen; $i++) {
$name = $tables[$i];
$table = '`' . $name . '`';
$sql = $zip->getFromName($table . '.sql');
if ($sql !== false) {
$sql = explode(';' . chr(10) , $sql);
for ($j = 0; $j < count($sql) - 1; $j++) {
$result = mysqli_query($conn, $sql[$j] . ';');
if (!$result) {
mysqli_close($conn);
$zip->close();
return 'Could not run query 2: ' . mysqli_error($conn);
}
}
}
}
}
}
mysqli_autocommit($conn, FALSE);
// mysqli_begin_transaction ($conn, MYSQLI_TRANS_START_READ_ONLY );//READ ONLY transaction
mysqli_begin_transaction($conn, MYSQLI_TRANS_START_READ_WRITE); <---ERROR HERE
$name = $tables[$uti];
$table = '`' . $name . '`';
$ucount = intval($zip->getFromName($table . '.txt'));
$sql = $tables = $zip->getFromName($table . '/offset' . $ustartindex . '.sql');
$nerrors = 0;
$serrors = '';
if ($sql !== false) {
$sql = explode(';' . chr(10) , $sql);
for ($i = 0; $i < count($sql) - 1; $i++) {
$sql[$i] = str_replace('NULL', "''", $sql[$i]); //avoid NULL errors
$result = mysqli_query($conn, $sql[$i] . ';');
if (!$result) {
$serrors.= 'Could not run query in ' . $table . ' : ' . mysqli_error($conn) . '<br />';
$nerrors+= 1;
break;
}
}
$ustartindex+= $limit;
}
else {
$uti+= 1;
$ustartindex = 0;
}
if (!mysqli_commit($conn)) {
return "Transaction commit failed";
}
if ($nerrors > 0) {
mysqli_close($conn);
$zip->close();
return $serrors;
}
}
mysqli_close($conn);
$zip->close();
}
catch(Exception $e) {
return var_dump($e->getMessage());
}
return true;
}
?>
I will add that this is not my script but it does all all I need it to do including showing the progress of the backup, which visually is better than just a white page.
I would if possible like to sort these errors out and have a working script. Many thanks.
From http://php.net/manual/en/mysqli.begin-transaction.php, mysqli_begin_transaction is only supported from php 5.5.0 onwards. As your running 5.3 it won't work.
You could remove the transaction and it would work, especially as your originally trying to set a read-only transaction. Also remove the commit.
I would remove the following line as this would rely on transactions working as you'd expect.
mysqli_autocommit($conn, FALSE);
If you NEED to stay on 5.3 then...
mysqli_query($conn, "START TRANSACTION");

Excel date is changed to different date in mysql

I am trying to import the excel file to mysql database. I have got date and IMEI field in excel to import to database. But while importing to database my date is changd to different date and IMEI no is changed to exponential format. How can I resolve that problem.
here is the picture.
And here is the code.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "portal";
//$exceldata = array();
// Create connection
$con = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
/** Set default timezone (will throw a notice otherwise) */
date_default_timezone_set('Asia/Kolkata');
include 'Classes2/PHPExcel/IOFactory.php';
if(isset($_FILES['file']['name'])){
// $file_name = $_FILES['file']['name'];
// $ext = pathinfo($file_name, PATHINFO_EXTENSION);
//Checking the file extension
$file_name = $_FILES['file']['tmp_name'];
$inputFileName = $file_name;
if(is_uploaded_file($inputFileName)){
// Read your Excel workbook
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch (Exception $e) {
die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
. '": ' . $e->getMessage());
}
//Table used to display the contents of the file
echo '<center><table style="width:50%;" border=1>';
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
// Loop through each row of the worksheet in turn
for ($row = 2; $row <= $highestRow; $row++) {
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL, TRUE, FALSE);
//check whether member already exists in database with same email
$prevQuery = "SELECT id FROM activereport WHERE aIMEI = '".$rowData[0][1]."' ";
// $prevResult = $con->query($prevQuery);
$prevResult = mysqli_query($con,$prevQuery);
$count = mysqli_num_rows($prevResult);
if($count > 0){
// //update member data
$sql = " UPDATE activereport SET modelno= '".$rowData[0][0]."', dateOfActivation='" . $rowData[0][2] . "' WHERE aIMEI = '" .$rowData[0][1]."' ";
}
else{
$sql = " INSERT INTO activereport (modelno, aIMEI, dateOfActivation) VALUES ('".$rowData[0][0]."','".$rowData[0][1]."','".$rowData[0][2]."')";
}
if (mysqli_query($con, $sql)) {
$exceldata[] = $rowData[0];
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}
echo '</table></center>';
//redirect to the listing page
header("Location: Import_Active_Data.php");
}
else{
echo '<p style="color:red;">Please upload valid</p>';
}
}
?>
One reason for this behavior could be the way excel stores dates: by counting the days since Jan 1, 1900. if you pass that as an argument to your sql query, it could do weird things.
Try converting the excel date to a string first and pass that to the sql query.
So, I'd change this block:
if($count > 0){
// //update member data
$sql = " UPDATE activereport SET modelno= '".$rowData[0][0]."', dateOfActivation='" . $rowData[0][2] . "' WHERE aIMEI = '" .$rowData[0][1]."' ";
}
else{
$sql = " INSERT INTO activereport (modelno, aIMEI, dateOfActivation) VALUES ('".$rowData[0][0]."','".$rowData[0][1]."','".$rowData[0][2]."')";
}
into this:
if($count > 0){
// Date-to-string conversion start
$exceldate = $rowData[0][2];
$phpdate = new DateTime();
$phpdate->setDate(1899, 12, 30);
$dateint = new DateInterval("P" . $exceldate . "D");
$phpdate->add($dateint);
$datestring = $phpdate->format("Y-m-d");
// Date-to-string conversion end
// //update member data
$sql = " UPDATE activereport SET modelno= '".$rowData[0][0]."', dateOfActivation='" . $datestring . "' WHERE aIMEI = '" .$rowData[0][1]."' ";
}
else{
$sql = " INSERT INTO activereport (modelno, aIMEI, dateOfActivation) VALUES ('".$rowData[0][0]."','".$rowData[0][1]."','".$datestring."')";
}
Instead of using the rowData[0][2] directly, this will convert the value of that Excel cell (2017-11-11 = 43050) into a php-string ('2017-11-11'), which you can then pass to the sql query.

PHP - How to import 200k data faster? And there's 403 error

How can I import 200k data faster?
And when I importing csv (delimited by comma) file using online, I got 403 error, and it inserted 200-400 data only. Also when I try to import it using localhost (xampp) i got
"Exception EAccessViolation in module xampp-control.exe at 001AA712.
Access violation at address 005AA712 in module 'xampp-control.exe'.
Read of address 00000042"
And the SQL Database connection is gone.
This is the code I used.
set_time_limit(0);
ignore_user_abort(true);
$file = $_FILES['file']['name'];
$type = $_FILES['file']['type'];
$size = $_FILES['file']['size'];
$temp = $_FILES['file']['tmp_name'];
$error = $_FILES['file']['error'];
if( ! $file)
{
$data['error'] = "Please select a file!";
}
else if($type != "application/vnd.ms-excel" && $type != "application/octet-stream")
{
$data['error'] = "Invalid file type!";
}
else
{
$newname = $file." - ".date("Ymd His");
move_uploaded_file($temp, "uploads/".$newname);
$fieldseparator = ",";
$lineseparator = "\n";
$csvfile = "uploads/".$newname;
if( ! file_exists($csvfile))
{
echo "File not found. Make sure you specified the correct path.\n";
exit;
}
$file = fopen($csvfile,"r");
if( ! $file)
{
echo "Error opening data file.";
exit;
}
$size = filesize($csvfile);
if(!$size)
{
echo "File is empty.";
exit;
}
$csvcontent = fread($file,$size);
fclose($file);
$row = 1;
$data_imported = 0;
$file3 = fopen($csvfile,"r");
$total_file_count = (count(file(FCPATH."/".$csvfile)) - 2);
$i = 0;
$insert = "INSERT IGNORE INTO `invoice`
(`row1`,
.
.
to
.
.
`row33`
) VALUES ";
while($datas = fgetcsv($file3, 10000, ","))
{
$i++;
ob_implicit_flush(true);
if($row == 1)
{
// Ignore 1st line
}
else
{
$row1 = isset($datas[0]) ? $datas[0] : "";
.
.
to
.
.
$row33 = isset($datas[32]) ? $datas[32] : "";
if($i == 200 OR $total_file_count == $data_imported)
{
$insert .= "(
'".mysqli_real_escape_string($this->db->conn_id(),$row1)."',
.
.
to
.
.
'".mysqli_real_escape_string($this->db->conn_id(),$row33)."'
);";
}
else
{
$insert .= "(
'".mysqli_real_escape_string($this->db->conn_id(),$row1)."',
.
.
to
.
.
'".mysqli_real_escape_string($this->db->conn_id(),$row33)."'
),";
}
if($i == 200 OR $total_file_count == $data_imported)
{
$this->QModel->query($insert);
$i=0;
$insert = "INSERT IGNORE INTO `invoice`
(`row1`,
.
.
to
.
.
`row33`
) VALUES ";
}
$data_imported++;
}
$row++;
}
fclose($file3);
echo "Success imported ".number_format($data_imported)." data.";
Any ideas?
Thank you.

Running MySQL queries in specific order

I wonder if someone could advise me here. I have a page where I am updating information in a database, from the previous page I post any new images (with a caption too) and I have a checkbox for deleting images. On the processing page I have the following code:
<?php
session_start();
$dbhost = 'removed';
$dbuser = 'removed';
$dbpass = 'removed';
$dbname = 'removed';
function reArrayFiles($file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
try {
$dbo = new PDO('mysql:host=localhost;dbname='.$dbname, $dbuser, $dbpass);
}catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$query="SELECT * FROM `soldier_info` WHERE `soldier_id` = " . $_POST['soldier_id'] ;
foreach ($dbo->query($query) as $row) {
$soldier_pre_images = explode(",", $row['soldier_images']);
}
if($_POST['deletephoto']){
$imagestodelete=$row['soldier_images'];
$captionstodelete=$row['soldier_images_captions'];
foreach($_POST['deletephoto'] as $todelete){
$deleteexplode = explode("--",$todelete);
echo $deleteexplode;
$deleteexplodepath = $deleteexplode[0];
$deletecaption=$deleteexplode[1];
$imagesafterdelete= str_replace($deleteexplodepath.",","",$imagestodelete);
echo $imagesafterdelete;
$captionsafterdelete = str_replace($deletecaption."--","",$captionstodelete);
echo $captionsafterdelete;
$unlinkpath = str_replace('site url','..',$deleteexplodepath);
unlink($unlinkpath);
}
try {
$dbo = new PDO('mysql:host=localhost;dbname='.$dbname, $dbuser, $dbpass);
$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$q = $dbo->prepare("UPDATE `soldier_info` SET `soldier_images`= :image, `soldier_images_captions`= :captions WHERE `soldier_id`= :id");
$q->execute(array(":image" => $imagesafterdelete, ":captions" => $captionsafterdelete, ":id" => $_POST['soldier_id']));
}catch (PDOException $e) {
$db_error = "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
if ($_FILES['photo']) {
$file_ary = reArrayFiles($_FILES['photo']);
$capcount = 0;
foreach ($file_ary as $file) {
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $file["name"]);
$extension = end($temp);
if ((($file["type"] == "image/gif")||($file["type"] == "image/jpeg")||($file["type"] == "image/jpg")||($file["type"] == "image/pjpeg")||($file["type"] == "image/x-png")||($file["type"] == "image/png"))&&($file["size"] < 9000000) && in_array(strtolower($extension), $allowedExts)) {
if ($file["error"] > 0) {
$file_error = "Return Code: " . $file["error"] . "<br>";
} else {
$newfilename = "../assets/uploads/images/" . $_POST['soldier_id'] . "/" . $file["name"];
$file_fullname = "site urlv/assets/uploads/images/" . $_POST['soldier_id'] . "/" . $file["name"];
$new_caption = $_POST['image_captions'][$capcount];
if (file_exists($newfilename)) {
$file_exists = $file["name"] . " already exists. ";
} else {
if(is_dir("../assets/uploads/images/" . $_POST['soldier_id'])){
move_uploaded_file($file["tmp_name"],$newfilename);
if (strlen($uploaded_images)>1){
$uploaded_images = $uploaded_images . ",". $file_fullname;
}else{
$uploaded_images = $file_fullname;
}
if (strlen($uploaded_captions)>1){
$uploaded_captions = $uploaded_captions . "--". $new_caption;
}else{
$uploaded_captions = $new_caption;
}
}else{
mkdir("../assets/uploads/images/" . $_POST['soldier_id'], 0777, true);
move_uploaded_file($file["tmp_name"],$newfilename);
if (strlen($uploaded_images)>1){
$uploaded_images = $uploaded_images . ",". $file_fullname;
}else{
$uploaded_images = $file_fullname;
}
if (strlen($uploaded_captions)>1){
$uploaded_captions = $uploaded_captions . "--". $new_caption;
}else{
$uploaded_captions = $new_caption;
}
}
}
if (strlen($row['soldier_images'])>1){
$uploaded_images = $row['soldier_images'] . ",". $uploaded_images;
}else{
$uploaded_images = $uploaded_images;
}
}
} else {
$file_invalid = "The file is not a jpg/gif/png file, or is larger than 20mb. Please try again.";
}
$capcount = $capcount+1;
}
try {
$dbo = new PDO('mysql:host=localhost;dbname='.$dbname, $dbuser, $dbpass);
$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$q = $dbo->prepare("UPDATE `soldier_info` SET `soldier_images`= :image, `soldier_images_captions`= :captions WHERE `soldier_id`= :id");
$q->execute(array(":image" => $uploaded_images, ":captions" => $uploaded_captions, ":id" => $_POST['soldier_id']));
}catch (PDOException $e) {
$db_error = "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
$query="SELECT * FROM `soldier_info` WHERE `soldier_id` = " . $_POST['soldier_id'] ;
foreach ($dbo->query($query) as $row) {
$firstname = $row['firstname'];
$surname = $row['surname'];
$yearofbirth = $row['yearofbirth'];
$dateofdeath = date("d/m/Y", strtotime($row['dateofdeath']));
$ageatdeath = $row['ageatdeath'];
$regiment = $row['regiment'];
$battallion_brigade = $row['battallion_brigade'];
$Coybty = $row['Coy/bty'];
$rank = $row['rank'];
$solider_number = $row['soldier_number'];
$Next_of_Kin = $row['Next_of_Kin'];
$CWGC = $row['CWGC'];
$Place_Died = $row['Place_Died'];
$Connection_to_Wymeswold = $row['Connection_to_Wymeswold'];
$Cemetery = $row['Cemetery'];
$LRoH = $row['LRoH'];
$Grave = $row['Grave'];
$Memorial = $row['Memorial'];
$Pier_Face = $row['Pier_Face'];
$Other_Mem = $row['Other_Mem'];
$Other_Details = $row['Other_Details'];
$soldier_images = explode(",", $row['soldier_images']);
$soldier_images_captions = explode("--", $row['soldier_images_captions']);
}
$dbo = null;
?>
This isn't a live site right now and is in testing/dev. However the issue I am seeing is that, all the queries are running, but the page loads up as though the select has run first (by this I mean that the records returned are those from before the updates as processed. Can I force this select to run last so that it gets the latest records?
I think you get the 'original' data on the last select because you are running the queries on different connections. Hence they will live in isolated transactions, that might not be properly committed when the last select runs.
If you run them all in the same PDO object I think it will work.
(If you take POST parameters and concatenate them into SQL your server will be hacked. It's just a matter of time and you have the URL here for everyone to see.)

Categories