PHP MQTT subscribe not consistent - containers

I am trying to display some values using MQTT on a PHP based page. The PHP code contains the subscriber. I am using Bluemix IoT service for the MQTT broker. Also, the messages are published via Python code on local machine.
When I try to display values on pages using page refresh, the page sometimes fails to display the values. There is no problem at the publisher end as the values are successfully displayed by Bluemix IoT service.
My code is as follows:
<?php
// include class
require('phpMQTT.php');
// set configuration values
if( getenv("VCAP_SERVICES") ) {
// get MySQL service configuration from Bluemix
$services = getenv("VCAP_SERVICES");
$services_json = json_decode($services, true);
$mysql_config = $services_json["iotf-service"][0]["credentials"];
$org_id = $mysql_config["org"];
$port = $mysql_config["mqtt_u_port"];
$username = $mysql_config["apiKey"];
$password = $mysql_config["apiToken"];
}
// set configuration values
$config = array(
'org_id' => $org_id,
'port' => $port,
'app_id' => 'm',
'iotf_api_key' => $username,
'iotf_api_secret' => $password,
'device_id' => 'trial',
'qos' => 1
);
global $Val_A;
global $Val_B;
global $Val_C;
global $Val_D;
//Read already existing file
$ini_b = parse_ini_file("data.ini",true);
$Val_A = $ini_b['Data']['A'];
$Val_B = $ini_b['Data']['B'];
$Val_C = $ini_b['Data']['C'];
$Val_D = $ini_b['Data']['D'];
$config['server'] = $config['org_id'] . '.messaging.internetofthings.ibmcloud.com';
$config['client_id'] = 'a:' . $config['org_id'] . ':' . $config['app_id'];
#echo $config['client_id'];
// initialize client
$mqtt_dev = new phpMQTT($config['server'], $config['port'], $config['client_id']);
$mqtt_dev->debug = false;
// connect to broker
if(!$mqtt_dev->connect(true, null, $config['iotf_api_key'], $config['iotf_api_secret'])){
echo 'ERROR: Could not connect to IoT cloud';
exit();
}
else
{
#echo "Success";
}
$topics['iot-2/type/newdevice/id/' . $config['device_id'] . '/evt/status/fmt/json'] =
array('qos' =>1, 'function' => 'getLocation');
$mqtt_dev->subscribe($topics, 1);
$elapsedSeconds = 0;
while ($mqtt_dev->proc(true)) {
#echo json_encode($json);
if (count($location) == 2) {
break;
}
if ($elapsedSeconds == 5) {
break;
}
$elapsedSeconds++;
sleep(1);
}
// disconnect
//I have tried commenting this too
$mqtt_dev->close();
function getLocation($topic, $msg) {
global $location;
global $json;
$json = json_decode($msg);
$Val_A = $json->A;
$Val_B = $json->B;
$Val_C = $json->C;
$Val_D = $json->D;
//Read already existing file
$ini_backup = parse_ini_file("data.ini",true);
$ValA_b = $ini_backup['Data']['A'];
$ValB_b = $ini_backup['Data']['B'];
$ValC_b = $ini_backup['Data']['C'];
$ValD_b = $ini_backup['Data']['D'];
if($Val_A != 0)
{
$ValA_b = $Val_A;
}
else
{
$Val_A = $ValA_b;
}
if($Val_B != 0)
{
$ValB_b = $Val_B;
}
else
{
$Val_B = $ValB_b;
}
if($Val_C != 0)
{
$ValC_b = $Val_C;
}
else
{
$Val_C = $ValC_b;
}
if($Val_D != 0)
{
$ValD_b = $Val_D;
}
else
{
$Val_D = $ValD_b;
}
$file = fopen("data.ini","w");
fwrite($file,"[Data]". "\n" );
fwrite($file,"A =" . $ValA_b . "\n" );
fwrite($file,"B =" . $ValB_b . "\n" );
fwrite($file,"C =" . $ValC_b . "\n" );
fwrite($file,"D =" . $ValD_b . "\n" );
fclose($file);
return $location;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="refresh" content="5" >
<div id="footer">
This page will automatically reload every 5 seconds. <br/>
</div>
<label for="A">A</label>
<input type="text" value="<?php echo $Val_A ?>" />
<label for="B">B</label>
<input type="text" value="<?php echo $Val_B ?>" />
<label for="C">C</label>
<input type="text" value="<?php echo $Val_C ?>" />
<label for="D">D</label>
<input type="text" value="<?php echo $Val_D ?>" />
</body>
</html>
Can some one guide where am I going wrong?

Rather than using meta to specify the refresh, try using php header("Refresh:5");
There is an old stack overflow thread discussing using meta versus header for refrseh in php.

Related

upload csv file and save data in data base in cakephp 3

How can i upload csv file and save data in to my mysql database.
according to id.in cakephp 3
i am unable to do that. can any one help me.
my controller
public function import() {
if(isset($_POST["submit"])){
if($_FILES['file']['csv']){
$filename = explode('.', $_FILES['file']['csv']);
debug($filename);
if($filename[1]=='csv'){
$handle = fopen($_FILES['file']['csv'], "r");
while ($data = fgetcsv($handle)){
$item1 = $data[0];
// $item2 = $data[1];
// $item3 = $data[2];
// $item4 = $data[3];
$Applicants = $this->Applicants->patchEntity($Applicants, $item1);
$this->Applicants->save($Applicants);
}
fclose($handle);
}
}
}
$this->render(FALSE);
}
my view:
<div class="col-md-8">
<?= $this->Form->create('Applicants',['type' => 'file','url' => ['controller'=>'Applicants','action' => 'import'],'class'=>'form-inline','role'=>'form',]) ?>
<div class="form-group">
<label class="sr-only" for="csv"> CSV </label>
<?php echo $this->Form->input('csv', ['type'=>'file','class' => 'form-control', 'label' => false, 'placeholder' => 'csv upload',]); ?>
</div>
<button type="submit" class="btn btn-default"> Upload </button>
<?= $this->Form->end() ?>
</div>
Your question is a bit unclear what do you want to do in the controller do you want to update the existing records or save new data. If you want to update then only you need to use patchEntity.
The patchEntity should have a database entity fetched where in you can change or update the data as per your need, so in case if your first column contains the id of the Applications table then below code can work and in $data you can write whatever fields you want to update or add
So you can use the below code block instead
public function import() {
if(isset($_POST["submit"])){
if($_FILES['file']['csv']){
$filename = explode('.', $_FILES['file']['csv']);
debug($filename);
if($filename[1]=='csv'){
$handle = fopen($_FILES['file']['csv'], "r");
while ($data = fgetcsv($handle)){
$item1 = $data[0];
$data = array(
'fieldName' => $item1
);
// $item2 = $data[1];
// $item3 = $data[2];
// $item4 = $data[3];
$Applicant = $this->Applicants->newEntity($data);
$this->Applicants->save($Applicant);
}
fclose($handle);
}
}
}
$this->render(FALSE);
}
If you have more specific code/requirement then please share, so that I can help you out accordingly.
Here is my Solution to upload csv file and save database
public function import($id = NULL) {
$data = $this->request->data['csv'];
$file = $data['tmp_name'];
$handle = fopen($file, "r");
while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($row[0] == 'id') {
continue;
}
$Applicants = $this->Applicants->get($row[0]);
$columns = [
'written_mark' => $row[1],
'written_comments' => $row[2],
'viva_mark' => $row[3],
'viva_comments' => $row[4]
];
$Applicant = $this->Applicants->patchEntity($Applicants, $columns);
$this->Applicants->save($Applicant);
}
fclose($handle);
$this->set('title','Upload Student CSV File Input Number and others');
return $this->redirect($this->referer());
}

Find how many times every word is repeated in db

Am using drupal to manage my content. I want to search all my contents title and body and find how many times each word is repeated in the whole contents.
It may be by an sql query, but I have no experience with sql.
Any ideas?
This code searches the body field and ALL fields of ANY Content Types for a specific string. You can run it via command line. Say you save it as "fieldsearch.php", you can then run it as:
php fieldsearch.php "myStringForWhichToSearch"
You need to fill in your connection data and database name. It outputs the array of matching nodes but you can format that output into anything you'd like (I recommend csv).
<?php
//Set Parameters here
$env = "dev"; // Options [dev|prod] - Defaults to dev
$prodConnection = array(
"host" => "",
"user" => "",
"pass" => ""
);
$devConnection = array(
"host" => "",
"user" => "",
"pass" => ""
);
//Use the selected env settings
if($env == "prod"){
$connection = $prodConnection;
} else {
$connection = $devConnection;
}
function getTables($con, $database){
//Get the set of field tables
$sql = "SHOW TABLES FROM $database";
$result = mysqli_query($con, $sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
$tables = array();
while ($row = mysqli_fetch_row($result)) {
$tables[] = $row[0];
}
mysqli_free_result($result);
return $tables;
}
function getFieldTables($con,$database){
$allTables = getTables($con, $database);
$fieldTables = array();
foreach($allTables as $key => $table){
if( isFieldTable($table) ){
$fieldTables[] = $table;
}
}
//add the common tables
$fieldTables[] = "field_data_body";
$fieldTables[] = "field_data_comment_body";
return $fieldTables;
}
function isFieldTable($table){
//echo $table . "\n";
if( stripos($table, "field_data_field") !== FALSE){
return TRUE;
}
}
//Set the search term here:
if (array_key_exists(1, $argv)) {
$searchString = $argv[1];
}
else {
die('usage: php fieldsearch.php "search string"' . "\n");
}
$databaseName = "myDatabaseName";
$outArray = array();
//Connect
$con=mysqli_connect($connection['host'],$connection['user'],$connection['pass'],$databasePrefix.$databaseNum);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//getFieldTables
$fieldTables = getFieldTables($con, $databaseName);
//Query each field tables data for the string in question
foreach($fieldTables as $key => $table){
//get Field value column name
$valueCol = str_replace("field_data_field_", '', $table);
$result = mysqli_query($con,"SELECT
entity_id
FROM
$table
WHERE
field_" . $valueCol . "_value
LIKE
'%$searchString%';");
if($result){
while($row = mysqli_fetch_assoc($result)){
$dataArray[$table][$row['entity_id']]['nid'] = $row['entity_id'];
}
}
}
//Add the body table
$result = mysqli_query($con,"SELECT
entity_id
FROM
field_data_body
WHERE
body_value
LIKE
'%$searchString%';");
if($result){
while($row = mysqli_fetch_assoc($result)){
$dataArray['field_data_body'][$row['entity_id']]['nid'] = $row['entity_id'];
}
}
var_dump($dataArray);

(codeigniter) add multiple rows of data from file to mysql database?

Is it possible to get data from file then add it in my database in mysql. I'm using codeigniter. My code only asks inputs from the user. Please help please. It is required by my professor so that if the user wants to input for example 100 data he/she doesn't manually input the data thus get the data from another database.
my view page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Students</title>
</head>
<body>
<div id="container">
<h1>Student's Page</h1>
<div id="body">
<div id="div2">
<?php
echo form_open('main/addToRegistrar');
?>
<br>
<?php
echo "<p>ID: ";
echo form_input('id');
echo "</p>";
echo "<p>First Name: ";
echo form_input('first_name');
echo "</p>";
echo "<p>Middle Name: ";
echo form_input('middle_name');
echo "</p>";
echo "<p>Last Name: ";
echo form_input('last_name');
echo "</p>";
echo "<p>";
echo form_submit('ADD', 'ADD');
echo "<p>";
echo form_close();
?>
<a href='<?php echo base_url()."main/admin"; ?>'>Home!</a>
</div>
</div>
<p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds </p>
</div>
</body>
</html>
my controller
public function addToRegistrar(){
if($this->session->userdata('is_logged_in')){
$this->load->model('model_users');
$this->model_users->addToRegistrar();
$this->load->view('view_addAteneoStudents');
} else{
redirect('main/restricted');
}
}
my model
public function addToRegistrar(){
$fname = $this->input->post('first_name');
$mname = $this->input->post('middle_name');
$lname = $this->input->post('last_name');
$id = $this->input->post('id');
$data = array(
'id' => $id,
'first_name' => $fname ,
'middle_name' => $mname ,
'last_name' => $lname
);
if($this->db->insert('registrar', $data)){
echo "Successfully added";
}
}
You must have an option to upload files (csv recommended) and upload it to your server. Here is a quick how:
view:
<html>
<body>
<form action="<?php echo base_url();?>" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
controller:
public function addToRegistrar()
{
if($this->session->userdata('is_logged_in')){
$this->load->model('model_users');
$this->model_users->addToRegistrar();
$this->load->view('view_addAteneoStudents');
} else{
redirect('main/restricted');
}
}
model:
function addToRegistrar()
{
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
} else {
$filename = "upload/" . $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], $filename);
//parse the uploaded file and insert to database
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = $row;
}
$this->db->insert_batch('registrar', $data);
fclose($handle);
}
}
}
}
NOTE: Your csv file should have the same column count as your database table 'registrar'.
More about reading csv files here.

UPS php api - create order

I am trying to integrate UPS php api to generate online order for sending stuff.
I am able to validate address and get rates for stuff transfer but i am not able to find any solution for generating order and labels for courir, can somebody help me in getting that.
UPS Developer Kit and API is quite a good reference to all API related development, including in PHP. It can be downloaded from here: https://www.ups.com/upsdeveloperkit/downloadresource?loc=en_US
Here is some code example, for the PHP ship accept code (from the API zip):
<?php
//Configuration
$access = " Add License Key Here";
$userid = " Add User Id Here";
$passwd = " Add Password Here";
$accessSchemaFile = " Add AccessRequest Schema File";
$requestSchemaFile = " Add ShipAcceptRequest Schema File";
$responseSchemaFile = "Add ShipAcceptResponse Schema File";
$endpointurl = ' Add URL Here';
$outputFileName = "XOLTResult.xml";
try
{
//create AccessRequest data object
$das = SDO_DAS_XML::create("$accessSchemaFile");
$doc = $das->createDocument();
$root = $doc->getRootDataObject();
$root->AccessLicenseNumber=$access;
$root->UserId=$userid;
$root->Password=$passwd;
$security = $das->saveString($doc);
//create ShipAcceptRequest data oject
$das = SDO_DAS_XML::create("$requestSchemaFile");
$requestDO = $das->createDataObject('','RequestType');
$requestDO->RequestAction='01';
//$requestDO->RequestOption='01';
$doc = $das->createDocument();
$root = $doc->getRootDataObject();
$root->Request = $requestDO;
$root->ShipmentDigest = 'test-Invalid-digest';
$request = $das->saveString($doc);
//create Post request
$form = array
(
'http' => array
(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => "$security$request"
)
);
//print form request
print_r($form);
$request = stream_context_create($form);
$browser = fopen($endpointurl , 'rb' , false , $request);
if(!$browser)
{
throw new Exception("Connection failed.");
}
//get response
$response = stream_get_contents($browser);
fclose($browser);
if($response == false)
{
throw new Exception("Bad data.");
}
else
{
//save request and response to file
$fw = fopen($outputFileName,'w');
fwrite($fw , "Response: \n" . $response . "\n");
fclose($fw);
//get response status
$resp = new SimpleXMLElement($response);
echo $resp->Response->ResponseStatusDescription . "\n";
}
}
catch(SDOException $sdo)
{
echo $sdo;
}
catch(Exception $ex)
{
echo $ex;
}
?>

Query to database and display

I use CodeIgniter 2.1.3, PHP and MySQL.
Hello, I want to display data from database. Always I display by foreach($results as $data), but now I want do display all data in few step. Display first record and when user click next then display next row from database. I now that I must use mysql_fetch_row() but I don't know how I can do it...
This is my model:
public function play($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->get("quiz");
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
controler:
public function index()
{
$config = array();
$config["base_url"] = base_url() . "index.php/main_menu/Quiz/index";
$config["total_rows"] = $this->quiz_model->record_count();
$config["per_page"] = 11;
$config["uri_segment"] = 4;
$this->pagination->initialize($config);
$page = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;
$data["results"] = $this->quiz_model->play($config["per_page"], $page);
$data["links"] = $this->pagination->create_links();
$this->load->view('left_column/quiz_open', $data);
}
Pagination is not important.
and view:
<form>
<?php
if (empty($results)) {
}
else {
foreach($results as $data) { ?>
<label style='width:450px;'> <b> &nbsp <?php echo $data->pytanie?> </b> </label>
<label style='width:300px;'> <input type="radio" name="Wiek" value=<?php echo $data->odp1 ?> /> <?php echo $data->odp1 ?> </label>
<label style='width:300px;'> <input type="radio" name="Wiek" value=<?php echo $data->odp2 ?> /> <?php echo $data->odp2 ?> </label>
<label style='width:300px;'> <input type="radio" name="Wiek" value=<?php echo $data->odp3 ?> /> <?php echo $data->odp3 ?> </label>
<?php }
}?>
<label style='width:300px;'> <input type="submit" name="Wyslij" id="Wyslij" value="&nbsp Wyƛlij &nbsp"/> </label>
</form>
There is an inbuilt Pagination class provided by codeIgniter. You can find it in user guide.
Define a start index variable in the function where u want to use pagination as zero.
public function pagination($start_index = 0)
{
$result = $this->model->get_results($data); //this $data is the argument which you are passing to your model function. If you are using database to get results array.
$items_per_page = 10; //this is constant variable which you need to define
$filtered_result = array_splice($result, $start_index, ITEM_PER_PAGE_USERS);
$model['$filtered_result'] = $filtered_result;
$total_rows = count($result);
$model['page_links'] = create_page_links (base_url()."/controlelr_name/pagination",ITEM_PER_PAGE_USERS, $total_rows);
$this->load->view('controller_name/view_file_name', $model);
}
This is a generalised function for pagination. You can keep this function in one helper file where you keep all generalised functions.
function create_page_links($base_url, $per_page, $total_rows)
{
$CI = & get_instance();
$CI->load->library('pagination');
$config['base_url'] = $base_url;
$config['total_rows'] = $total_rows;
$config['per_page'] = $per_page;
$CI->pagination->initialize($config);
return $CI->pagination->create_links();
}
This create page links function is a generic function.............for more explanation check pagination class from user guide......