Sorry if I'm not good at formulating questions or if this isn't a good question, but I've been trying for days and getting no progress on this and I'm ready to effing cry. Please, please help.
So this PHP file:
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], true);
$conn = new mysqli("localhost", "user", "password", "database");
$i = 1;
$message = array();
while ($i < 31){
$query = $conn->prepare("SELECT dag, maand, jaar, timeslot FROM boeker WHERE dag = $i AND maand = ? AND jaar = ?");
$query->bind_param('ii', $obj["monthQ"], $obj["yearQ"]);
$query->execute();
$result = $query->get_result();
$outp = $result->fetch_all(MYSQLI_ASSOC);
$message = array();
if(empty($result)){
//available
} else if ($result["timeslot"] == null){
array_push($message, "occupied", $i);
} else {
array_push($message, $result["timeslot"], $i);
}
$i++;
}
$package = json_encode($message);
echo $package;
?>
is getting this request:
https://url/file.php?x='{"monthQ":10,"yearQ":2021}'
and the reply is an empty Response Payload, which throws an error, because it can't be JSON.parsed
I would think that $message, even when the array stays empty, would make $package a simple [], which should parse...
Is something wrong with my PHP?
Thanks for any help!
You need to remove the single quotes around the json string in your url. If you have no control over constructing that url, you can just run:
$obj = json_decode(trim($_GET['x'],"'"), true);
I've tested that, and it works.
If you do have control over constructing that url, I recommend that you remove the single quotes AND urlencode the json block.
Leaving breadcrumbs after solving a similar problem here. My php.ini file had a max_post_size set to 2K and I was sending a POST request with size >2K. PHP decided to sweep the problem under the rug and proceed with the request with an empty body.
Related
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!
I understand that similar general questions exist, but none of them follow my specific set of circumstances, and none of them really provide a solution.
Inside the same folder on the server, I have two files: "quiz_maker.php"
and "master_data.php."
I send a JSON object to "master_data.php" from "quiz_maker.php" with the following Ajax code:
if(localStorage.getItem("JSON Question Data Object") != null){
//The JSON object was stringified before saving to localStorage.
var dataString = localStorage.getItem("JSON Question Data Object");
$.ajax({
method: "POST",
url: "master_data.php",
data: { jsonDataObject: dataString },
success: function(msg){
console.log(msg + "\n");
}
});
}
Then, in "master_data.php", I receive it as follows:
if(isset($_POST['jsonDataObject'])){
echo "set";
$masterQuestionData = $_POST['jsonDataObject'];
$masterQuestionData = json_decode($masterQuestionData, TRUE);
//Perform MySQL Queries here.
}
else{
echo "not set";
}
When I run the code on "quiz_maker.php", the Ajax success handler fires, and I receive the string "set" in the console as I would expect. However, if I look at the "master_data.php" file, the string "not set" gets echoed out, and the following notice is displayed:
Notice: Undefined index: `jsonDataObject` in
/home/sites/5a/0/03891393e8/public_html/master_data.php on line 35
Furthermore, all the MySQL queries execute perfectly using the allegedly "undefined index" "jsonDataObject".
What would be the reason why Ajax's success handler fires, gives me the string "set" and all of the queries work, but I get an undefined index notice on master_data.php?
Thank you.
As requested, here is the whole master_data.php file:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
$booleanSuccessfulOne = false;
$booleanSuccessfulTwo = false;
$servername = "[REDACTED]";
$username = "[REDACTED]";
$password = "[REDACTED]";
// Create connection
$link = mysqli_connect($servername, $username, $password, $username);
// Check connection
if (mysqli_connect_error()) {
$alert = "Oops! We're having trouble publishing your questions and
answers right now. Please try again later.";
die($alert);
}
if(isset($_POST['jsonDataObject'])){
echo "set";
$masterQuestionData = $_POST['jsonDataObject'];
// Unescape the string values in the JSON array
$masterQuestionData = $_POST['jsonDataObject'];
// Decode the JSON array
$masterQuestionData = json_decode($masterQuestionData, TRUE);
$maxQuestions = $masterQuestionData["statistics"][0]["totalQuestions"];
for($i = 1; $i <= $maxQuestions; $i++){
$question = $masterQuestionData["block"][$i-1]["question"];
$answer = $masterQuestionData["block"][$i-1]["answer"];
$query = "INSERT INTO `master` (`id`, `question`, `solution`)
VALUES('".$i."', '".$question."', '".$answer."') ON DUPLICATE KEY
UPDATE `id` = '".$i."', `question` = '".$question."', `solution` =
'".$answer."'";
mysqli_query($link, $query);
}
$query = "DELETE FROM `master` WHERE `id` > '".$maxQuestions."'";
mysqli_query($link, $query);
}
else{
echo "not set";
}
There shouldn't be spaces in the item key for localstorage. The rest of my suggestions are in the chat comments.
localStorage.getItem("JSON Question Data Object");
Can you try the following below and let us know what happens? Change all of your getItem() and setItem() to have no spaces.
localStorage.getItem("JSON");
I believe it should fix up this issue because the rest of your ajax & php looks fine.
That said, you can use bracket notation if you want
localStorage['JSON Question Data Object']
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.
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.
I have this code:
<?php
foreach($items as $item) {
$site = $item['link'];
$id = $item['id'];
$newdata = $item['data_a'];
$newdata2 = $item['data_b'];
$ch = curl_init($site.'updateme.php?id='.$id.'&data1='.$newdata.'&data2='.$newdata2);
curl_exec ($ch);
// do some checking here
curl_close ($ch);
}
?>
Sample input:
$site = 'http://www.mysite.com/folder1/folder2/';
$id = 512522;
$newdata = 'Short string here';
$newdata = 'Another short string here with numbers';
Here the main process of updateme.php
if (!$id = intval(Tools::getValue('id')))
$this->_errors[] = Tools::displayError('Invalid ID!');
else
{
$history = new History();
$history->id = $id;
$history->changeState($newdata1, intval($id));
$history->id_employee = intval($employee->id_employee);
$carrier = new Carrier(intval($info->id_carrier), intval($info->id_lang));
$templateVars = array('{delivery}' => ($history->id_data_state == _READY_TO_SEND AND $info->shipping_number) ? str_replace('#', $info->shipping_number, $carrier->url) : '');
if (!$history->addWithemail(true, $templateVars))
$this->_errors[] = Tools::displayError('an error occurred while changing status or was unable to send e-mail to the employee');
}
The site will always be changing and each $items will have atleast 20 data inside it so the foreach loop will run atleast 20 times or more depending on the number of data.
The target site will update it's database with the passed variables, it will probably pass thru atleast 5 functions before it is saved to the DB so it could probably take some time too.
My question is will there be a problem with this approach? Will the script encounter a timeout error while going thru the curl process? How about if the $items data is around 50 or in the hundreds now?
Or is there a better way to do this?
UPDATES:
* Added updateme.php main process code. Additional info: updateme.php will also send an email depending on the variables passed.
Right now all of the other site are hosted in the same server.
You can have a php execution time problem.
For your curl timeout problem, you can "fix" it using the option CURLOPT_TIMEOUT.
Since the cURL script that calls updateme.php doesn't expect a response, you should make updateme.php return early.
http://gr.php.net/register_shutdown_function
function shutdown() {
if (!$id = intval(Tools::getValue('id')))
$this->_errors[] = Tools::displayError('Invalid ID!');
else
{
$history = new History();
$history->id = $id;
$history->changeState($newdata1, intval($id));
$history->id_employee = intval($employee->id_employee);
$carrier = new Carrier(intval($info->id_carrier), intval($info->id_lang));
$templateVars = array('{delivery}' => ($history->id_data_state == _READY_TO_SEND AND $info->shipping_number) ? str_replace('#', $info->shipping_number, $carrier->url) : '');
if (!$history->addWithemail(true, $templateVars))
$this->_errors[] = Tools::displayError('an error occurred while changing status or was unable to send e-mail to the employee');
}
}
register_shutdown_function('shutdown');
exit();
You can use set_time_limit(0) (0 means no time limit) to change the timeout of the PHP script execution. CURLOPT_TIMEOUT is the cURL option for setting the timeout, but I think it's unlimited by default, so you don't need to set this option on your handle.