PHP file not pulling in my .txt's - php

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');
}
}
?>

Related

Create my oracle oci class in php. But data show 1 first record only

This code from my PHP Project.
and create oracle connection class.
modified from mysql connection class(work fine).
class databaseOracle
{
public $oci;
public $connected = false;
public $parameters;
public $result;
function __construct($host, $dbPort, $dbName, $userDB, $passwordDB)
{
try {
$ociDB = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = " . $host . ")(PORT = " . $dbPort . ")))(CONNECT_DATA=(SID=" . $dbName . ")))";
$this->oci = oci_connect($userDB, $passwordDB, $ociDB, 'AL32UTF8');
if (!$this->oci) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
echo "Database oracle connection Failed.</br>";
exit();
} else {
echo "Database oracle connection success.</br>";
}
} catch (EngineExcpetion $e) {
echo "Error : " . $e->getMessage() . "</br>";
}
// exit();
}
public function bind($para, $value)
{
$this->parameters[count($this->parameters)] = ":" . $para . "\x7F" . $value;
}
public function bindParams($parray)
{
if (empty($this->parameters) && is_array($parray)) {
$columns = array_keys($parray);
foreach ($columns as $i => &$column) {
$this->bind($column, $parray[$column]);
}
}
}
public function queryString($showQuery = 0, $query = "", $parameters = "")
{
$this->result = null;
if ($showQuery == 1) {
require_once('SQLFormatter.php');
echo SqlFormatter::format($query);
var_dump($parameters);
}
$this->result = oci_parse($this->oci, $query);
# Add parameters to the parameter array
$this->bindParams($parameters);
# Bind parameters
if (!empty($this->parameters)) {
foreach ($this->parameters as $param) {
$parameters = explode("\x7F", $param);
oci_bind_by_name($this->result, $parameters[0], $parameters[1]);
}
}
oci_execute($this->result);
$r = oci_fetch_array($this->result, OCI_ASSOC + OCI_RETURN_LOBS + OCI_RETURN_NULLS);
$this->parameters = array();
return $r;
}
}
$oracleDB = new databaseOracle($ociHost, $ociPort, $ociDB, $ociUsername, $ociPassword);
$query = $oracleDB->queryString(0,"SELECT * from SOME_TABLE where CREATED_BY = :created FETCH NEXT 50 ROWS ONLY",array("created" => "2"));
print_r($query);
my problem
i'm create class of oracle connection. modify from mysql connection class.
it's can query and read record from oracle database. example 50 record
but array result of query show first row only.

Socket programming with PHP and insert data to the database (continuous)

I have multiple gps devices. I cannot make changes to this device. It sends data to a port.
I break this incoming data and insert it to the database according to its type. But sometimes I have problems. Device sometimes sends id_number field blank. It sends all other data correctly. And sometimes the program just crashes.
<?php
set_time_limit (0);
$ip_address = "xxx.xxx.xxx.xxx";
$port = "yyy";
$server = stream_socket_server("tcp://$ip_address:$port", $errno, $errorMessage);
if ($server === false) {
die("stream_socket_server error: $errorMessage");
}
$client_sockets = array();
while (true) {
// prepare readable sockets
$read_sockets = $client_sockets;
$read_sockets[] = $server;
// start reading and use a large timeout
if(!stream_select($read_sockets, $write, $except, 300000)) {
die('stream_select error.');
}
// new client
if(in_array($server, $read_sockets)) {
$new_client = stream_socket_accept($server);
if ($new_client) {
//print remote client information, ip and port number
//echo 'new connection: ' . stream_socket_get_name($new_client, true) . "\n";
$client_sockets[] = $new_client;
//echo "total clients: ". count($client_sockets) . "\n";
// $output = "hello new client.\n";
// fwrite($new_client, $output);
}
//delete the server socket from the read sockets
unset($read_sockets[ array_search($server, $read_sockets) ]);
}
// message from existing client
foreach ($read_sockets as $socket) {
$data = fread($socket, 2048);
echo "data: " . $data . "\n";
if($data[0]=='$') {
write_file($data);
$explp = array();
$explp = explode("#",$data);
$i=0;
$j=count($explp);
while ($i < ($j-1)){
$listexa= explode(";",$explp[$i]);
$location= explode(",",$listexa[0]);
$response = "";
$id_number = $location[2];
$package_type = substr($location[0],1);
if ($package_type == 'DATA')
{
$lati = substr($listexa[2],1);
$longi = substr($listexa[3],2);
$speed = $listexa[4];
if(count($speed)>2)
data_package($id_number,$package_no,'DATA');
}
else if($package_type=='GEOLOC')
{
$lati = substr($listexa[3],1);
$longi = substr($listexa[4],2);
$speed = $listexa[5];
if($location[3]=='-' || $location[3]=='2' || $location[3]=='R')
{
$speed= '0';
$package_type = 'GEO';
geo_package($id_number,$package_no,$package_type);
}
}
else if($package_type=='ALIVE')
{
alive_package($package_no,$id_number);
}
$i = $i+1;
}
if (!$data) {
unset($client_sockets[ array_search($socket, $client_sockets) ]);
#fclose($socket);
//echo "client disconnected. total clients: ". count($client_sockets) . "\n";
continue;
}
//send the message back to client
if (sizeof($response) > 0) {
fwrite($socket, $response);
}
}
} }
function alive_package($package_no,$id_number){
$link=dbcon();
try{
$statement = $link->prepare('INSERT INTO alive_packages (package_no, id_number)
VALUES (:package_no, :id_number)');
$statement->execute([
'package_no' => $package_no,
'id_number' => $id_number,
]);
}
catch (PDOException $e) {
echo "DataBase Error: The user could not be added.<br>".$e->getMessage(); write_file_log($e->getMessage());
$link = null;
} catch (Exception $e) {
echo "General Error: The user could not be added.<br>".$e->getMessage(); write_file_log($e->getMessage());
$link = null;
}
$link = null;
}
function data_package($id_number,$package_no,$package_type){
$link=dbcon();
$typee= '-';
try{
$statement = $link->prepare('INSERT INTO data_package (id_number, package_no, package_type)
VALUES (:id_number, :package_no, :package_type)');
$statement->execute([
'id_number' => $id_number,
'package_no' => $package_no,
'package_type' => $package_type,
]);
}
catch (PDOException $e) {
echo "DataBase Error: The user could not be added.<br> ".$e->getMessage(); write_file_log($e->getMessage());
$link = null;
} catch (Exception $e) {
echo "General Error: The user could not be added.<br> ".$e->getMessage(); write_file_log($e->getMessage());
$link = null;
}
$link = null;
}
function geo_package($id_number,$package_no,$package_type){
$link=dbcon();
$typee= '-';
try{
$statement = $link->prepare('INSERT INTO geo_package (id_number,package_no,package_type)
VALUES (:id_number, :package_no, :package_type)');
$statement->execute([
'id_number' => $id_number,
'package_no' => $package_no,
'package_type' => $package_type,
]);
}
catch (PDOException $e) {
echo "DataBase Error: The user could not be added.<br> ".$e->getMessage(); write_file_log($e->getMessage());
$link = null;
} catch (Exception $e) {
echo "General Error: The user could not be added.<br> ".$e->getMessage(); write_file_log($e->getMessage());
$link = null;
}
$link = null;
}
function dbcon(){
$dbhost = '127.0.0.1';
$dbname = 'examplename';
$dbusername = 'exampleuser';
$dbpassword = 'examplepassword';
$link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $link;
}
function write_file($data){
$filename = "xxx.txt";
$file = fopen( $filename, "a+" );
fwrite( $file, $data."\n" );
fclose( $file );
}
function write_file_log($data){
$filename = "yyy.txt";
$file = fopen( $filename, "a+" );
fwrite( $file, $data."\n" );
fclose( $file );
}
I want it to run 24/7 and only restart that socket when something goes wrong. Or I want to take the id_number field of a device once and use it over and over again. Since there are more than one device, a separate socket is opened for each one. But when the id_number of a device is empty, I cannot insert the data to the database. How can I solve this problem?
Briefly, while a socket sends data normally, after a while it starts to send blank id_number and I lose the data until I restart the program. Other devices continue to work.
I have 2 options.
1st option: restart socket when id_number is empty.
2nd option: restart socket when id_number is empty.
But I don't know how to do these.
An additional problem or shortcut is to run the code again when an error occurs in the program. How can I do that?
Note: I am running a php program with a service in Centos 7.

Problem when Handling repeated error values on php and mysql

I have a PHP program that connect to a MariaDB databse.
I upload name as "numbers" and i defined the value as UNIQUE so I donĀ“t want to be repeatated.
However I would like to handle the error when a vlaue is repeated:
This is the table I created:
Table in MariaDB
create table test(
-> id int NOT NULL AUTO_INCREMENT,
-> name varchar(255) UNIQUE,
-> date DATE NOT NULL,
-> PRIMARY KEY (id)
-> );
This is the script in PHP:
$host = "localhost";
$db_name = "xxx";
$username = "xxx";
$password = "xxx";
$connection = null;
$dt1=date("Y-m-d");
try{
$connection = new PDO("mysql:host=" . $host . ";dbname=" . $db_name, $username, $password);
$connection->exec("set names utf8");
}
catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
function saveData($name, $dt1){
global $connection;
$query = "INSERT INTO test(name, date) VALUES( :name, :date )";
$callToDb = $connection->prepare( $query );
$name=htmlspecialchars(strip_tags($name));
//$dt1=htmlspecialchars(strip_tags($dt1));
$callToDb->bindParam(":name", $name);
$callToDb->bindParam(":date", $dt1);
if($callToDb->execute()){
//return '<h3 style="text-align:center;">registration submmited!</h3>';
//if (!$callToDb->execute()) {
// if ($callToDb->errno == 1062) {
// return '<h3 style="text-align:center;">VALUE REPEATED!</h3>';
// }
// else{
return '<h3 style="text-align:center;">registration submmited!</h3>';
// }
}
}
if( isset($_POST['submit'])) {
$name = htmlentities($_POST['name']);
$dt1 = htmlentities($_POST['date']);
//then you can use them in a PHP function.
$result = saveData($name, $dt1);
echo $result;
}
else{
echo '<h3 style="text-align:center;">A very detailed error message</h3>';
}
//header("location:javascript://history.go(-1)");
}
the code part after if($callToDb->execute()){ it is commented because it is not working but I would like to just show a message when the vlaue is repeated. The same than when a vlaue is registrated correctly.
The issue to handle duplicate error is in this part which at the moment I am not using in my code as is not working fine:
if (!$callToDb->execute()) {
if ($callToDb->errno == 1062) {
return '<h3 style="text-align:center;">VALUE REPEATED!</h3>';
}
else{
return '<h3 style="text-align:center;">registration submmited!</h3>';
}
}
Any idea why this part of the code it is not working?
Change your code with this one.
$affected_rows = $callToDb->rowCount();
if (!$callToDb->execute())
{
if ($affected_rows == 0)
{
return '<h3 style="text-align:center;">VALUE REPEATED!</h3>';
}
else
{
return '<h3 style="text-align:center;">registration submmited!</h3>';
}
}

php with pdo, create dynamic database connection

I create connection with this statement
dbh = new PDO('mysql:host=localhost;dbname=mydb;port=3306;connect_timeout=15', 'root', '');
But in my application users capable to change data sources so I need to create current database connection with server informations user posted, I try this:
dbh = new PDO('sqlsrv:server=' + $result["servername"] + ';dbname=' + $result["dbname"] + ';port=3306;connect_timeout=15', '' + $result["user"] + '', '' + $result["password"] + '');`
But it failed. Even I tried the simple code examples got documents it fails for that too.. Whats with it and how can I make it ?
At first, you cant merge strings with '+'. you must use '.' and you need to create new PDO connection object(or set it existing) for each database connection here I share parts of my code doing this:
private function __construct()
{
//default database connection
$this->dbh = new PDO('mysql:host=localhost;dbname=webfilter;port=3306;connect_timeout=15', 'root', '');
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$this->directed = false;
$this->resultBool = true;
}
public static function getConnection()
{
$sqlstring = "select * from datasources WHERE ACTIVE =1";
if (!isset(self::$instance))
{
$object = __CLASS__;
self::$instance = new $object;
}
if (true) {
$request = self::$instance->dbh->prepare($sqlstring);
if ($request->execute()) {
if ($result = $request->fetch(PDO::FETCH_ASSOC)) {
if ($result["SOFTWARE"] == "mysql") {
self::$instance->dbh = null;
self::$instance->connectedDbName = "mysql(" . $result["DATABASENAME"] . ")";
self::$instance->dbh = new PDO('mysql:host=' . $result["SERVERADDRESS"] . ';dbname=' . $result["DATABASENAME"] . ';port=3306;connect_timeout=15', '' . $result["USERNAME"] . '', '' . $result["PASSWORD"] . '');
self::$instance->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
self::$instance->directed = true;
self::$instance->resultBool = true;
} else if ($result["SOFTWARE"] == "mssql") {
self::$instance->dbh = null;//close the existing connection
self::$instance->connectedDbName = "mssql(" . $result["DATABASENAME"] . ")";
self::$instance->dbh = new PDO('sqlsrv:server=' . $result["SERVERADDRESS"] . ';Database=' . $result["DATABASENAME"] . '', '' . $result["USERNAME"] . '', '' . $result["PASSWORD"] . '');
self::$instance->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
self::$instance->dbh->query("use " . $result["DATABASENAME"]);
self::$instance->directed = true;
self::$instance->resultBool = true;
} else if ($result["SOFTWARE"] == "oracle") {
self::$instance->connectedDbName = "oracle(" . $result["DATABASENAME"] . ")";
self::$instance->dbh = new PDO('odbc:DRIVER=FreeTDS;server=localhost;Database=Dbname', 'username', '!123qwe');
}
self::$instance->resultBool = true;
$temp = self::$instance->dbh->query("select DEVICEID from ethernet LIMIT 1");
self::$instance->setDeviceid($temp->fetchColumn());
return self::$instance;
}
self::$instance->connectedDbName = "default";
$temp = self::$instance->dbh->query("select DEVICEID from ethernet LIMIT 1");
self::$instance->setDeviceid($temp->fetchColumn());
return self::$instance;
}
}
self::$instance->connectedDbName = "default";
return self::$instance;
}
public function getConnectionStatusMessage()
{
if ($this->resultBool) {
return "Connection Successfull" . $this->connectedDbName;
} else {
return "Connection Failed:" . $this->resultString;
}
}
$dbh = new PDO('sqlsrv:server=' . $result["servername"] . ';dbname=' . $result["dbname"] . ';port=3306;connect_timeout=15', $result["user"], $result["password"]);

PHP file not pulling in .txt files anymore

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

Categories