Running MySQL queries in specific order - php

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.)

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");

Trying to get property of non-object CRUD

I am making a CRUD system for blog publications, but it's kinda strange, another developer (with more experience) looked to my coded and for him it's all right too, but this error (Notice: Trying to get property of non-object in C:\xampp\htdocs\genial\painel\inc\database.php on line 32) remains appearing.
My database code:
<?php
mysqli_report(MYSQLI_REPORT_STRICT);
function open_database() {
try {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
return $conn;
} catch (Exception $e) {
echo $e->getMessage();
return null;
}
}
function close_database($conn) {
try {
mysqli_close($conn);
} catch (Exception $e) {
echo $e->getMessage();
}
}
function find( $table = null, $id = null ) {
$database = open_database();
$found = null;
try {
if ($id) {
$sql = "SELECT * FROM" . $table . " WHERE id = " . $id;
$result = $database->query($sql);
if ($result->num_rows > 0) {
$found = $result->fetch_assoc();
}
}
else {
$sql = "SELECT * FROM " . $table;
$result = $database->query($sql);
if ($result->num_rows > 0) {
$found = $result->fetch_all(MYSQLI_ASSOC);
}
}
} catch (Exception $e) {
$_SESSION['message'] = $e->GetMessage();
$_SESSION['type'] = 'danger';
}
close_database($database);
return $found;
}
function find_all( $table ) {
return find($table);
}
function save($table = null, $data = null) {
$database = open_database();
$columns = null;
$values = null;
//print_r($data);
foreach ($data as $key => $value) {
$columns .= trim($key, "'") . ",";
$values .= "'$value',";
}
$columns = rtrim($columns, ',');
$values = rtrim($values, ',');
$sql = "INSERT INTO " . $table . "($columns)" . " VALUES " ($values);";
try {
$database->query($sql);
$_SESSION['message'] = 'Registro cadastrado com sucesso.';
$_SESSION['type'] = 'success';
} catch (Exception $e) {
$_SESSION['message'] = 'Nao foi possivel realizar a operacao.';
$_SESSION['type'] = 'danger';
}
close_database($database);
}
function update($table = null, $id = 0, $data = null) {
$database = open_database();
$items = null;
foreach ($data as $key => $value) {
$items .= trim($key, "'") . "='$value',";
}
$items = rtrim($items, ',');
$sql = "UPDATE " . $table;
$sql .= " SET $items";
$sql .= " WHERE id=" . $id . ";";
try {
$database->query($sql);
$_SESSION['message'] = 'Registro atualizado com sucesso.';
$_SESSION['type'] = 'success';
}
catch (Exception $e) {
$_SESSION['message'] = 'Nao foi possivel realizar a operacao.';
$_SESSION['type'] = 'danger';
}
close_database($database);
}
Sorry if it's not right idled.
I put an space on the code after the "FROM" at
$sql = "SELECT * FROM" . $table . " WHERE id = " . $id;
The error remains the same but know on line 36 that is:
if ($result->num_rows > 0) {
$found = $result->fetch_all(MYSQLI_ASSOC);
}
Turned the code on line 36 to:
$if (result = $database->query($sql)) {
The error disappeared, others problems not relative to this question happened.
Just in case this question isn't closed as off-topic -> typo generated, I'd better provide an acceptable answer.
Add a space between FROM and $table in your SELECT query.
Check for a non-false result from your query.
Your new code could look like this:
$sql = "SELECT * FROM `$table`";
if ($id) {
// assuming id has been properly sanitized
$sql .= " WHERE id=$id"; // concatenate with WHERE clause when appropriate
}
if ($result = $database->query($sql)) { // only continue if result isn't false
if ($result->num_rows) { // only continue if one or more row
$found = $result->fetch_all(MYSQLI_ASSOC); // fetch all regardless of 1 or more
}
}
$sql = "INSERT INTO " . $table . "($columns)" . " VALUES " ($values);"; has too many double quotes in it -- you can tell by how Stack Overflow highlights the characters. I could say that you could clean up the syntax, but it would ultimately be best to scrap your script and implement prepared statements.

PHP Explode and updata data to each colomn in mysql database

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);

Need help cleaning up PHP script

Objective: Take a data entry that contains multiple dates in "$column4" and for each date, create a new entry with $column2, $column3, $column4 and a date followed by one comment.
For this example let's say that:
$column1 is an auto-incrementing primary ID
$column2 = '20141122001';
$column3 = 'something';
$column4 = 'else';
$string = '12/29/2014 2:44PM - working with the lender to remove the mortgage late so we are able to refinance the client. - Person 1 12/04/2014 2:27PM - file suspended until rapid rescore comes back removing late payment from credit. - Person 2';
The example below works for two dates, but how about 1-20 dates? Thanks in advance.
<?php
$host = 'localhost';
$db_user = 'intergl8_james';
$db_pass = 'Interglobalsecure2014';
$db_name = 'intergl8_test';
try {
$pdo = new PDO('mysql:host='.$host.';dbname='.$db_name.'', $db_user, $db_pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('SELECT * FROM test');
$stmt->execute();
$result = $stmt->fetchAll();
if ( count($result) ) {
foreach($result as $row) {
$string = $row[4];
// $column1 = $row[0]; just the ID, don't need to copy
$column2 = $row[1];
$column3 = $row[2];
$column4 = $row[3];
?>
<?php
echo $string . "<br>";
if(preg_match('/(.*)([0-9]{2}\/[0-9]{2}\/[0-9]{2,4})(.*)/', $string, $matches))
{
$date = $matches[2];
}
echo $date;
//////////////////////
if (isset($date)) {
$newstring = str_replace($date,"",$string);
if(preg_match('/(.*)([0-9]{2}\/[0-9]{2}\/[0-9]{2,4})(.*)/', $newstring, $matches))
{
$date2 = $matches[2];
}
}
echo "<br>";
echo $date2;
////////////////
echo "<br>";
$parts = parse_url($string);
$path_parts= explode($date2, $parts[path]);
$user = $path_parts[1];
$user2 = $path_parts[0];
//$user3 = $path_part[2];
echo $date2 . " " . $user . "<br>";
echo $user2 . "<br>";
$newdate = $date2 . " " . $user;
//echo $user3;
?>
<?php
$db_user = 'intergl8_james';
$db_pass = 'Interglobalsecure2014';
try {
$pdo = new PDO('mysql:host=localhost;dbname=intergl8_test', $db_user, $db_pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('INSERT INTO test2 VALUES(:id,:number,:blah,:cool,:notes)');
$stmt->execute(array(
':id' => '', ':number' => $column2, ':blah' => $column3, ':cool' => $column4, 'notes' => $newdate
));
$stmt->execute(array(
':id' => '', ':number' => $column2, ':blah' => $column3, ':cool' => $column4, 'notes' => $user2
));
# Affected Rows?
echo $stmt->rowCount() ." row(s) inserted."; // 1
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
?>
<?php
}
} else {
echo "No rows returned.";
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
UPDATE:
<?php
$host = 'localhost';
$db_user = '';
$db_pass = '';
$db_name = '';
try {
$pdo = new PDO('mysql:host='.$host.';dbname='.$db_name.'', $db_user, $db_pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('SELECT * FROM test');
$stmt->execute();
$result = $stmt->fetchAll();
if ( count($result) ) {
foreach($result as $row) {
$string = $row[4];
// $column1 = $row[0]; just the ID, don't need to copy
$column2 = $row[1];
$column3 = $row[2];
$column4 = $row[3];
?>
<?php
preg_match_all('/(.*)([0-9]{2}\/[0-9]{2}\/[0-9]{2,4})(.*)/', $string, $matches, PREG_SET_ORDER);
foreach ($matches as $val) {
echo "matched: " . $val[0] . "<br>";
/* echo "part 1: " . $val[1] . "<br>";
echo "part 2: " . $val[2] . "<br>";
echo "part 3: " . $val[3] . "<br>";
echo "part 4: " . $val[4] . "<br><br>"; */
// start crazy shit
$db_user = '';
$db_pass = '';
$db_name = '';
try {
$pdo = new PDO('mysql:host=localhost;dbname='..'', $db_user, $db_pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('INSERT INTO test2 VALUES(:id,:number,:blah,:cool,:notes)');
$stmt->execute(array(
':id' => '', ':number' => $column2, ':blah' => $column3, ':cool' => $column4, 'notes' => $val[0]
));
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
// end crazy shit
}
?>
<?php
}
} else {
echo "No rows returned.";
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>

Categories