In my code am trying to verify if query is true before outputing result i have tried:
require("init.php");
if(empty($_GET["book"]) && empty($_GET["url"])) {
$_SESSION["msg"] = 'Request not valid';
header("location:obinnaa.php");
}
if(isset($_GET["book"]) && isset($_GET["url"])) {
$book = $_GET['book'];
$url = $_GET['url'];
$drs = urldecode("$url");
$txt = encrypt_decrypt('decrypt', $book);
if(!preg_match('/(proc)/i', $url)) {
$_SESSION["msg"] = 'ticket printer has faild';
header("location:obinnaa.php");
exit();
} else {
$ql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$count = mysqli_num_rows($sql);
if($count < 1) {
$_SESSION["msg"] = 'Transation has oready been made by a customer please check and try again';
header("location:obinnaa.php");
exit();
}
while($riow = mysqli_fetch_assoc($ql)) {
$id = $riow["id"];
$tqty = $riow["quantity"];
for($b = 0; $b < $tqty; $b++) {
$run = rand_string(5);
$dua .= $run;
}
}
$sql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$split = $dua;
$show_plit = str_split($split, 5);
$b = 0;
while($row = mysqli_fetch_assoc($sql)) {
$id = $row["id"];
$qty = $row["quantity"];
$oldB = $b;
$am = " ";
for(; $b < $oldB + $qty; $b++) {
$am .= "$show_plit[$b]";
$lek = mysqli_query($conn, "UPDATE books SET ticket='$am' WHERE id=$id");
}
if($lek) {
$adr = urlencode($adr = "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
$ty = encrypt_decrypt("encrypt", $txt);
$vars = array(
"book" => $ty,
"url" => $adr
);
$querystring = http_build_query($vars);
$adr = "viewbuy.php?" . $querystring;
header("location: $adr");
} else {
$_SESSION["msg"] = 'Transation failed unknow error';
header("location:obinnaa.php");
}
}
}
}
but i get to
$_SESSION["msg"]='Transation has oready been made by a customer please check and try again
even when the query is right what are mine doing wrong.
Check your return variable name from the query. You have $ql when it should be $sql.
$sql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$count = mysqli_num_rows($sql);
A good IDE would flag this. NetBeans is a good free one.
Public Service Announcement:
NEVER build SQL queries straight from a URL parameter. Always sanitize your inputs and (better yet) use parameterized queries for your SQL calls. You can Google these topics for more info.
This is the first time i'm working in Laravel. I'm developing a custom command which will read a file and insert rows in database. I'm getting errors. Below is my code any help will be appreciated.
Command File.
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Model;
use App\Ship;
//use DB;
class shipdata extends Command
{
protected $signature = 'ship:start';
protected $description = 'This Command will Read file and Extract data from it and will store data in database';
public function __construct()
{
parent::__construct();
}
public function handle()
{
// $this->line('Query Working');
ShipNow::ShipNow();
}
}
Model File
public function ShipNow()
{
$dir = "d:/xampp/htdocs/lara12/IN/";
$failed_dir = "d:/xampp/htdocs/lara12/FAILED/";
$processed_dir = "d:/xampp/htdocs/lara12/PROCESSED/";
$files = array();
// Get all files which need to process
foreach (glob($dir."*.SHIP") as $file) {
$files[] = $file;
}
// If .SHIP files available in the folder then start processing
if(count($files) > 0)
{
// Start processing file
foreach($files as $file)
{
$row = 1;
$file_name = $file;
// Get file name without extension
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $file_name);
// Generate new filename with extension PROC
$rename_filename = $withoutExt.".PROC";
// Rename filename
$file_proc = rename($file_name, $rename_filename);
// File processing
$error = 0;
if (($handle = fopen($rename_filename, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, "|")) !== FALSE) {
$num = count($data);
// For header table insert
if($row==1)
{
$myparams['warehouse'] = $data[0];
$myparams['SHIPMENT_ID'] = $data[1];
$myparams['COMPANY'] = $data[2];
$myparams['CARRIER'] = $data[3];
$myparams['CARRIER_SERVICE'] = $data[4];
$myparams['CUSTOMER'] = $data[5];
$myparams['CUSTOMER_NAME'] = $data[6];
$myparams['SHIP_TO_NAME'] = $data[7];
$myparams['SHIP_TO_ADDRESS1'] = $data[8];
$myparams['SHIP_TO_ADDRESS2'] = $data[9];
$myparams['SHIP_TO_ADDRESS3'] = $data[10];
$myparams['SHIP_TO_CITY'] = $data[11];
$myparams['SHIP_TO_COUNTRY'] = $data[12];
$myparams['SHIP_TO_POSTAL_CODE'] = $data[13];
$myparams['SHIP_TO_ATTENTION_TO'] = $data[14];
$myparams['SHIP_TO_PHONE_NUM'] = $data[15];
$myparams['SHIP_TO_EMAIL_ADDRESS'] = $data[16];
$myparams = save();
/* $sql = "exec dbo.Portal_3PL_ShipmentEntry_Header '".$myparams['SHIPMENT_ID']."','".$myparams['COMPANY']."','".$myparams['CARRIER']."','".$myparams['CARRIER_SERVICE']."','".$myparams['CUSTOMER']."','".$myparams['CUSTOMER_NAME']."','".$myparams['SHIP_TO_NAME']."','".$myparams['SHIP_TO_ADDRESS1']."','".$myparams['SHIP_TO_ADDRESS2']."','".$myparams['SHIP_TO_ADDRESS3']."','".$myparams['SHIP_TO_CITY']."','".$myparams['SHIP_TO_COUNTRY']."','".$myparams['SHIP_TO_POSTAL_CODE']."','".$myparams['SHIP_TO_ATTENTION_TO']."','".$myparams['SHIP_TO_PHONE_NUM']."','".$myparams['SHIP_TO_EMAIL_ADDRESS']."'";
$sql_result = odbc_exec($conn, $sql);
if (odbc_error())
{
echo odbc_errormsg($conn);
$error = 1;
}
$ERP_ORDER_LINE_NUM = 1;
$shipment_header = odbc_fetch_array($sql_result);*/
}
// For shipment detail
else
// {
// $ITEM = $data[1];
// $QUANTITY = intval($data[2]);
// $INTERNAL_SHIPMENT_NUM = $shipment_header['INTERNAL_SHIPMENT_NUM'];
//
// $query2 = "exec dbo.Portal_3PL_ShipmentEntry_Detail '".$INTERNAL_SHIPMENT_NUM."','".$myparams['COMPANY']."',".$ERP_ORDER_LINE_NUM.",'".$ITEM."','".$QUANTITY."',NULL,'N'";
// echo $query2.PHP_EOL;
// $query_result2 = odbc_exec($conn, $query2);
// if (odbc_error())
// {
// echo odbc_errormsg($conn);
// $error = 1;
//
// }else{
// $ERP_ORDER_LINE_NUM++;
// }
// $shipment_detail = odbc_fetch_array($query_result2);
//
// echo trim($shipment_detail['Result'])."#".trim($shipment_detail['Comment'])."#".trim($shipment_detail['INTERNAL_SHIPMENT_LINE_NUM']);
// }
$row++;
}
if($error == 1)
{
$failed_file = "FAILED/".basename($withoutExt).".FAIL";
$file_to_move = "IN/".basename($rename_filename);
fclose($handle);
rename($file_to_move, $failed_file);
// $sql = "INSERT INTO qcimportlog (filename, recordprocess, status) VALUES
// ('$file_name', '$row', 'failed')";
// $result = mysql_query($sql) or die(mysql_error());
}
else
{
$processed_file = "PROCESSED/".basename($rename_filename);
$file_to_move = "IN/".basename($rename_filename);
echo $processed_file;
fclose($handle);
rename($file_to_move, $processed_file);
// $sql = "INSERT INTO qcimportlog (filename, recordprocess, status) VALUES
// ('$file_name', '$row', 'success')";
// $result = mysql_query($sql) or die(mysql_error());
}
}
}
}
else
{
echo "No files to process";
}
}
Kernel.Php
protected $commands = [
Commands\QuizStart::class,
Commands\SendWelcomeEmailCommand::class,
Commands\shipdata::class,
];
ERRORs:
D:\xampp\htdocs\lara12>php artisan ship:start
PHP Fatal error: Class 'App\Console\Commands\ShipNow' not found in D:\xampp\htdocs\lara12\app\Console\Commands\shipdata.php on line 26
[Symfony\Component\Debug\Exception\FatalErrorException]
Class 'App\Console\Commands\ShipNow' not found
ShipNow::ShipNow() should be Ship::ShipNow(), since that's the name of the Model and you call it as a static method, so it has to be a static method in the Ship file:
public static function ShipNow()
{
...
I've got a simple class with two methods: add and process.
require_once('MailQueue.config.php');
require_once('class.phpmailer.subclass.php');
class MailQueue {
private $dbServer;
private $dbName;
private $dbUsername;
private $dbPassword;
private $mailLimit;
private $mailLimitTimeUnit;
private $db;
function __construct() {
global $CONFIG;
// Set database connection variables
$this->dbServer = $CONFIG['dbServer'];
$this->dbName = $CONFIG['dbName'];
$this->dbUsername = $CONFIG['dbUsername'];
$this->dbPassword = $CONFIG['dbPassword'];
// Set app settings
$this->mailLimit = $CONFIG['mailLimit'];
$this->mailLimitTimeUnit = $CONFIG['mailLimitTimeUnit'];
// Connect to database
$this->db = new mysqli($this->dbServer, $this->dbUsername, $this->dbPassword, $this->dbName);
if($this->db->connect_error) {
die("Error connecting to MailQueue.<br />".$this->db->connect_error);
}
}
function add($data) {
$sqls = "";
foreach($data as $d) {
$sqls .= "INSERT INTO mailqueue (".
"desiredSendTime, ".
"fromName, ".
"fromAddress, ".
"toName, ".
"toAddress, ".
"subject, ".
"bodyHtml ".
") VALUES (".
"'".$d['sendAt']."',".
"'".$d['fromName']."',".
"'".$d['fromAddress']."',".
"'".$d['toName']."',".
"'".$d['toAddress']."',".
"'".$d['subject']."',".
"'".$d['body']."'".
");";
}
$insertIds = Array();
if(!$this->db->multi_query($sqls)){
die("Error adding emails to mailqueue: (".$this->db->errno.") ".$this->db->error);
}
// fetch insert ids
do {
$insertIds[] = $this->db->insert_id;
} while($this->db->more_results() && $this->db->next_result());
return $insertIds;
}
function processQueue($numberOfMessages, $preferredEmailIds="") {
// Get number of emails already sent in this timeframe
// Do not check for the last timeUnit, but for the timeUnit we're currently in, e.g.
// if timeUnit = 'hour', count the processed emails in de current hour, not in the last 60 minutes.
switch($this->mailLimitTimeUnit) {
case 'year':
$startOfCurrentTimeframe = date('Y-01-01 00:00:00');
break;
case 'month':
$startOfCurrentTimeframe = date('Y-m-01 00:00:00');
break;
case 'day':
$startOfCurrentTimeframe = date('Y-m-d 00:00:00');
break;
case 'hour':
$startOfCurrentTimeframe = date('Y-m-d H:00:00');
break;
case 'minute':
$startOfCurrentTimeframe = date('Y-m-d H:i:00');
break;
default:
$startOfCurrentTimeframe = '';
}
if($startOfCurrentTimeframe != '') {
$successCounter = 0;
$sql = "SELECT ".
"COUNT(*) AS currentCount ".
"FROM ".
"mailqueue ".
"WHERE ".
"actualSendTime BETWEEN '".$startOfCurrentTimeframe."' AND NOW()";
if(!($stmt = $this->db->prepare($sql))) {
die("Prepare failed: (".$this->db->errno.") ".$this->db->error);
}
if(!($stmt->execute())) {
die("Execute failed: (".$stmt->errno.") ".$stmt->error);
}
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$currentCount = $row['currentCount'];
$spaceLeft = $this->mailLimit - $currentCount;
// Don't exceed the mail limits!
if($spaceLeft < $numberOfMessages){
$numberOfMessages = $spaceLeft;
}
// In case of preferred emails, add an explicit filter to accomplish this
if($preferredEmailIds!=""){
$preferredEmailsOnly = "AND id IN (".implode(',', $preferredEmailIds).") ";
} else {
$preferredEmailsOnly = "";
}
// Process new emails
$sql = "SELECT ".
"* ".
"FROM ".
"mailqueue ".
"WHERE ".
"desiredSendTime < NOW() ".
"AND actualSendTime IS NULL ".
$preferredEmailsOnly.
"ORDER BY ".
"desiredSendTime, ".
"id ".
"LIMIT ?";
if(!($stmt = $this->db->prepare($sql))) {
die("Prepare failed: (".$this->db->errno.") ".$this->db->error);
}
if (!$stmt->bind_param("i", $numberOfMessages)){
die("Binding parameters failed: (".$stmt->errno.") ".$stmt->error);
}
if (!$stmt->execute()) {
die("Execute failed: (".$stmt->errno.") ".$stmt->error);
}
$result = $stmt->get_result();
if($result->num_rows > 0) {
$successCounter = 0;
$sqls = "";
while($row = $result->fetch_assoc()) {
$msg = new themedMailer();
$msg->From = $row['fromAddress'];
$msg->FromName = $row['fromName'];
$msg->Subject = $row['subject'];
$msg->Body = $row['bodyHtml'];
$msg->IsMail();
$msg->AddAddress($row['toAddress'], $row['toName']);
if($msg->Send()) {
$successCounter++;
// Save the time of sending to the email in the database
$sqls .= "UPDATE mailqueue SET actualSendTime = NOW() WHERE id = ".$row['id'].";";
} else {
die("Sending mail failed: ".$this->ErrorInfo);
}
}
// Update the sent emails
if(!$this->db->multi_query($sqls)){
die("Failed updating records for sent emails; these emails will be sent again because of this error.");
}
}
$stmt->close();
}
return $successCounter;
}
}
If I use separate http requests to call the add and process functions, it works alright. The add function adds some records in a table and the process function processes some records from the same table (not necessarily the same records).
If I try to combine the two to make process process the records that are inserted by add, the process function simply doesn't find the records that were inserted by the add function. Some code to explain what I've been trying:
This code works fine:
HTTP Request 1:
ERROR_REPORTING(E_ALL);
require_once('../MailQueue.class.php');
$queue = new MailQueue();
$currentTime = date('YmdHis');
$data = Array();
$num = 2000;
for($i=1; $i<=$num; $i++) {
$data[$i] = Array();
$data[$i]['sendAt'] = date('Y-m-d H:i:s');
$data[$i]['fromName'] = 'John Doe';
$data[$i]['fromAddress'] = 'john#doe.com';
$data[$i]['toName'] = 'Jane Doe';
$data[$i]['toAddress'] = 'jane#doe.com';
$data[$i]['subject'] = 'Test message MailQueue '.$currentTime;
$data[$i]['body'] = 'Test message MailQueue '.$currentTime;
}
$queue->add($data);
echo "Added ".$num." new emails to be sent";
HTTP Request 2:
ERROR_REPORTING(E_ALL);
require_once('../MailQueue.class.php');
$try = 50;
$queue = new MailQueue();
echo "Trying to send ".$try." emails.<br />";
$counter = $queue->processQueue($try);
echo "Sent ".$counter." emails.";
if($counter < $try) {
echo " Not all desired emails were sent, so the mail limit was probably reached. Please try again later.";
}
The following code doesn't work, because the SELECT query in the process function returns no records:
Only 1 HTTP Request:
ERROR_REPORTING(E_ALL);
require_once('../MailQueue.class.php');
$queue = new MailQueue();
$currentTime = date('YmdHis');
$try = 50;
$data = Array();
for($i=1; $i<=3; $i++) {
$data[$i] = Array();
$data[$i]['sendAt'] = date('Y-m-d H:i:s');
$data[$i]['fromName'] = 'John Doe '.$i;
$data[$i]['fromAddress'] = 'john#doe.com';
$data[$i]['toName'] = 'Jane Doe';
$data[$i]['toAddress'] = 'jane#doe.com';
$data[$i]['subject'] = 'Test message MailQueue '.$currentTime;
$data[$i]['body'] = 'Test message MailQueue '.$currentTime;
}
// Directly process the added messages
echo "Trying to send ".$try." emails.<br />";
$counter = $queue->processQueue($try, $queue->add($data));
echo "Added 3 new emails to be sent. ".$counter." emails were actually sent.";
Can anyone explain why combining the two functions doesn't work? Autocommit is 1 and I've trying to commit explicitly, but to no avail.
I have a program that writes MySQL data to Excel via PHPExcel and I am having no errors but the problem is they don't have any line breaks in every 30 records.
How can I achieve this programmatically in PHPExcel?
This is my code:
require 'PHPExcel.php';
require 'PHPExcel/Writer/Excel2007.php';
require 'PHPExcel/IOFactory.php';
$user = "root";
$pass = "admin";
$host = "localhost";
$db = "hrtms";
$dept = "WAREHOUSE/DRIVER";
$TimeIn = "";
$LunchOut = "";
$LunchIn = "";
$TimeOut = "";
$objPHPExcel = new PHPExcel();
try{
$con = new PDO("mysql:host=$host;dbname=$db",$user,$pass);
$con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$con->exec('SET NAMES "utf8"');
}
catch(PDOException $e){
echo $e->getMessage();
exit();
}
try{
$query = $con->prepare("SELECT * FROM emptb WHERE Department = :dept ORDER BY id ASC");
$query->bindParam(':dept',$dept);
$query->execute();
}
catch(PDOException $e){
echo $e->getMessage();
exit();
}
$objPHPExcel->setActiveSheetIndex(0);
//set default font
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setName('Verdana');
//set titles
$objPHPExcel->getActiveSheet()->SetCellValue('B1','EMPLOYEE ATTENDANCE LOGS');
//$objPHPExcel->getActiveSheet()->getStyle('B1')->getAlignment()->setWrapText(true);
//merge cells
$objPHPExcel->getActiveSheet()->mergeCells('B1:T1');
$objPHPExcel->getActiveSheet()->mergeCells('C4:D4');
$objPHPExcel->getActiveSheet()->mergeCells('E8:F8');
//set text alignment
$objPHPExcel->getActiveSheet()->getStyle('B1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setSize(18);
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFill()->getStartColor()->setARGB('#333');
//set column width
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(6.14);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(0.67);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(10.86);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(1.43);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(9.71);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(1.43);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(6.71);
$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(1.57);
$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(2);
$objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(9);
$objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(0.58);
$objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(0.92);
$objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(9);
$objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(1.71);
$objPHPExcel->getActiveSheet()->getColumnDimension('O')->setWidth(2.43);
$objPHPExcel->getActiveSheet()->getColumnDimension('P')->setWidth(6.14);
$objPHPExcel->getActiveSheet()->getColumnDimension('Q')->setWidth(1.71);
$objPHPExcel->getActiveSheet()->getColumnDimension('R')->setWidth(9.29);
$objPHPExcel->getActiveSheet()->getColumnDimension('S')->setWidth(4);
$objPHPExcel->getActiveSheet()->getColumnDimension('T')->setWidth(0.67);
$objPHPExcel->getActiveSheet()->getColumnDimension('U')->setWidth(0.67);
//set text alignment
$rowCount = 4;
while($row = $query->fetch())
{
$rowTitle = $rowCount + 2;
$rowTitle1 = $rowCount + 4;
//data label
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->mergeCells('C'.($rowCount).':D'.($rowCount));
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount,'ID No:');
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->mergeCells('C'.($rowTitle).':D'.($rowTitle));
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle)->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowTitle,'Name:');
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowCount)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->mergeCells('I'.($rowCount).':J'.($rowCount));
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowCount)->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowCount)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowCount)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowCount)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('I'.$rowCount,'Dept:');
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle1)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->mergeCells('C'.($rowTitle1).':D'.($rowTitle1));
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle1)->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle1)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle1)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle1)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowTitle1,'Section:');
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowTitle1)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->mergeCells('I'.($rowTitle1).':J'.($rowTitle1));
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowTitle1)->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowTitle1)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowTitle1)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowTitle1)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('I'.$rowTitle1,'Line:');
//data contents
$objPHPExcel->getActiveSheet()->mergeCells('E'.($rowCount).':G'.($rowCount));
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowCount)->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->SetCellValue('E'.$rowCount,$row['EmpID']);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowCount)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowCount)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowCount)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->mergeCells('E'.($rowTitle).':S'.($rowTitle));
$objPHPExcel->getActiveSheet()->SetCellValue('E'.$rowTitle,$row['Lastname'] . ', ' . $row['Firstname']);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowTitle)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowTitle)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowTitle)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->mergeCells('L'.($rowCount).':S'.($rowCount));
$objPHPExcel->getActiveSheet()->SetCellValue('L'.$rowCount,$row['Department']);
$objPHPExcel->getActiveSheet()->getStyle('L'.$rowCount)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('L'.$rowCount)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('L'.$rowCount)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('E'.$rowTitle1,$row['SectionName']);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowTitle1)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowTitle1)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowTitle1)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('L'.$rowTitle1,$row['LineName']);
$objPHPExcel->getActiveSheet()->getStyle('L'.$rowTitle1)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('L'.$rowTitle1)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('L'.$rowTitle1)->getFont()->setName('Arial');
$rowCount++;
try{
$subquery = $con->prepare("SELECT c.dt,a.TimeIn,a.LunchOut,a.LunchIn,a.RNDOUT FROM cal c LEFT JOIN attendance a ON a.ValidDate = c.dt
AND a.EmpID = :id WHERE c.dt BETWEEN DATE('2015-08-01') AND DATE('2015-08-30') GROUP BY c.dt ORDER BY c.dt ASC");
$subquery->bindParam(':id',$row['EmpID']);
$subquery->execute();
}
catch(PDOException $e){
echo $e->getMessage();
exit();
}
$rowCount += 6;
while($subrow = $subquery->fetch())
{
if($subrow['TimeIn'] == "00:00:00")
{
$TimeIn = "";
}
else
{
$TimeIn = $subrow['TimeIn'];
}
if($subrow['LunchOut']=="00:00:00")
{
$LunchOut = "";
}
else
{
$LunchOut = $subrow['LunchOut'];
}
if($subrow['LunchIn']=="00:00:00")
{
$LunchIn = "";
}
else
{
$LunchIn = $subrow['LunchIn'];
}
if($subrow['RNDOUT']=="00:00:00")
{
$TimeOut = "";
}
else
{
$TimeOut = $subrow['RNDOUT'];
}
$titleRow = 10;
$objPHPExcel->getActiveSheet()->getStyle('C'.$titleRow)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('C'.$titleRow)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.$titleRow)->getFont()->setSize(11);
$objPHPExcel->getActiveSheet()->getStyle('C'.$titleRow)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$titleRow,'Date');
$objPHPExcel->getActiveSheet()->getStyle('E'.$titleRow)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('E'.$titleRow)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('E'.$titleRow)->getFont()->setSize(11);
$objPHPExcel->getActiveSheet()->getStyle('E'.$titleRow)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('E'.$titleRow,'TimeIn');
$objPHPExcel->getActiveSheet()->getStyle('G'.$titleRow)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('G'.$titleRow)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('G'.$titleRow)->getFont()->setSize(11);
$objPHPExcel->getActiveSheet()->getStyle('G'.$titleRow)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('G'.$titleRow,'LunchOut');
$objPHPExcel->getActiveSheet()->getStyle('J'.$titleRow)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('J'.$titleRow)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('J'.$titleRow)->getFont()->setSize(11);
$objPHPExcel->getActiveSheet()->getStyle('J'.$titleRow)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('J'.$titleRow,'LunchIn');
$objPHPExcel->getActiveSheet()->getStyle('M'.$titleRow)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('M'.$titleRow)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('M'.$titleRow)->getFont()->setSize(11);
$objPHPExcel->getActiveSheet()->getStyle('M'.$titleRow)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('M'.$titleRow,'TimeOut');
$titleRow++;
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getFont()->setSize(10);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount,$subrow['dt']);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowCount)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowCount)->getFont()->setSize(10);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowCount)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('E'.$rowCount,$TimeIn);
$objPHPExcel->getActiveSheet()->getStyle('G'.$rowCount)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('G'.$rowCount)->getFont()->setSize(10);
$objPHPExcel->getActiveSheet()->getStyle('G'.$rowCount)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('G'.$rowCount,$LunchOut);
$objPHPExcel->getActiveSheet()->getStyle('J'.$rowCount)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('J'.$rowCount)->getFont()->setSize(10);
$objPHPExcel->getActiveSheet()->getStyle('J'.$rowCount)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('J'.$rowCount,$LunchIn);
$objPHPExcel->getActiveSheet()->getStyle('M'.$rowCount)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('M'.$rowCount)->getFont()->setSize(10);
$objPHPExcel->getActiveSheet()->getStyle('M'.$rowCount)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('M'.$rowCount,$TimeOut);
$rowCount++;
}
}
$excelWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel2007');
header('Content-Type:application/ms-excel');
header('Content-Disposition:attachment;filename="'.$dept.'.xlsx"');
header('Cache-Control:max-age=0');
$excelWriter->save('php://output');
If you mean every 30 rows of the spreadsheet, then use the print setup options as described in the documentation:
$objPHPExcel->getActiveSheet()
->setBreak('A10' , PHPExcel_Worksheet::BREAK_ROW);
will set a print break on row 10
So just set those breakpoints every 30 rows as you're building the worksheet
You only need to use \n if you want to control exactly where a line wraps.
Example:
$objPHPExcel->getActiveSheet()->setCellValue('H5', "Hello\nWorld");
You should always use double quotes when you add escape sequences in a PHP string.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What’s wrong with my PHP curl request, please help .. I’m not getting any data back
I'm posting XML data to a URL that is supposed to send me (echo) back results, and instead of sending them back to me , this is what I get after running the PHP .. My curl code is below this result ... I am suspecting that something might be wrong with my CURL code below, how can I actually get the results back from the XML data posted to the URL(mysgproc.php), I posted the url code as well ? Thanks a bunch
HTTP/1.1 200 OK
Date: Fri, 19 Oct 2012 16:30:26 GMT
Server: Apache/2.2.9 (Fedora)
Set-Cookie: ZDEDebuggerPresent=php,phtml,php3; path=/
Content-Length: 238
Connection: close
Content-Type: text/html
<?xml version="1.0" encoding="UTF-8"?><iniResponseMsg deliveryTimeStamp="19/10/2012 16:30:26 GMT" messageID="9d085e45-9e9b-11da-befd-0014221b359d" correlationID="69c8277d-77af-4fd9-8cc0-7c30d2963bee"> <state>fail</state></iniResponseMsg>
Below is my code ...
<?php
$url ="http://127.0.0.1/sens/msgproc.php";
$xml_data = file_get_contents("/usr/local/www/data/message_test.xml");
#$header ="POST HTTP/1.0 \r\n";
#$header .="Content-type: text/xml \r\n";
#$header .="Content-length: ".strlen($xml_data)." \r\n";
#$header .="Content-transfer-encoding: text\r\n";
#$header .="Connection: close \r\n\r\n";
#$header .= $xml_data;
$headers = array('Content-Type: text/xml','Content-Transfer-Encoding: text','Connection: close');
$ch = curl_init();
curl_setopt ($ch,CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$xml_data);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch, CURLOPT_TIMEOUT, 4);
#curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $header);
$data = curl_exec($ch); // if the post is successful , the server will return some data.
#$info = curl_getinfo($ch);
#
#if(!curl_errno($ch))
# echo 'It took '.$info['total_time'].'seconds to send a request to'.$info['url'];
#
# else
#
curl_close($ch);
echo $data;
?>
Here is the msgproc.php code
<?php
//$pass='go';
/*******************************************************************************
* COMPONENT NAME:
* msgproc.php
*
* DESCRIPTION:
* This script accepts the various XML documents from G*.
* The document is passed to the correct routine
* in msgproc.php based on what it is.
*
*******************************************************************************/
require('sensdb.php');
require('dbutil.php');
require('msgproc_util.php');
// first this is to pipe all output to the buffer for loggin later in the file
// echo and print statements will get logged instead of outputted
ob_start();
//$raw_post_data = $HTTP_RAW_POST_DATA;
$raw_post_data = file_get_contents("php://input");
$time_log = date("d/m/Y G:i:s") . ' - aeroastro sensor sys time';
/* CONNECT TO THE DATABASE */
sensdb_connect();
$script_time = date("M-d-Y H:i:s");
// logging variables
$type='';
$byte_count=0;
$message_id='';
$error='';
$error_type='';
$source = $_SERVER['REMOTE_ADDR'];
/*******************************************************************************
* COMPONENT NAME:
* main process
*
* DESCRIPTION:
*
*******************************************************************************/
/****** formerly function test_read_xml_post() ***********************/
//$fp = fopen("/usr/local/www/data/sensor/sens/message_test.xml", "r");
//$fp = fopen("php://input", "r");
echo "string length:" . strlen($raw_post_data) . ' ';
// reject all data not from Globalstar of development
//if ( $source == "207.88.248.142" ) {
$data = trim($raw_post_data);
//} else {
// $data = NULL;
//}
$byte_count += strlen($data);
//fclose($fp);
// test of php5 parsing xml .... much easier
if ( $xml = simplexml_load_string($data) ) {
// innocent until proven guilty
$status = true;
// this will help us find the root element to determine message type
$dom = dom_import_simplexml($xml);
$xml_root = $dom->tagName;
// process stumessages here
if ( $xml_root == 'stuMessages' ) {
$type = 'STxMessage';
// what is the message id
$xml_messageID = $xml->xpath('/stuMessages/#messageID');
foreach ( $xml_messageID as $id ) {
$message_id = $id;
}
// what is the packet time
$packetTimes = $xml->xpath('/stuMessages/#timeStamp');
foreach ( $packetTimes as $_time ) {
$packetTime = $_time;
}
$time_log .= "\n". $packetTime . ' - globalstar packet time';
// how many messages
$message_count = count($xml->xpath('/stuMessages/stuMessage'));
if ( $message_count >= 1 ) {
// fomat the sql string
$sql = get_msglog_sql($type, $source, $byte_count, $message_id, $error );
if ( mysql_query($sql) ) {
// get the insert id
// be careful not to change the sql above which might break our ability here to get the last insert id
$incoming_id = mysql_insert_id();
echo $script_time . " - stu_message packet $message_id logged: insert_id:$incoming_id";
} else {
echo $script_time . " - stu_message failed logging";
}
// mysql_query("LOCK TABLES STxMessage WRITE");
// mysql_query("SET AUTOCOMMIT = 0");
mysql_query("BEGIN");
foreach( $xml->stuMessage as $stuMessage ) {
$unixtime = $stuMessage->unixTime;
$gps = $stuMessage->gps;
$payload = $stuMessage->payload;
// convert to an ESN int
$esn = $stuMessage->esn;
$esn = esn_to_num($esn);
// test the message time against system time
// JL 2007
$time_log .= "\n" . gmdate("d/m/Y H:i:s", "$unixtime") . " - packet stu message time";
// JL 2006 Apr
// log message data larger than 255 chars for TSM account a la Tony B
// these messages don't fit in our DB
if ( strlen($payload) > 255 ) {
// log any output
$large_message_log = '/usr/local/www/logs/large_message_log';
$sql = 'INSERT INTO STxLargeMessage ( ESN,GPS,Payload,UnixTime,IncomingID) values ("'.$esn.'","'.$gps.'","'.$payload.'","'.$unixtime.'","'.$incoming_id.'")';
// Perform Insert of large message
$result = #mysql_query($sql);
// Let's make sure the file exists and is writable first.
if ( is_writable($large_message_log) ) {
// The file pointer is at the bottom of the file hence
$handle = #fopen($large_message_log, 'a');
// Write $response to our opened file.
#fwrite($handle, "\n".$data);
#fclose($handle);
}
}
// do we have an ESN for this message
// $select_esn = 'select ESN from STx where ESN = "'.$esn.'"';
// $result = mysql_query($select_esn);
// $result_count = mysql_num_rows($result);
$sql = 'INSERT INTO STxMessage( ESN,GPS,Payload,UnixTime,IncomingID) values ("'.$esn.'","'.$gps.'","'.$payload.'","'.$unixtime.'","'.$incoming_id.'")';
// Perform Insert
$result = mysql_query($sql);
$GMT_unixtime = gmdate("Y-m-d H:i:s", "$unixtime");
$update = 'update STx set MessageCount = MessageCount + 1, LastMessageTime = "' . $GMT_unixtime . '" where ESN = "' . $esn . '"';
// increment the message count by 1
mysql_query($update);
unset($update);
// Check db result
if ( !$result ) {
$status = false;
// log the error
echo 'Invalid query: ' . mysql_error() . "\n";
echo $message .= 'Whole query: ' . $query;
}
unset($result);
unset($unixtime);
unset($gps);
unset($payload);
unset($esn);
}
if ( $status ) {
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");
}
// mysql_query("UNLOCK TABLES");
// mysql_query("SET AUTOCOMMIT = 1");
} else { // no data but valid xml, return pass, probably G* "pining" aeroastro for life
$error = "no data in xml packet id:" . $message_id . "\n";
echo $error;
}
// make our response xml for globalstar
$response = make_globalstar_response_xml('stuResponseMsg', $message_id, $status);
} elseif ( $xml_root == 'prvmsgs' ) { // process prvmsgs messages
/*******************************************************************************
* COMPONENT NAME:
* PRVMSGS
*
* DESCRIPTION:
* These routines accept the PRVMSGS sent by Globalstar in response to the
* INIMSGS that were sent. This routine stores the PRVMSGS into the database,
* and also sends a respose message back to Globalstar.
*
*******************************************************************************/
$type = 'PrvMessage';
// what is the message id
$xml_messageID = $xml->xpath('/prvmsgs/#prvMessageID');
foreach ( $xml_messageID as $id ) {
$message_id = $id;
}
// how many messages
$message_count = count($xml->xpath('/prvmsgs/prvmsg'));
if ( $message_count >= 1 ) {
// fomat the sql string for logging
$sql = get_msglog_sql($type, $source, $byte_count, $message_id, $error );
if ( mysql_query($sql) ) {
// get the insert id
$incoming_id = mysql_insert_id();
echo $script_time . " - PrvMessage packet $message_id logged";
} else {
echo $script_time . " - PrvMessage failed logging";
}
mysql_query("BEGIN");
// loop through the messages
foreach( $xml->prvmsg as $prvmsg ) {
$esn = esn_to_num($prvmsg->esn);
$provid = $prvmsg->provID;
$tstart = $prvmsg->tStart;
$tend = $prvmsg->tEnd;
$txretryminsec = $prvmsg->txRetryMinSec;
$txretrymaxsec = $prvmsg->txRetryMaxSec;
$txretries = $prvmsg->txRetries;
$rfchannel = $prvmsg->rfChannel;
$sql = 'REPLACE INTO PrvMessage ( ESN, ProvID, TStart, TEnd, TxRetryMinSec, TxRetryMaxSec, TxRetries, RFChannel, IncomingID) values ("'.$esn.'","'.$provid.'","'.$tstart.'","'.$tend.'","'.$txretryminsec.'","'.$txretrymaxsec.'","'.$txretries.'","'.$rfchannel.'","'.$incoming_id.'")';
// Perform Insert
$result = mysql_query($sql);
// insert status "change" record
$insert_sql = 'insert INTO STxStatusChangeHistory (StatusChangeID, ESN, Status, StatusChangeTimestamp) values ("","'.$esn.'","Provisioned",NOW())';
// Perform Insert
$insert = mysql_query($insert_sql);
// Check result
if (! $result) {
$status = false;
// log the error
echo 'Invalid provisioning: ' . mysql_error() . "\n";
echo 'Whole query: ' . $sql;
} else {
$sql = 'UPDATE STx SET Status="Provisioned" WHERE ESN ="'.$esn.'"';
$result = mysql_query($sql);
// Check result
if (! $result) {
$status = false;
// log the error
echo 'Invalid STx update during provisioning: ' . mysql_error() . "\n";
echo 'Whole query: ' . $sql;
}
}
unset($result);
unset($esn);
unset($provid);
unset($tstart);
unset($tend);
unset($txretryminsec);
unset($txretrymaxsec);
unset($txretries);
unset($rfchannel);
}
if ( $status ) {
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");
msglog_update($message_id, "PrvMessage INSERT ERROR");
}
}
// make our response xml for globalstar
$response = make_globalstar_response_xml('prvResponseMsg', $message_id, $status);
} elseif ( $xml_root == 'instmsgs' ) { // process instmsgs messages
/*******************************************************************************
* COMPONENT NAME:
* INSTMSGS
*
* DESCRIPTION:
* After the VAR gets the PRVMSGS and installs the RTU, it will send the
* INSTMSG back here to indicate where the unit was installed.
*
*******************************************************************************/
$type = 'InstMessage';
// what is the message id
$xml_messageID = $xml->xpath('/instmsgs/#instMessageID');
foreach ( $xml_messageID as $id ) {
$message_id = $id;
}
// how many messages
$message_count = count($xml->xpath('/instmsgs/instmsg'));
if ( $message_count >= 1 ) {
// fomat the sql string for logging
$sql = get_msglog_sql($type, $source, $byte_count, $message_id, $error );
if ( mysql_query($sql) ) {
// get the insert id
$incoming_id = mysql_insert_id();
echo $script_time . " - InstMessage packet $message_id logged";
} else {
echo $script_time . " - InstMessage failed logging";
}
mysql_query("BEGIN");
// loop through the messages
foreach( $xml->instmsg as $instmsg ) {
$esn = esn_to_num($instmsg->esn);
$provid = $instmsg->provID;
$rfchannel = $instmsg->rfChannel;
$tactual = $instmsg->tActual;
$deltat = $instmsg->deltaT;
$latitude = $instmsg->latitude;
$longitude = $instmsg->longitude;
$txretries = $instmsg->txRetries;
$txoffset = $instmsg->txOffset;
$txretryminsec = $instmsg->txRetryMinSec;
$txretrymaxsec = $instmsg->txRetryMaxSec;
$powerlevel = $instmsg->powerLevel;
$sql = 'REPLACE INTO InstMessage ( ESN
,ProvID
,IncomingID
,RFChannel
,TActual
,DeltaT
,Latitude
,Longitude
,TxRetries
,TxOffset
,TxRetryMinSec
,TxRetryMaxSec
,PowerLevel ) values ("'.$esn.'"
,"'.$provid.'"
,"'.$incoming_id.'"
,"'.$rfchannel.'"
,"'.$tactual.'"
,"'.$deltat.'"
,"'.$latitude.'"
,"'.$longitude.'"
,"'.$txretries.'"
,"'.$txoffset.'"
,"'.$txretryminsec.'"
,"'.$txretrymaxsec.'"
,"'.$powerlevel.'")';
// Perform Insert
$result = mysql_query($sql);
// Check result
if (! $result) {
$status = false;
// log the error
echo 'Invalid InstMessage sql: ' . mysql_error() . "\n";
echo 'Whole query: ' . $sql;
} else {
$sql = 'UPDATE STx SET Status="Installed" WHERE ESN ="'.$esn.'"';
$result = mysql_query($sql);
// Check result
if (! $result) {
$status = false;
// log the error
echo 'Invalid STx update during Install: ' . mysql_error() . "\n";
echo 'Whole query: ' . $sql;
}
}
unset($result);
unset($esn);
unset($provid);
unset($tstart);
unset($tend);
unset($txretryminsec);
unset($txretrymaxsec);
unset($txretries);
unset($rfchannel);
unset($txoffset);
unset($txretryminsec);
unset($txretrymaxsec);
unset($powerlevel);
}
if ( $status ) {
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");
msglog_update($message_id, "InstMessage INSERT ERROR");
}
}
// make our response xml for globalstar
$response = make_globalstar_response_xml('instResponseMsg', $message_id, $status);
} elseif ( $xml_root == 'inimsgs' ) { // process inimsgs messages
/*******************************************************************************
* COMPONENT NAME:
* INIMSGS
*
* DESCRIPTION:
* The 'INIMSGS' are the messages sent to begin the provisioning process. The
* message contains a range of ESN numbers to be provisiond. The 'INIMSGS'
* are forwarded to Globalstar. Then, the 'get_prvmsgs' function is called
* to poll the database for the response 'prvmsgs' that Globalstar will send.
*
*******************************************************************************/
$type = 'inimsgs';
// what is the message id
$xml_messageID = $xml->xpath('/inimsgs/#iniMessageID');
foreach ( $xml_messageID as $id ) {
$message_id = $id;
}
// how many messages
$message_count = count($xml->xpath('/inimsgs/inimsg'));
if ( $message_count >= 1 ) {
/* DONT FORGET - have a trigger in the database to set a default route for NASCORP */
$sql = "INSERT INTO STx (ESN, RouteID, GroupID, SubGroupID, STxModel, STxModelGenType, STxName, Note, Status, FilterProfile) VALUES ";
$sep = "";
/* FOR EACH OF THE MESSAGES IN THE PACKET.. .*/
foreach ( $xml->inimsg as $inimsg ) {
$groupid = $inimsg->groupID;
$subgroupid = strlen($inimsg->subGroupID) ? $inimsg->subGroupID : 'NULL';
/* FIRST CHECK THAT THE REQUESTED RANGE IS AVAILABLE */
$esnStart = $inimsg->esnStart;
$esnEnd = $inimsg->esnEnd;
$number = check_esn_range($esnStart, $esnEnd, $inuse);
$isreal = ($inimsg->isReal == 'Yes') ? true : false;
$route_id = get_route_id($groupid, $inimsg->routeAddress);
if ( $number > 0 ) {
/* SPLIT THE ESN NUMBER INTO MANUFACTURER AND SERIAL NUMBER */
$esnS = explode('-', $esnStart);
$esnE = explode('-', $esnEnd);
/* FOR EACH ESN IN THE SPECIFIED RANGE... */
for ( $mfg=(int) $esnS[0]; $mfg <= (int) $esnE[0]; $mfg++ ) {
for ( $ser=(int) $esnS[1]; $ser <= (int) $esnE[1]; $ser++ ) {
$sxtmodel = $inimsg->stxModel;
$sxtmodelgentype='1';
switch ($sxtmodel) {
case "101-1":
$sxtmodel = '101';
$sxtmodelgentype = "1";
break;
case "101-2":
$sxtmodel = '101';
$sxtmodelgentype = "2";
break;
case "101-3":
$sxtmodel = '101';
$sxtmodelgentype = "3";
break;
}
$esn = (($mfg << 23) | $ser);
$sql .= $sep;
$sql .= sprintf("(%d ,%d ,%d ,%s ,'%s' ,'%s' ,'%s' ,'%s' ,'%s' ,'%s' )",
$esn
,$route_id
,$groupid
,$subgroupid
,mysql_escape_string($sxtmodel)
,$sxtmodelgentype
,mysql_escape_string($inimsg->stxName)
,mysql_escape_string($inimsg->note)
,$isreal ? 'Initiated' : 'Fake'
,$inimsg->filterProfile);
$sep = ",";
}
}
$groupid = $inimsg->groupID;
$subgroupid = $inimsg->subGroupID;
$esnstart = esn_to_num($inimsg->esnStart);
$esnend = esn_to_num($inimsg->esnEnd);
$stxmodel = $inimsg->stxModel;
$stxname = $inimsg->stxName;
// new filter setting
$filterprofile = $inimsg->filterProfile;
$routeaddress = $inimsg->routeAddress;
// $mobility = $inimsg->mobility;
// $latdefault = $inimsg->latDefault;
// $londefault = $inimsg->lonDefault;
$stxspacing = $inimsg->txSpacing;
// $txfrequency = $inimsg->txFrequency;
// $trequestedstart = $inimsg->tRequestedStart;
// $trequestedend = $inimsg->tRequestedEnd;
$note = $inimsg->note;
$isreal = $inimsg->isReal;
$insert_inimessage = 'INSERT INTO IniMessage (GroupID
,SubGroupID
,ESNStart
,ESNEnd
,STxModel
,STxName
,FilterProfile
,TxSpacing
,RouteAddress
,Note
,IsReal) VALUES ("'.$groupid.'"
,"'.$subgroupid.'"
,"'.$esnstart.'"
,"'.$esnend.'"
,"'.$stxmodel.'"
,"'.$stxname.'"
,"'.$filterprofile.'"
,"'.$stxspacing.'"
,"'.$routeaddress.'"
,"'.$note.'"
,"'.$isreal.'")';
mysql_query("BEGIN");
if ( mysql_query($insert_inimessage) ) {
// not used for anything
$inserted = true;
} else {
$status=false;
}
unset($groupid);
unset($subgroupid);
unset($esnstart);
unset($esnend);
unset($stxmodel);
unset($stxname);
unset($filterprofile);
unset($routeaddress);
unset($mobility);
unset($stxspacing);
unset($note);
unset($isreal);
} else {
$status = false;
echo $script_time . " invalid ESN range\n".$raw_post_data;
}
}
/* IF THE CONTENTS OF THE MESSAGE LOOKED OK, THEN COMMIT
IT TO THE DATABASE... */
/* CREATE THE STx TABLE ENTRIES */
if ( $status ) {
if ( $status = mysql_query($sql) ) {
mysql_query("COMMIT");
} else {
$doc->errors = mysql_error();
mysql_query("ROLLBACK");
}
} else {
$doc->errors = mysql_error();
mysql_query("ROLLBACK");
}
} else {
$status = false;
echo $script_time . " no messages in xml \n".$raw_post_data;
}
// make our response xml for globalstar
$response = make_globalstar_response_xml('iniResponseMsg', $message_id, $status);
}
} else {
// failed to load xml so lets fail
$status=false;
$response = make_globalstar_response_xml('xml_error', 0, $status);
echo $script_time . " - xml error\n" . $raw_post_data;
}
// log any output
$msgproc_log = '/usr/local/www/logs/msgproc_log';
// collect any trash here for logging
$buffer_string = ob_get_contents()."\n";
// Let's make sure the file exists and is writable first.
if ( is_writable($msgproc_log) ) {
// The file pointer is at the bottom of the file hence
$handle = #fopen($msgproc_log, 'a');
// Write $response to our opened file.
#fwrite($handle, $buffer_string);
#fclose($handle);
}
//empty buffer to logs so that globalstar gets response only
ob_end_clean();
mysql_close();
// send the output for Globalstar to see
echo $response;
?>
msgproc.php has dependencies. No one has the time to debug it. So do this:
Try tracing into the server processing code.
echo __LINE__, PHP_EOL; flush(); // every few lines :)
// even followed by a die; to slowly move deeper into the code
Poor man's debugging. And see where output stops, slowly pinpoint the issue. Also set_error_handler and set_exception_handler and see if anything gets caught.