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.
Related
I have been looking at several php codes trying to find out the problem with my code, and why it wont receive data from post
below is my php code can any one tell me whats up with it
i am trying to send audio data with the name of the audio file through this php file
the php script is supposed to receive the audio file create then audio object and then extract the name and audio part from the file but when i send the data to test it through postman i get 400 error message as i have set it up to indicate error but i do not understand why this is happening
<?php
include_once '../../configration/database.php';
include_once '../../objects/sound.php';
// JWT TOKEN VALIDATION
$data = json_decode(file_get_contents("php://input"));
$database = new Database();
$conn = $database->getConnection();
// CONTROL
$sound = new Sound($conn);
// make sure data is not empty
if (
!is_null($data->$filename)
&& !is_null($data->$extension)
&& !is_null($data->$waveform) )
{
$sound->filename = $data->filename;
$sound->extension = $data->extension;
$sound->waveform = $data->waveform;
// create the product
if ($sound->create_new())
{
http_response_code(200);
}
else
{
http_response_code(503);
echo json_encode(array(
"message" => "Unable to create sound."
));
}
}
else {
http_response_code(400);
echo json_encode(array(
"message" => "Unable to create sound. Data is incomplete."
));
}
?>
the database.php file is as follows
<?php
include_once 'GlobalConfig.php';
class Database
{
public $conn;
public function getConnection(){
$config= new GlobalConfig();
$this->conn = null;
try{
$dsn = "mysql:host={$config->host};port={$config->port};dbname={$config->db_name};charset=utf8";
$this->conn = new PDO($dsn, $config->username, $config->password);
$this->conn->exec("set names utf8");
}catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
public function getConnectionAndValidate($data){
$this->conn = null;
$config= new GlobalConfig();
try{
$dsn = "mysql:host={$config->host};port={$config->port};dbname={$config->db_name};charset=utf8";
$this->conn = new PDO($dsn, $config->username, $config->password);
$this->conn->exec("set names utf8");
}catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
if (!validateToken($data->JWT, $data->UserID, $this->conn)){
http_response_code(401);
echo "Authorization: declined";
exit();
}
return $this->conn;
}
}
THE sound.php FILE IS AS FOLLOWS
<?php
class Sound
{
private $conn;
private $table_name = "";
public $filename;
public $extension;
public $waveform;
public $path;
public function __construct($db)
{
$this->conn = $db;
}
function create_new()
{
$this->path = $this->filename .".". $this->extension;
$myfile = fopen($this->path, "w") or die("Unable to open file!");
fwrite($myfile, $this->waveform);
fclose($myfile);
// $query = " INSERT INTO `tbl_address`
// (`contact_number`,`UserID` ,`billing_street_address`, `billing_city_address`, `billing_state_address`, `billing_country_address`, `billing_zip`,
// `shipping_street_address`, `shipping_city_address`, `shipping_state_address`, `shipping_country_address`, `shipping_zip`)
// VALUES (:contact_number,'$this->user_id', :billing_street_address, :billing_city_address, :billing_state_address, :billing_country_address, :billing_zip,
// :shipping_street_address, :shipping_city_address, :shipping_state_address, :shipping_country_address, :shipping_zip);";
// $stmt = $this->conn->prepare($query);
// $this->contact_number = htmlspecialchars(strip_tags($this->contact_number));
// $this->billing_street_address = htmlspecialchars(strip_tags($this->billing_street_address));
// $this->billing_city_address = htmlspecialchars(strip_tags($this->billing_city_address));
// $this->billing_state_address = htmlspecialchars(strip_tags($this->billing_state_address));
// $this->billing_country_address = htmlspecialchars(strip_tags($this->billing_country_address));
// $this->billing_zip = htmlspecialchars(strip_tags($this->billing_zip));
// $this->shipping_street_address = htmlspecialchars(strip_tags($this->shipping_street_address));
// $this->shipping_city_address = htmlspecialchars(strip_tags($this->shipping_city_address));
// $this->shipping_state_address = htmlspecialchars(strip_tags($this->shipping_state_address));
// $this->shipping_country_address = htmlspecialchars(strip_tags($this->shipping_country_address));
// $this->shipping_zip = htmlspecialchars(strip_tags($this->shipping_zip));
// // bind values
// $stmt->bindParam(":contact_number", $this->contact_number);
// $stmt->bindParam(":billing_street_address", $this->billing_street_address);
// $stmt->bindParam(":billing_city_address", $this->billing_city_address);
// $stmt->bindParam(":billing_state_address", $this->billing_state_address);
// $stmt->bindParam(":billing_country_address", $this->billing_country_address);
// $stmt->bindParam(":billing_zip", $this->billing_zip);
// $stmt->bindParam(":shipping_street_address", $this->shipping_street_address);
// $stmt->bindParam(":shipping_city_address", $this->shipping_city_address);
// $stmt->bindParam(":shipping_state_address", $this->shipping_state_address);
// $stmt->bindParam(":shipping_country_address", $this->shipping_country_address);
// $stmt->bindParam(":shipping_zip", $this->shipping_zip);
// if ($stmt->execute()) {
// $this->address_id = $this->conn->lastInsertId();
// }
// else {
// echo json_encode(array("message" => "Unable to get address."));
// }
}
}
?>
I have a database at local server. I am trying to access this database. I have table of venueTypeMaster in the database. I tried to get all the venuetypes from database. But when I run the script message I get is - 'No database selected'.
I have a class in which I have created two functions in php script. For createVenue it dose not send any message and the query has been executed successfully. But for getVeunueTypes it is showing this message. Connection for both is same.
DB Script:
<?php
include_once("config.php");
include_once("exceptions.php");
class DB {
static $con;
public static function getConnection() {
try {
if ( DB::$con == null ) {
DB::$con = mysqli_connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD);
if ( DB::$con) {
$status = mysqli_select_db(DB::$con,DB_NAME);
if (! $status ) throw new DBSelectionExcpetion(mysqli_error());
return DB::$con;
} else {
$e = new DBConnectionException(mysqli_error());
throw $e;
}
}
return DB::$con;
} catch(DBConnectionException $e) {
throw $e;
} catch(DBSelectionExcpetion $de) {
throw $de;
}
return null;
}
?>
venueTypes script
<?php
include("exceptions.php");
include("DB.php");
include("config.php");
class VenueTypes {
public function getVenueTypes() {
try {
$con = DB::getConnection();
$query = "select * from venueTypeMaster";
$rs = mysql_query($query) or die (json_encode(array("result"=>-1, "message"=>mysql_error())));
$n = mysql_num_rows($rs);
$vt = array();
if ( $n > 0 ) {
while ( $row = mysql_fetch_assoc($rs)) {
$vt[] = $row;
}
$result = array("result"=>1, "message"=>"success", "venueTypes" => $vt);
return json_encode($result);
} else {
$result = array("result"=>-1, "message"=>"Venue types list is empty");
return json_encode($result);
}
} catch(DBConnectionException $e) {
$result = array("result"=>-1, "message"=> $e -> getMessage());
return json_encode($result);
}
return null;
}
public function createVenueType($fields) {
try {
$required = array("venuetype", "active", "entry_by", "entry_date", "entry_time", "last_modify_date", "ip_addr","venue_name");
$actual = array_keys($fields);
$intersection = array_intersect($required, $actual);
$n1 = sizeof($required);
$n2 = sizeof($intersection);
if ( $n1 != $n2 ) {
throw new MissingParameterException();
}
$con = DB::getConnection();
$keys = array_keys($fields);
$values = array_values($fields);
$columns = implode(",", $keys);
$n = sizeof($values);
for($i=0;$i<$n; $i++) {
$values[$i] = "'" . mysqli_real_escape_string($con,$values[$i]) . "'";
}
$columnValues = implode(",", $values);
$query = "insert into venuetypemaster($columns) values($columnValues)";
mysqli_query($con,$query) or die (json_encode(array("result"=>-1, "message"=>mysqli_error())));
$af = mysqli_affected_rows($con);
if ( $af == 1 ) {
$venuetypeId = mysqli_insert_id($con);
$result = array("result"=>1, "message"=>"success", "venuetypeId" => $venuetypeId);
return json_encode($result);
} else {
$result = array("result"=>-1, "message"=>"Failed to register");
return json_encode($result);
}
} catch(DBConnectionException $e) {
$result = array("result"=>-1, "message"=> $e -> getMessage());
return json_encode($result);
}
return null;
}
?>
getVenueType script
<?php
header("Content-type: application/json");
if ( $_SERVER['REQUEST_METHOD']=='GET') {
include_once ("../include/VenueTypes.php");
try {
$v = new VenueTypes();
$response = $v -> getVenueTypes();
//$response is null means something went wrong as a result we got null result from above statement
if ( $response == null ) {
$response = json_encode(array("result" => -2, "message" => "Empty result"));
echo $response;
} else {
echo $response;
}
} catch(Exception $e) {
$result = array("result" => -1, "message" => $e -> getMessage());
echo json_encode($result);
}
} else {
$result = array("result" => -3, "message" => "Unsupported method : " . $_SERVER['REQUEST_METHOD']);
echo json_encode($result);
}
?>
Can anyone help please.. Thank you..
The problem is that you are mixing between the mysqli_xxx() and mysql_xxx() functions. These two libraries are not compatible with each other; you must only use one or the other throughout your code.
Since the mysql_xxx() functions are obsolete and deprecated, that means you should only use mysqli_xxx().
Change all occurrences of mysql_ in your code to mysqli_.
You will also need to make other changes to these lines of code -- notably this will include adding the DB reference variable (ie the variable returned by getConnection()), but some other syntax changes may also be necessary.
I want to make a sendmail function on my program. But first, I want to store the information: send_to, subject, and message in a table in another database(mes) where automail is performed. The problem is data fetched from another database(pqap) are not being added on the table(email_queue) in database(mes).
In this code, I have a table where all databases in the server are stored. I made a query to select a specific database.
$sql5 = "SELECT pl.database, pl.name FROM product_line pl WHERE visible = 1 AND name='PQ AP'";
$dbh = db_connect("mes");
$stmt5 = $dbh->prepare($sql5);
$stmt5->execute();
$data = $stmt5->fetchAll(PDO::FETCH_ASSOC);
$dbh=null;
Then after selecting the database,it has a query for selecting the information in the table on the selected database. Here's the code.
foreach ($data as $row5) GenerateEmail($row5['database'], $row5['name']);
Then this is part (I think) is not working. I don't know what's the problem.
function GenerateEmail($database, $line) {
$sql6 = "SELECT * FROM invalid_invoice WHERE ID=:id6";
$dbh = db_connect($database);
$stmt6 = $dbh->prepare($sql6);
$stmt6->bindParam(':id6', $_POST['idtxt'], PDO::PARAM_INT);
$stmt6->execute();
$data = $stmt6->fetchAll(PDO::FETCH_ASSOC);
$dbh=null;
foreach ($data as $row6) {
$invnumb=$row6['Invoice_Number'];
$partnumb=$row6['Part_Number'];
$issue=$row6['Issues'];
$pic=$row6['PIC_Comments'];
$emailadd= $row6['PersoninCharge'];
if($row6['Status']=="Open") {
$message = "<html><b>Invoice Number: {$invnumb}.</b><br><br>";
$message .= "<b>Part Number:</b><br><xmp>{$partnumb}</xmp><br><br>";
$message .= "<b>Issues:</b><br><xmp>{$issue}</xmp><br>";
$message .= "<b>{$pic}<b><br>";
$message .= "</html>";
if(!empty($emailadd)) {
dbInsertEmailMessage($emailadd, "Invoice Number: {$invnumb} - {$issue}.", $message);
$dbh=null;
}
}
}
}
function dbInsertEmailMessage($send_to, $subject, $message) {
$sql7 = "INSERT INTO email_queue (Send_to, Subject, Message) VALUES (:send_to, :subject, :message)";
$dbh = db_connect("mes");
$stmt7 = $dbh->prepare($sql7);
$stmt7->bindParam(':send_to', $send_to, PDO::PARAM_STR);
$stmt7->bindParam(':subject', $subject, PDO::PARAM_STR);
$stmt7->bindParam(':message', $message, PDO::PARAM_STR);
$stmt7->execute();
$dbh=null;
}
Here's my db connection:
function db_connect($DATABASE) {
session_start();
// Connection data (server_address, database, username, password)
$servername = '*****';
//$namedb = '****';
$userdb = '*****';
$passdb = '*****';
// Display message if successfully connect, otherwise retains and outputs the potential error
try {
$dbh = new PDO("mysql:host=$servername; dbname=$DATABASE", $userdb, $passdb, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
return $dbh;
//echo 'Connected to database';
}
catch(PDOException $e) {
echo $e->getMessage();
}
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
There are a couple things that may help with your failed inserts. See if this is what you are looking for, I have notated important points to consider:
<?php
// take session_start() out of your database connection function
// it draws an error when you call it more than once
session_start();
// Create a connection class
class DBConnect
{
public function connect($settings = false)
{
$host = (!empty($settings['host']))? $settings['host'] : false;
$username = (!empty($settings['username']))? $settings['username'] : false;
$password = (!empty($settings['password']))? $settings['password'] : false;
$database = (!empty($settings['database']))? $settings['database'] : false;
try {
$dbh = new PDO("mysql:host=$host; dbname=$database", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
// You return the connection before it hits that setting
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
catch(PDOException $e) {
// Only return the error if an admin is logged in
// you may reveal too much about your database on failure
return false;
//echo $e->getMessage();
}
}
}
// Make a specific connection selector
// Put in your database credentials for all your connections
function use_db($database = false)
{
$con = new DBConnect();
if($database == 'mes')
return $con->connect(array("database"=>"db1","username"=>"u1","password"=>"p1","host"=>"localhost"));
else
return $con->connect(array("database"=>"db2","username"=>"u2","password"=>"p2","host"=>"localhost"));
}
// Create a query class to return selects
function query($con,$sql,$bind=false)
{
if(empty($bind))
$query = $con->query($sql);
else {
foreach($bind as $key => $value) {
$kBind = ":{$key}";
$bindVals[$kBind] = $value;
}
$query = $con->prepare($sql);
$query->execute($bindVals);
}
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
return (!empty($result))? $result:0;
}
// Create a write function that will write to database
function write($con,$sql,$bind=false)
{
if(empty($bind))
$query = $con->query($sql);
else {
foreach($bind as $key => $value) {
$kBind = ":{$key}";
$bindVals[$kBind] = $value;
}
$query = $con->prepare($sql);
$query->execute($bindVals);
}
}
// Do not create connections in your function(s), rather pass them into the functions
// so you can use the same db in and out of functions
// Also do not null the connections out
function GenerateEmail($con,$conMes,$line = false)
{
if(empty($_POST['idtxt']) || (!empty($_POST['idtxt']) && !is_numeric($_POST['idtxt'])))
return false;
$data = query($con,"SELECT * FROM `invalid_invoice` WHERE `ID` = :0", array($_POST['idtxt']));
if($data == 0)
return false;
// Instead of creating a bunch of inserts, instead create an array
// to build multiple rows, then insert only once
$i = 0;
foreach ($data as $row) {
$invnumb = $row['Invoice_Number'];
$partnumb = $row['Part_Number'];
$issue = $row['Issues'];
$pic = $row['PIC_Comments'];
$emailadd = $row['PersoninCharge'];
if($row['Status']=="Open") {
ob_start();
?><html>
<b>Invoice Number: <?php echo $invnumb;?></b><br><br>
<b>Part Number:</b><br><xmp><?php echo $partnumb; ?></xmp><br><br>
<b>Issues:</b><br><xmp><?php echo $issue; ?></xmp><br>
<b><?php echo $pic; ?><b><br>
</html>
<?php
$message = ob_get_contents();
ob_end_clean();
if(!empty($emailadd)) {
$bind["{$i}to"] = $emailadd;
$bind["{$i}subj"] = "Invoice Number: {$invnumb} - {$issue}.";
$bind["{$i}msg"] = htmlspecialchars($message,ENT_QUOTES);
$sql[] = "(:{$i}to, :{$i}subj, :{$i}msg)";
}
}
$i++;
}
if(!empty($sql))
return dbInsertEmailMessage($conMes,$sql,$bind);
return false;
}
function dbInsertEmailMessage($con,$sql_array,$bind)
{
if(!is_array($sql_array))
return false;
write($con,"INSERT INTO `email_queue` (`Send_to`, `Subject`, `Message`) VALUES ".implode(", ",$sql_array),$bind);
return true;
}
// Create connections
$con = use_db();
$conMes = use_db('mes');
GenerateEmail($con,$conMes);
I have a TCP server, which listens for incoming messages(data/requests) and replies accordingly. However, it does not reply after the first connection. If its a data message, the data is inserted into the database, but the confirmation message does not reach the client. And, there is no response if its a data request message. When I restart the server, it replies correctly only to the first incoming connection. Henceforth, there is no response from server to client.
I have attached my code, please suggest what can be done to correct the issue.
/**
* Settings
*/
$listen_address = "0.0.0.0";
$listen_port = ****;
$mysql_server = "localhost";
$mysql_username = "root";
$mysql_password = "*****";
$mysql_database = "*****";
/**
* End Settings
*/
function socketError($errorFunction, $die=false) {
$errMsg = socket_strerror(socket_last_error());
echo("{$errorFunction}() error: $errMsg");
if ($die) {
exit();
}
}
function doQuery($query) {
global $db, $mysql_server, $mysql_username, $mysql_password, $mysql_database, $thread_id;
if (0) echo "Trying query: $query\n";
if(!($res = mysqli_query($db, $query))) {
#mysqli_kill($db, $thread_id);
#mysqli_close($db);
$db = mysqli_connect($mysql_server, $mysql_username, $mysql_password, $mysql_database);
if(mysqli_connect_errno()) {
echo("\r\nFailed to connect to MySQL: " . mysqli_connect_error());
}
if(!($res = mysqli_query($db, $query))) {
echo("Error: " . mysqli_error($db) . "\n");
}
}
return $res;
}
function logMessage($socket, $msg) {
global $db, $mysql_server, $mysql_username, $mysql_password, $mysql_database, $thread_id;
$get_ip = socket_getpeername($socket, $address);
echo("Received ({$address}): {$msg}\n");
// process update:<pid>:<sid>! request
// the response is sent in format: d_id:value<uptill the first comma>,
// in case of multiple rows, they are separated by LF character (\n)
if (preg_match('/^update:([0-9]+):([0-9]+)!/', $msg, $matches)) {
$pid = $matches[1];
$sid = $matches[2];
$res = doQuery("SELECT d_id FROM devices WHERE project_id = $pid AND subproject_id = $sid");
if ($res) {
if (mysqli_num_rows($res) > 0) {
$output = '';
$i = 0;
while ($r = mysqli_fetch_array($res)) {
$res2 = doQuery("SELECT tt.d_id, tt.field_a, tt.value FROM data tt INNER JOIN (SELECT d_id, MAX(update_time) AS MaxDateTime FROM data WHERE d_id = {$r['d_id']} GROUP BY d_id) groupedtt ON tt.d_id = groupedtt.d_id AND tt.update_time = groupedtt.MaxDateTime");
if ($res2) {
if (mysqli_num_rows($res2) > 0) {
while ($r2 = mysqli_fetch_array($res2)) {
$tmp = explode(',', $r2['value'], 2);
$output .= ($i>0?"\n":'').$r2['d_id'].':'.$r2['field_a'].':'.$tmp[0].',';
++$i;
}
}
}
}
return $output;
}
}
}
else {
// Ensure nothing breaks our query
$msg = str_replace("'", "\'", $msg);
$parts = explode(':', $msg);
if (is_numeric($parts[0])) {
//if(!mysqli_query($db, "INSERT INTO data (data, datetime, receiver) VALUES ('{$msg}', '".time()."', '".$address."')")) {
doQuery("INSERT INTO data (sender, d_id, value, update_time, field_a) VALUES ('".$address."', {$parts[0]}, '{$parts[2]}', '".date("Y-m-d H:i:s")."','{$parts[1]}')");
return "yes\n";
}
else return "no\n";
}
}
function sendData($socket, $message) {
socket_write($socket, $message);
}
error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
ignore_user_abort(true);
// Stage 1: MySQL Connection
$db = mysqli_connect($mysql_server, $mysql_username, $mysql_password, $mysql_database);
if(mysqli_connect_errno()) {
echo("\r\nFailed to connect to MySQL: " . mysqli_connect_error());
}
else
$thread_id = mysqli_thread_id($db);
// Stage 2: start listening
if(!($server = #socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) {
socketError("socket_create", true);
}
socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1);
if(!#socket_bind($server, $listen_address, $listen_port)) {
socketError("socket_bind", true);
}
if(!#socket_listen($server)) {
socketError("socket_listen", true);
}
$allSockets = array($server);
echo("Listening on port {$listen_port}\n");
// Stage 3: accept clients
while (true) {
if(connection_aborted()) {
foreach($allSockets as $socket) {
socket_close($socket);
}
break;
}
$changedSockets = $allSockets;
#socket_select($changedSockets, $write = NULL, $except = NULL, 5);
foreach($changedSockets as $socket) {
if ($socket == $server) {
if(!($client = #socket_accept($server))) {
socketError("socket_accept", false);
} else {
$allSockets[] = $client;
}
} else {
$data = socket_read($socket, 2048);
if ($data === false || $data === '') {
unset($allSockets[array_search($socket, $allSockets)]);
socket_close($socket);
} else {
if(trim($data != "")) {
$response = logMessage($socket, $data);
sendData($socket, $response);
}
}
}
}
}
?>
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');
}
}
?>