cakephp error while saving data - php

i am working on a cakephp 2.x ... well the scenario is that i am sending messages to my webapp ... there are almost 509 messages ... the problem is it is saving some messages into db and on some messages it gives me an error on android console ... ...so first thing i want to ask what u all think that where the actual problem lies or can be lie..and the other think is there a way that i can throw some exception error on data which is not saving into the db .. so i can track the particular messages which is not saving into and causing the problem ...i need some help in debugging this code
here is my code
public function message(){
$this->loadModel('Message');
if ($this->request->isPost()){
$json = $this->request->data('json');
$data = json_decode($json, TRUE);
foreach($data as $datas){
$date = $datas['date'];
$mobileNo = $datas['mobileNo'];
$mobileNo = AllSecure::replaceDashesAndSpaces($mobileNo);
$body = $datas['body'];
$timestamp = $date/1000;
$date = date('Y-m-d h:i' , $timestamp);
$this->request->data['Message']['mobileNo'] = $mobileNo;
$this->request->data['Message']['body'] = $datas['body'];
$this->request->data['Message']['type'] = $datas['type'];
$this->request->data['Message']['User_id'] = $datas['idUser'];
$this->request->data['Message']['dateTime'] = $date;
$count = $this->Message->checkTextMessages($mobileNo,$body,$date,$datas['idUser']);
if($mobileNo!=null){
if($count>0){
}else{
$this->Message->create();
$this->Message->save($this->request->data
}
}
}
}
}

well i solved my problem by self ... i dont know why it is causing the problem ... so i did this .. and it works
foreach($data as $datas){
$i=0
$this->request->data['Message'][$i]['mobileNo'] = $datas['mobileNo'];;
$this->request->data['Message'][$i]['body'] = $datas['body'];
$this->request->data['Message'][$i]['type'] = $datas['type'];
$this->request->data['Message'][$i]['User_id'] = $datas['idUser'];
$i++;
if($mobileNo!=null){
}
}
$isSave = $this->Message->saveAll($this->request->data["Message"]);
echo $isSave;

Related

PHP: Script failing after PDO query

During my create user process I make a few queries to various database's to get the new user setup. This script has been working fine for about a year and a half, but now something is off.
So the first thing I do is I check to see if a user exists with the credentials being submitted. I've thoroughly tested the check and I'm confident my issue isn't there.
If that check comes back false then the script continues to create the user.
public function registerUser() {
parse_str($_SERVER['QUERY_STRING'], $data);
$data = (object) $data;
$check = json_decode($this->checkUserExists($data->email));
if ($check->res) {
$res = new \stdClass();
$res->res = false;
$res->user_status = $check->user_status;
$res->msg = 'User exists.';
echo json_encode($res);
}
if (!$check->res) {
$this->createUser($data);
}
}
The problem arises after all the queries have been completed, the script does not seem to want to run the if statement at the bottom. I marked it with comment characters so it's easier to find, but I included the entire function for clarity, maybe I'm doing something that is causing the issue.
I tried invoking an error manually at various points during the script. And I am able to trigger an error all the way down to the bottom of the script.
private function createUser($data) {
$Crypt = new CryptController();
$AuthSelect = new AuthController();
$Time = new TimeController();
$remote_address = new RemoteAddressController();
$Session = new SessionController();
$AuthInsert = new AuthModel_Insert();
$hashed_password = $Crypt->create_hash($data->password);
$data->password = '';
$AuthData = json_decode($AuthSelect->getAuth());
$system_auth_id = $AuthData->system_auth_id;
$user_id = $Crypt->get_uuid();
$user_auth_id = $Crypt->get_uuid();
$user_createddate = $Time->time();
$user_updateddate = $Time->time();
$user_lastupdateddate = $Time->time();
$agent_ip = $remote_address->getIpAddress();
$userData = $this->createUserObject(
$user_id,
$user_auth_id,
$system_auth_id,
$hashed_password,
$user_createddate,
$user_updateddate,
$user_lastupdateddate,
$data
);
$agentData = $this->createAgentObject(
$user_id,
$agent_ip,
$data
);
//////////////////////////////////////////
$create_user = $AuthInsert->createNewUser(
$userData
);
$create_user_agent = $this->setUserAgent(
$agentData
);
$sessionKeyData = new \stdClass();
$sessionKeyData->user_id = $user_id;
$sessionKeyData->user_auth_id = $user_auth_id;
$sessionKeyData->system_auth_id = $system_auth_id;
$sessionKeyData->agent_id = $create_user_agent->agent->agent_id;
$set_session_key = $Session->setSessionKey(
$sessionKeyData
);
$send_activation_email = $this->createUserActivation(
$userData
);
if (
$create_user &&
$create_user_agent->res &&
$set_session_key->res &&
$send_activation_email->res) {
$res = new \stdClass();
$res->res = true;
$res->msg = 'New user successfully created.';
echo json_encode($res);
} else {
$res = new \stdClass();
$res->res = false;
$res->msg = 'Error: User creation process incomplete.';
echo json_encode($res);
}
//////////////////////////////////////////
trigger_error("Invoked Error: ",E_USER_ERROR);
}
The queries themselves go through just fine, all the tables are populated just fine. The issue is that after that happens the script doesn't finish. It seems to end the createUser() function and return to the registerUser() function at which point the user will exist so it will return false and echo that back to the client.
In my testing it seems my issue might be at the bottom with that if statement. But I've tested each of those queries individually and they do return the desired booleans to get the true condition. But, even the false condition doesn't go through which should return 'Error: User creation process incomplete.'. That doesn't happen either.
I'm hoping someone sees something I'm missing because I've been stuck on this problem for too long. I appreciate any guidance that might lead me to an answer. Thanks in advance.
Just for clarification the message I'm getting back is $res->msg = 'User exists.'; which comes from registeruser(). The message I'm expecting back is $res->msg = 'New user successfully created.'; which should come from createUser().

JSON is overwriting the old data how to keep on adding data with new ID

so, I am working on a JSON file that should keep on incrementing IDs.
However I get stuck at id:0 and when I insert new data the old data will be replaced by the new one (it keeps id:0).
I am not entirely sure what code is related and what not, so I will post whatever I think should be related and if someone with more knowledge related to JSON could adjust (in case it needs any) it, I would appreciate it a lot.
The include database_json.php contains the following code:
$databaseFile = file_get_contents('json_files/database.json');
$databaseJson = json_decode($databaseFile, true);
$database = $databaseJson['data'];
// below starts a new page, the page that submits the form called saveJson.php
include_once('database_json.php');
$data = $_POST;
//Setup an empty array.
$errors = array();
if (isset($data)) {
$newExerciseData = $data;
$exerciseArray = $data['main_object'];
$databaseFile = 'json_files/database.json';
$textContent = file_get_contents($databaseFile);
$database = json_decode($textContent, true);
if ($data['id'] === 'new') {
if (count($database['data']) == 0) {
$ID = 0;
} else {
$maxID = max($database['data']);
$ID = ++$maxID["id"];
}
$newJsonFile = 'jsonData_' . $ID . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData = array(
'id' => $ID,
// a lot of variables that aren't related to the problem
);
$database['data'][] = $newArrayData;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
} else {
$index = array_search((int) $_POST['id'], array_column($database['data'], 'id'));
$correctJsonFile = 'json_files/jsonData_' . $_POST['id'] . '.json';
$newJsonFile = 'jsonData_' . $_POST['id'] . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData2 = array(
'id' => (int) $_POST['id'],
// more not related to problem variables
);
$database['data'][$index] = $newArrayData2;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE));
}
echo json_encode($newExerciseData, JSON_UNESCAPED_UNICODE);
}
EDIT: someone wanted me to post how the JSON itself looked like... so this is how it looks:
The file is called: database.json
{
"data":
[
{
"id":0,
"exercisetitle":"Test300520180924",
"exerciseWord":["huiswerk"],
"syllables":["Huis","werk"],
"file":"jsonData_.json",
"audio":null,"language":null
}
]
}
(do not mind the audio and language, that's something for later on.
The best I could do was this, yes I read the stuff about making a post and how to properly format stuff etc. but I people would often say I need to include certain code etc etc. and it mostly would turn out messy as hell, so I would rather have a bit too much code (the code I think is related) then not have enough.
Cheers!

Writing .php file using php code

Hi there I'm trying to write a .php file using this code, server replying this error : syntax error, unexpected '0' (T_LNUMBER) in
I wanna know how can I write integer in php file as you can see
$status1 = \''0'\';
This code having problem, anybody please tell me what to do.
<?php
if(isset($_POST['user1'])){
$data = urldecode('%3C').'?php
$user1 = \''.$_POST['user1'].'\';
$pass1 = \''.$_POST['pass1'].'\';
$status1 = \''0'\';
$user2 = \''.$_POST['user2'].'\';
$pass2 = \''.$_POST['pass2'].'\';
$status2 = \''0'\';
$user3 = \''.$_POST['user3'].'\';
$pass3 = \''.$_POST['pass3'].'\';
$status3 = \''0'\';
$user4 = \''.$_POST['user4'].'\';
$pass4 = \''.$_POST['pass4'].'\';
$status4 = \''0'\';
$user5 = \''.$_POST['user5'].'\';
$pass5 = \''.$_POST['pass5'].'\';
$status5 = \''0'\';
$user6 = \''.$_POST['user6'].'\';
$pass6 = \''.$_POST['pass6'].'\';
$status6 = \''0'\';
$user7 = \''.$_POST['user7'].'\';
$pass7 = \''.$_POST['pass7'].'\';
$status7 = \''0'\';
$user8 = \''.$_POST['user8'].'\';
$pass8 = \''.$_POST['pass8'].'\';
$status8 = \''0'\';
$user9 = \''.$_POST['user9'].'\';
$pass9 = \''.$_POST['pass9'].'\';
$status9 = \''0'\';
$user10 = \''.$_POST['user10'].'\';
$pass10 = \''.$_POST['pass10'].'\';
$status10 = \''0'\';
?'.urldecode('%3E');
$fx=fopen('datauser.php','w');
fwrite($fx,$data);
fclose($fx);
if($fx === false) {
header("Location: ./tokensettings.php?save=err");
}
else {
header("Location: ./tokensettings.php?save=success");
}
}
?>
Thank you so much.
Here is how my form looks like.
If you still want to do it your way you need to use the \ correctly for each ' to be included in the string even those in [ ] - not saying the final string produced would actually work but it is based on your code and my best guess at your desired result
<?php
$string1=' \'\'.$_POST[\'user1\']\'\';';
$string1=$string1.'\'\'0\'\';';
echo $string1;
?>
The whole urlencoding stuff is not needed at all, your quoting and escaping is messy and incorrect. and why not simply use file_put_contents? Use HEREDOC to avoid messy escaping.
file_put_contents('datauser.php', <<<CONTENT
<?php
\$user = '{$_POST['user']}';
\$pass = '{$_POST['pass']}';
\$status = '0';
CONTENT
);
but if you really want to use files as data storage, I would encourage you to save it in a data format like xml or json instead of writing php.
// save data to file ($_POST used as example...)
file_put_contents('user.json', json_encode($_POST));
// read data
$data = json_decode(file_get_contents('user.json'));

get json data in function php

I am new in this json chapter.I have a file named mysql_conn.php .This file have a php function to call data from mysql database.So can anyone help me to create one json file to get data from mysql_conn.php.Below is my code
mysql_conn.php
function getWrkNoTest($wrkno){
$conf = new BBAgentConf();
$log = new KLogger($conf->get_BBLogPath().$conf->get_BBDateLogFormat(), $conf->get_BBLogPriority() );
$connection = MySQLConnection();
$getWrkNoTest ="";
$lArrayIndex = 0;
$query = mysql_query("
SELECT
a.jobinfoid,
a.WRKNo,
a.cate,
a.det,
a.compclosed,
a.feedback,
a.infoID,
b.callerid,
b.customername
FROM bb_jmsjobinfo a
LEFT JOIN bb_customer b
ON a.customerid = b.customerid
WHERE a.WRKNo = '$wrkno';"
);
$result = mysql_query($query);
$log->LogDebug("Query[".$query."]");
while ($row = mysql_fetch_array($result)){
$getWrkNoTest = array("jobinfoid"=>$row['jobinfoid'],
"WRKNo"=>$row['WRKNo'],
"cate"=>$row['cate'],
"det"=>$row['det'],
"compclosed"=>$row['compclosed'],
"feedback"=>$row['feedback'],
"infoID"=>$row['customerid'],
"customerid"=>$row['infoID'],
"callerid"=>$row['callerid'],
"customername"=>$row['customername']);
$iList[$lArrayIndex] = $getWrkNoTest;
$lArrayIndex = $lArrayIndex + 1;
}
$QueryResult = print_r($getWrkNoTest,true);
$log->LogDebug("QueryResult[".$QueryResult."]");
closeDB($connection);
return $iList;
}
json.php
if ($_GET['action']=="getJsonjms"){
$wrkno = $_GET["wrkno"];
if($wrkno != ""){
$jms = getWrkNoTest($wrkno);
if(!empty($jms)){
echo json_encode($jms);
}else{
echo "No data.";
}
}else{
echo "Please insert wrkno";
}
}
I dont know how to solve this.Maybe use foreach or something else.Sorry for my bad english or bad explanation.I'm really new in this json things. Any help will appreciate.Thanks
If I understand your question right, you want to convert the results you receive from your MySQL query into JSON and then store that data into a file?
If this is correct, you can build off of what you currently have in json.php. In this block here, you use json_encode():
if(!empty($jms)){
echo json_encode($jms);
}
We can take this data and pass it to file_put_contents() to put it into a file:
if (!empty($jms)) {
$json = json_encode($jms);
// write the file
file_put_contents('results.json', $json);
}
If this is a script/page that's visited frequently, you'll want to make the filename (above as results.json) into something more dynamic, maybe based on the $wrkno or some other schema.

Timeout Issue file_get_contents?

Hey I've a problem with my code.
It works fine for the first 10 name, but then "file_get_contents" return just empty strings
Is this a timeout problem? or has it a other reason?
And how can i fix this?
my Code:
<?php
$member;
mysql_connect("localhost","**********","********");
mysql_select_db('bf3_ezstats');
$sql = mysql_query('SELECT id, name FROM ez2bf3_player ORDER BY id ASC');
while($row = mysql_fetch_assoc($sql)){
$member[$row['id']] = $row['name'];
}
mysql_close();
print_r($member);
foreach ($member as $ip => $player){
ini_set('default_socket_timeout', 120);
$SC = file_get_contents('http://battlelog.battlefield.com/bf3/user/'.$player);
$SC = split('<surf:container id="profile-gamereport-previews">',$SC);
$SC = split('</surf:container>',$SC[1])[0];
$IPs = array(0=>$player);
while(strpos($SC,'href') !== false){
$start = strpos($SC,"href");
$end = strpos($SC,'"',$start+6);
$IP= substr($SC,$start,$end-$start);
$IPs[] = "http://battlelog.battlefield.com".str_replace('href="',"",$IP);
$SC = substr($SC,$end,strlen($SC)-1);
}
print_r($IPs);
}
?>
file_get_contents() on external URIs is just a huge security issue. This method could lead to many errors, probably including yours.
If you need to work on external servers, through HTTP, I strongly recommand the use of cURL (http://php.net/manual/fr/book.curl.php). You'll find it more handy, I think, and you may save yourself a lot of trouble.

Categories