PHP file not pulling in .txt files anymore - php

I have a func.php file that grabs three .txt files from my server and inputs the data into a table in a MySQL database. I recently upgraded my PHP to 5.4 from 5.3 and this has caused an issue where it doesn't pull in the .txt files anymore but just deletes the table. In the update_training_db function, it runs empty_table but not move_file and load_csv. This code was working in 5.3 but I am not sure why it isn't grabbing the text files anymore. Can anyone help?
The whole PHP script consists of 4 functions as seen in the whole code. empty_table, move_file, load_csv, and update_training_db to execute everything.
The Problem:
function update_training_db($dbt){
empty_table($dbt, 'customers');
move_file('/training/TrainingCustomerList.txt');
load_csv($dbt, '/training/TrainingCustomerList.txt', 'customers');
}
Whole file:
<?php
header('Content-Type: application/json; charset=UTF-8');
$argv = $_SERVER['argv'];
$totalArgv = count($argv);
// Use PDO to connect to the DB
$dsn_training = 'mysql:dbname=training;host=127.0.0.1';
$user = 'training';
$password = 'training';
try {
$dbt = new PDO($dsn_training, $user, $password);
$dbt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo 'Connected to SQL Server';
}
function empty_table($dbconn, $tablename){
try{
$sql = "TRUNCATE TABLE " . $tablename;
$sth = $dbconn->prepare($sql);
//$sth->bindParam(':tablename', $tablename, PDO::PARAM_STR);
// The row is actually inserted here
$sth->execute();
//echo " [+]Table '" . $tablename . "' has been emptied.<br>";
$sth->closeCursor();
}
catch(PDOException $e) {
die_with_error($e->getMessage());
}
}
function move_file($filename){
$source ="/public_html/b3/" . $filename;
$dest = "/public_html/includes/sfupdate/" . $filename;
if(!copy($source, $dest)){
throw new Exception("Failed to copy file: " . $filename);
}
else{
//echo "Successfully moved $filename.<br>";
}
}
function move_files(){
try {
move_file('training/TrainingCustomerList.txt');
}
catch(Exception $e){
die_with_error($e->getMessage());
}
//sleep(1);
//Return JSON
$return["json"] = json_encode($return);
//echo json_encode($return);
}
function load_csv($dbconn, $filename, $tablename){
try{
$sql = "LOAD DATA LOCAL INFILE '/includes/sfupdate/" . $filename . "' INTO TABLE " . $tablename . " FIELDS TERMINATED BY '\\t' ENCLOSED BY '\"' ESCAPED BY '\\\' LINES TERMINATED BY '\\n'";
$sth = $dbconn->prepare($sql);
// The row is actually inserted here
$sth->execute();
//echo " [+]CSV File for '" . $tablename . "' Table Imported.<br>";
$sth->closeCursor();
}
catch(PDOException $e) {
die_with_error($e->getMessage());
}
}
function update_training_db($dbt){
empty_table($dbt, 'customers');
move_file('/training/TrainingCustomerList.txt');
load_csv($dbt, '/training/TrainingCustomerList.txt', 'customers');
}

Related

PHP 7.x SQLITE3 PDO - is the execute() closing the PDO connection?

I have this code that works weird with SQLITE3 , since the same code with MYSQL works fine
The issue is the line commented with "ISSUE" at line #31, because with MYSQL/MariaDB that "re connection" is NOT needed
Now I better explain
If the IF routine is not entered, I have NO error
If the IF routine is processed, line #34 throws
Uncaught Error: Call to undefined method PDOStatement::prepare()
like if the $PDO-execute(); inside the IF is destroying the PDO istance
You may say, well, no problem, now you have fixed it ... yes, but I'd like to understand why this happen.
Also portability is a point. If this is PDO ... except for the connection, the rest of the script should work and moved among various supported PDO DBs
Thank you if you kindly hint what is the reason and what is it
<?php
// Create or open a database file
$PDO = new PDO('sqlite:myDatabase.sqlite3');
if( isset($_POST['NoteUpdateText']) && !empty(trim($_POST['NoteUpdateText'])) ){
//$testo = $_POST['NoteUpdateText'];
try {
$PDO = $PDO->prepare('UPDATE ajax SET testo = :testo WHERE id = :id');
$PDO->bindValue(':testo', $_POST['NoteUpdateText']);
$PDO->bindValue(':id', 1);
$PDO->execute();
// echo a message to say the UPDATE succeeded
//echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
}
// In EVERY case, load the actual DB record and return it to javascript
$PDO = new PDO('sqlite:myDatabase.sqlite3'); // --- ISSUE, theoretically this is already opened at line #3 ---
try {
$PDO = $PDO->prepare('SELECT testo FROM ajax WHERE id=1 LIMIT 1');
$PDO->execute();
$row = $PDO->fetch();
//var_dump($row);
echo $row["testo"];
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
?>
FIXED CODE
<?php
//include 'db-con2.php';
// table: ajax
// col: testo
// Create or open a database file
$PDO = new PDO('sqlite:myDatabase.sqlite3');
if( isset($_POST['NoteUpdateText']) && !empty(trim($_POST['NoteUpdateText'])) ){
//$testo = $_POST['NoteUpdateText'];
try {
$statement = $PDO->prepare('UPDATE ajax SET testo = :testo WHERE id = :id');
$statement->bindValue(':testo', $_POST['NoteUpdateText']);
$statement->bindValue(':id', 1);
$statement->execute();
// echo a message to say the UPDATE succeeded
//echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e)
{
echo $sql . "<br> - IF -" . $e->getMessage();
}
}
// carica da DB in ogni caso per caricare il P col testo realmente in DB
//$PDO = new PDO('sqlite:myDatabase.sqlite3');
try {
$statement = $PDO->prepare('SELECT testo FROM ajax WHERE id=1 LIMIT 1');
$statement->execute();
$row = $statement->fetch();
//var_dump($row);
echo $row["testo"];
}
catch(PDOException $e)
{
echo $sql . "<br> - NORMALE - " . $e->getMessage();
}
?>
Why would you override $PDO variable ?
$pdo = new PDO('sqlite:myDatabase.sqlite3');
if( isset($_POST['NoteUpdateText']) && !empty(trim($_POST['NoteUpdateText'])) ){
//$testo = $_POST['NoteUpdateText'];
try {
$stmt = $PDO->prepare('UPDATE ajax SET testo = :testo WHERE id = :id');
if ($stmt->execute(array(':testo'=>$_POST['NoteUpdateText'], ':id' => 1)))
{
// echo a message to say the UPDATE succeeded
//echo $stmt->rowCount() . " records UPDATED successfully";
} else {
// There's error processing updates
// debug
print_r($stmt->errorInfo());
}
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
}
// In EVERY case, load the actual DB record and return it to javascript
// There's no need to redeclare $PDO
// $PDO = new PDO('sqlite:myDatabase.sqlite3'); // --- ISSUE, theoretically this is already opened at line #3 ---
try {
$stmt = $pdo->prepare("SELECT testo FROM ajax WHERE id=1 LIMIT 1"); // line #34
$stmt->execute();
$row = $stmt->fetch();
//var_dump($row);
echo $row["testo"];
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}

PHP PDO return a empty array the next day

I use php with PDO to manage a database with mysql. When I run the server I can read and insert data in the tables of my database, everything is correct. But, the next day I use my script, my code return a empty Array when I read and don't insert any data. Furthermore, my script don't throw any exception when does that, and I don't understand why.
I run my database connection with this code:
try {
$this->dataBase = new PDO('mysql:dbname=' . $this->dbName . ';host=' .
$this->host . ';port=' . $this->port,
$this->user, $this->pass);
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
I get the data from my database with the code:
try {
$sql = $this->dataBase->prepare("SELECT username FROM teachers");
$sql->execute();
$result = $sql->fetchAll();
return $result;
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
$this->reconnect();
}
I do something wrong?

PHP file not pulling in my .txt's

I have an admin store dashboard with an update button that triggers a php file which empties a mySQL database that then puts in new data from three .txt files (they are new stores). There is an issue where the table just gets wiped and/or the data from the .txt file is not being sent. I recently upgraded my PHP to 5.4 from 5.3 and am unsure what the issue is. Can anyone recommend me a suggestion on how to fix this issue?
PHP:
<?php
header('Content-Type: application/json; charset=UTF-8');
$argv = $_SERVER['argv'];
$totalArgv = count($argv);
// Use PDO to connect to the DB
$dsn = 'mysql:dbname=busaweb_stores;host=127.0.0.1';
$dsn_training = 'mysql:dbname=busaweb_busaedu;host=127.0.0.1';
$user = 'busaweb_*****';
$password = '*****';
try {
$dbs = new PDO($dsn, $user, $password);
$dbt = new PDO($dsn_training, $user, $password);
$dbs->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo 'Connected to SQL Server';
}
catch (PDOException $e) {
die_with_error('PDO Connection failed: ' . $e->getMessage());
}
//Check request
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "move":
move_files();
echo_success("Files have been moved.");
break;
case "update-stores":
$count = update_stores_db($dbs);
echo_success("DB Updated.<br>" . $count . " Stores Geocoded.");
break;
case "geocode":
$count = geocode_remaining($dbs);
echo_success($count . " stores geocoded.");
break;
case "update-training":
update_training_db($dbt);
echo_success("Training DB Updated.");
break;
case "update-all":
$count = update_stores_db($dbs);
update_training_db($dbt);
echo_success("DB Updated.<br>" . $count . " Stores Geocoded.");
break;
case "backup":
$backupFile = backup_db();
echo_success("DB Backed Up: <br>" . $backupFile);
break;
default:
//Close PDO Connections
$dbs = null;
$dbt = null;
break;
}
}
}
//if being executed from the shell, update all
else if($totalArgv > 0){
$count = update_stores_db($dbs);
update_training_db($dbt);
echo_success("DB Updated.<br>" . $count . " Stores Geocoded.");
break;
};
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
//Error handling
function die_with_error($error) {
$return = array(
"status" => "Failed",
"data" => $error
);
//Close PDO Connections
$dbs = null;
$dbt = null;
die(json_encode($return));
}
function echo_success($message){
$return = array(
"status" => "OK",
"data" => $message
);
$return["json"] = json_encode($return);
echo json_encode($return);
//Close PDO Connections
$dbs = null;
$dbt = null;
}
//Move all files
function move_files(){
try {
move_file('sfinder/StoreList.txt');
move_file('sfinder/StoreProductIndex.txt');
move_file('sfinder/StoreTypeIndex.txt');
move_file('training/TrainingCustomerList.txt');
}
catch(Exception $e){
die_with_error($e->getMessage());
}
//sleep(1);
//Return JSON
$return["json"] = json_encode($return);
echo json_encode($return);
}
//Move a file
function move_file($filename){
$source ="/home/busaweb/public_html/b3/" . $filename;
$dest = "/home/busaweb/public_html/adminportal/includes/sfupdate/" . $filename;
if(!copy($source, $dest)){
throw new Exception("Failed to copy file: " . $filename);
}
else{
//echo "Successfully moved $filename.<br>";
}
}
//Empty a SQL Table
function empty_table($dbconnection, $tablename){
try{
$sql = "TRUNCATE TABLE " . $tablename;
$sth = $dbconnection->prepare($sql);
//$sth->bindParam(':tablename', $tablename, PDO::PARAM_STR);
// The row is actually inserted here
$sth->execute();
//echo " [+]Table '" . $tablename . "' has been emptied.<br>";
$sth->closeCursor();
}
catch(PDOException $e) {
die_with_error($e->getMessage());
}
}
//Import CSV file from JDE to DB
function load_csv($dbconn, $filename, $tablename){
try{
$sql = "LOAD DATA LOCAL INFILE '/home/busaweb/public_html/adminportal/includes/sfupdate/" . $filename . "' INTO TABLE " . $tablename . " FIELDS TERMINATED BY '\\t' ENCLOSED BY '\"' ESCAPED BY '\\\' LINES TERMINATED BY '\\n'";
$sth = $dbconn->prepare($sql);
// The row is actually inserted here
$sth->execute();
//echo " [+]CSV File for '" . $tablename . "' Table Imported.<br>";
$sth->closeCursor();
}
catch(PDOException $e) {
die_with_error($e->getMessage());
}
}
function update_stores_db($dbs){
move_files();
empty_table($dbs, "stores");
load_csv($dbs, 'sfinder/StoreList.txt', 'stores');
empty_table($dbs, 'stores_product_type_link');
load_csv($dbs, 'sfinder/StoreProductIndex.txt', 'stores_product_type_link');
empty_table($dbs, 'stores_store_type_link');
load_csv($dbs, 'sfinder/StoreTypeIndex.txt', 'stores_store_type_link');
return $count;
}
function update_training_db($dbt){
move_file('training/TrainingCustomerList.txt');
empty_table($dbt, 'customers');
load_csv($dbt, 'training/TrainingCustomerList.txt', 'customers');
}
}
?>

php - Add Script Not working

I'm having a problem with my update script. Basically I enter values into textboxes and when I click on 'Add' these values get added to the database.
At the moment it is allowing me to enter intergers and these getting added to the database but when I try to add text it doesn't. The database field types are set to varchar(20) and this is my PHP code:
public function insert($tableName,$fieldArray,$fieldValues) {
$pdo = new SQL();
$dbh = $pdo->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);
$this->sql = "INSERT INTO " . $tableName . " (".implode(',', $fieldArray).") VALUES (".implode(',', $fieldValues).")";
try {
// Query
$stmt = $dbh->prepare($this->sql);
$stmt->execute();
$count = $stmt->rowCount();
echo $count.' row(s) inserted by SQL: '.$stmt->queryString;
$stmt->closeCursor();
}
catch (PDOException $pe) {
echo 'Error: ' .$pe->getMessage(). 'SQL: '.$stmt->queryString;
die();
}
// Close connection
$dbh = null;
}
Please let me know what I am doing wrong! :)
Change the sql query line to:
$this->sql = "INSERT INTO " . $tableName . " (`".implode('`, `', $fieldArray)."`) VALUES ('".implode("', '", $fieldValues) . "')";
The thing is you are not escaping strings with quotes. Like 'someText'
You need to enclose your fields into quotes.
Put the text as such
$text = "text"; //How you're doing it now
$text = "'text'"; //How you ought to (after sql escaping)
Or try this:
$this->sql = "INSERT INTO " . $tableName . " (`".implode('`,`', $fieldArray)."`) VALUES ('".implode("','", $fieldValues)."')";

PDO insert from one DB to another

I am trying to use PDO to read a SQLite DB and then insert into MYSQL.
The read is working and in the foreach I can echo out the SQLite data BUT when it comes to inserting into the new DB nothing logged and no data inserted at all.
try
{
$db = new PDO('sqlite:' . $passedFile);
$dbup = new PDO("mysql:host=localhost;port=8889;dbname=TestDB", "dbuser", "password");
//select all lines from the sqlite DB
$result = $db->query('SELECT * FROM TestDB');
foreach($result as $row)
{
$dbup->exec("INSERT INTO TestDB ('field1','field2','field3') VALUES ('" . $row['field1'] . "','" . $row['field2'] . "','" .$row['field3'] . "')");
}
// close the database connection
$db = NULL;
$dbup = NULL;
}
catch(PDOException $e)
{
print 'Exception : '.$e->getMessage();
}
As idea, instead of using $dbup->exec($mysqlQuery)
try $dbup->exec($mysqlQuery) or die(print_r($dbup->errorInfo(), true));

Categories