I'm new to PHP and I've encountered an issue that is driving me crazy. Perhaps someone here can let me know what I'm doing wrong.
I have a from that a user fills out. The below script is using the date entered into the mysql database to generate json data:
<?php
include("../includes.php");
$sq = new SQL();
$TableName = "permissions";
$Fields = $_POST["Fields"];
$FieldsSTR = "`" . str_replace("*;*","`,`", $Fields) . "`";
$Join = "AND";
$Start = 0;
$Limit = $_POST["Limit"];
if($Limit == "")$Limit = 1000;
$Where = $_POST["Where"];
$WhereSTR = "";
if($Where !== "")$WhereSTR = str_replace("*;*"," $Join ", $Where);
$q = "SELECT $FieldsSTR FROM `$TableName` $WhereSTR";
$data = $sq->sqlQuery($q);
if(sizeof($data)>0)array_shift($data);
header("Content-Type: application/json");
echo "[";
foreach($data as $k=>$line){
echo "[";
echo "\"" . str_replace("*;*","\",\"",$line) . "\"";
echo "]";
if($k < sizeof($data) - 1)echo ",";
}
echo "]";
exit;
?>
The problem that I'm having is that it has stopped working. One day it's fine and the next day it's not working. I'm thinking that maybe the cause of this problem is that crazy user data has been entered into the database. In my foreach statement I tried to replace the ";" with a "" tag, but that didn't work.
Has anyone encountered this issue before? Perhaps someone can point me in the right direction!
Thanks
Jason
Thanks everyone for your input. I was able to stumble on an fix to my immediate problem. I changed my foreach loop to the following:
foreach($data as $k=>$line){
$parts = explode("*;*",$line);
$NEWLINE = array();
for($i = 0;$i < sizeof($parts);$i++){
$value = $parts[$i];
$value = str_replace("\r","<br>",str_replace("\n","<br>",$value));
$NEWLINE[] = "\"" . $value . "\"";
}
$FINDATA[] = "[" . implode(",",$NEWLINE) . "]";
}
But I will now look into into using json_encode() as mentioned in the comments.
Thanks,
Jason
Related
I am trying to create a cron job in php that deletes disabled users found in a csv file and logs the deleted users to a txt file. Everything works except only the last user in the csv file is deleted. Here is what I have so far:
class purgeInactive extends JApplicationCli
{
public function doExecute()
{
$file = '../tmp/purge_user.csv';
$contents = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$csvRows = array_map('str_getcsv', $contents);
$log = ('../log/purged_users.txt');
$today = date('F j, Y, g:ia');
$row = 1;
if (($handle = fopen("../tmp/purge_user.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++) {
file_put_contents($log, PHP_EOL . 'Removed Disabled User(s): ' . $data[$c] . PHP_EOL . '-' . $today . PHP_EOL, FILE_APPEND);
$disUsers = implode(',', $data);
echo ', ' . $disUsers ; // to test $disUsers output
} // end for statement
} // end while statment
} // end if statement
fclose($handle);
$db = JFactory::getDbo();
$user = JFactory::getUser();
$query = $db->getQuery(true);
$userArray = var_export($disUsers,true);
echo PHP_EOL.'This is to test the output of $userArray'.$userArray;
$query
->select($db->quoteName(array('id')))
->from($db->quoteName('#__users'))
//->delete ($db->quoteName('#__users'))
//->where(array($db->quoteName('username') . ' IN(' . $userArray) . ')');
->where(array($db->quoteName('username') . ' = ' . $userArray));
//->where($deleteReq);
$db->setQuery($query);
//$result = $db->execute();
$result = $db->query();
}
}
JApplicationCli::getInstance('purgeInactive')->execute();
Any suggestions on how to run each user in the csv file individually? I am about brain dead on this as I have been working on it too long.
Note: I am running Joomla that uses ldap and I use echo for $userArray to check results.
I think instead of ...
->where(array($db->quoteName('username') . ' = ' . $userArray));
You just want
->where(array($db->quoteName('username') . ' IN(' . $userArray) . ')');
That's assuming you want to delete all the rows whose usernames are in $userArray.
If the values in $userArray aren't necessarily SQL-safe, you might also want to do this first:
$userArray = array_map('mysql_real_escape_string', $userArray);
Each row of your csv is iterating this line: $disUsers = implode(',', $data);
This means that all usernames in that row will be saved to $disUsers, then the next iteration will overwrite the old data with the new row's usernames -- this is why only the final row of data is making it down to your delete query.
$data[$c] is what should be pushed into a $disUsers array like this: $disUsers[] = $data[$c];
In your query, you'll need to quote-wrap each array value; this will do that job:
->where($db->qn('username') . ' IN (' . implode(',', array_map(function($username)use($db) {return $db->q($username);}, $disUsers)) . ')')
Here is a post of mine where I discuss writing Joomla queries with IN: https://joomla.stackexchange.com/a/22898/12352
I have a very strange issue. I am querying data and formatting it into a json. The format works great, but when i try to add a case that prevents a , from appearing in the last item of the json, the "Order By Date" of my SQL statement doesn't work, i just orders it by ID. Any thoughts why?
$sql = "SELECT * FROM events ORDER BY date";
$res = mysql_query($sql,$con);
$number = mysql_num_rows($res);
$json = 'var event_data={';
$i = 1;
while ($row = mysql_fetch_assoc($res))
{
$json .= '"'.$row['id'].'": {';
$json .= '"loc_id":"'.$row['loc_id'].'"';
$json .= ', "type":"'.$row['type'].'"';
$json .= ', "time":"'.$row['time'].'"';
$json .= ', "date":"'.$row['date'].'"}';
if ($i < $number)
{
$json .= ','; //<----- this is the problem child
}else{
$json .= '';
}
$i ++;
}
$json .= '};';
echo $json;
Please stop what you're doing now and check out: http://php.net/manual/en/function.json-encode.php
Building your own json encoder is going to be difficult to do correctly and will take quite take quite a bit of processing if you're doing it from PHP. Build up your data structure using PHP then encode the entire thing in one pass:
$o = array();
while ( $row = mysql_fetch_assoc($res) ) {
$n = array();
$n['loc_id'] = $row['loc_id'];
$n['type'] = $row['type'];
# ...
$o[ $row['id'] ] = $n;
}
echo json_encode($o);
I wrote a javascript function which takes in a string and parses it as an associative array.
function getValues(string){
var array_values = new Array();
var pairs_array = string.split('\n');
if(pairs_array[0] == 'SUCCESS'){
window.success = true;
}
for(x=1; x< pairs_array.length; x++){
var parsedValue = '';
//console.log(pairs_array[x] + "<br>");
var pair = pairs_array[x].split('=');
//console.log(pair[1]);
var variable = pair[0];
if(pair[1]){
var value = pair[1];
for(i=0; i< value.length; i++){
var character = value.charAt(i);
if(character == '+'){
parsedValue = parsedValue + character.replace('+', ' ');
}else{
parsedValue = parsedValue + value.charAt(i);
}
}
array_values[variable] = decodeURIComponent(parsedValue);
}else{
array_values[variable] = '';
}
}
return array_values;
}
Then the function is called on the string window.name_value_pairs as follows
var array_callback = getValues(window.name_value_pairs);
for(x in array_callback){
console.log("call" + x + " " + array_callback[x]);
}
Works fine. Now i have been trying to write the function in php because i would prefer it on the server side but it is not working out. I'm not sure if the array values ar getting pushed onto the array because nothing gets returned. heres the php code i have tried:
Note: $results_values is a string
$result_values = $_REQUEST['result_values'];
echo "php array " . getValuesPhp($result_values);
function getValuesPhp($string){
$array_values = array();
$pairs_array = explode("\n",$string);
if($pairs_array[0] == 'SUCCESS'){
$success = true;
echo "TRUE";
}
for($x=1; $x< count($pairs_array); $x++){
$parsedValue = '';
$pair = explode("=",$pairs_array[$x]);
$variable = $pair[0];
if(isset($pair[1])){
$value = $pair[1];
for($i=0; $i< strlen($value); $i++){
$character = $value[$i];
//echo "char \n" . $character;
if(strpos($character, '+') !== false){
//echo "plus";
$parsedValue .= str_replace('+', ' ', $character);
}else{
//echo "hi2";
$parsedValue .= $value[$i];
}
}
echo "\n var " . $variable;
echo "\n parsed " . $parsedValue;
$array_values['" . $variable . "'] = $parsedValue;
//echo "arrayValues " . $array_values['" . $variable . "'];
//array_push($GLOBALS[$array_values]['" . $variable . "'], $parsedValue);
}else{
$array_values['" . $variable . "'] = '';
//array_push($GLOBALS[$array_values]['" . $variable . "'], '');
}
}
//echo "array payment stat" . $array_values['payment_status'];
return $array_values;
}
note: where it says $array_values['" . $variable . "'] this does print out the write result as it goes through the loop however it seems like the array elements are not being added to the array as nothing is returned at the end.
Thanks for any help
Sarah
Update:
#ChrisWillard I would like to return an associative array from the string. the string is in the format where each line is in the form key=value .. it is actually the string which comes back from a paypal pdt response. For example:
SUCCESS
mc_gross=3.00
protection_eligibility=Eligible
address_status=confirmed
item_number1=3
tax=0.00
item_number2=2
payer_id=VWCYB9FFJ
address_street=1+Main+Terrace
payment_date=14%3A26%3A14+May+22%2C+2014+PDT
payment_status=Completed
charset=windows-1252
address_zip=W12+4LQ
mc_shipping=0.00
mc_handling=0.00
first_name=Sam
address_country_code=GB
address_name=Sam+Monks
custom=
payer_status=verified
business=mon%40gmail.com
address_country=United+Kingdom
num_cart_items=2
mc_handling1=0.00
mc_handling2=0.00
address_city=Wolverhampton
payer_email=monks%40gmail.com
mc_shipping1=0.00
mc_shipping2=0.00
tax1=0.00
tax2=0.00
txn_id=3PX5572092U
payment_type=instant
last_name=Monks
address_state=West+Midlands
item_name1=Electro
receiver_email=mon%40gmail.com
item_name2=Dub
quantity1=1
quantity2=1
receiver_id=WHRPZLLP6
pending_reason=multi_currency
txn_type=cart
mc_gross_1=1.00
mc_currency=USD
mc_gross_2=2.00
residence_country=GB
transaction_subject=
payment_gross=3.00
thanks for all your answers and help. it was a combination of two things that caused it to not print.. firstly my silly syntax error (being just new at programming haha I wont go into the logic i had behind this but it did make sense to me at the time haha) $array_values['" . $variable . "'] = $parsedValue; changed to this:
$array_values[$variable] = $parsedValue;
it was also the line
echo "php array" . getValuesPhp($result_values); that caused it not to print.
when i changed this to
print_r(getValuesPhp($result_values)); it printed perfect thanks to #ChrisWillard for this. So here is my final code. A combination of #ChrisWillard answer and #Mark B and #Jdo answers. I also wanted to check first if pair[1] existed and go through each character of pair[1] changing any '+' to a space ' ' if it existed so that it could be read by the user. Now i have found the function to do this for me haha. I'm sure it is not new information for a lot of you but for anyone who doesn't know it is urldecode so you can see below ive commented out the loop that i did not need (going through the characters of the string changing the plus value) and instead ive written: $finished_array[$key] = urldecode($value); thanks for all your help.
$result_values = $_REQUEST['result_values'];
print_r(getValuesPhp($result_values));
function getValuesPhp($string){
$finished_array = array();
$pairs_array = explode("\n",$string);
if($pairs_array[0] == 'SUCCESS'){
$success = true;
//echo "TRUE";
}
for($x=1; $x< count($pairs_array); $x++){
$parsedValue = '';
$pair = explode("=",$pairs_array[$x]);
$key = $pair[0];
if(isset($pair[1])){
$value = $pair[1];
//for($i=0; $i< strlen($value); $i++){
//$character = $value[$i];
//if(strpos($character, '+') !== false){
//$parsedValue .= str_replace('+', ' ', $character);
//}else{
//$parsedValue .= $value[$i];
//}
//}
$finished_array[$key] = urldecode($value);
}else{
$finished_array[$key] = '';
}
}
return $finished_array;
}
This is totally non-sensical:
$array_values['" . $variable . "'] = $parsedValue;
You're literally using " . $variable . " as your array key - remember that '-quoted strings do NOT expand variables.
Why not just
$array_values[$variable] = $parsedValue
From what I can gather, this should get you what you need:
$result_values = $_REQUEST['result_values'];
print_r(getValuesPhp($result_values));
function getValuesPhp($string){
$finished_array = array();
$pairs_array = explode("\n",$string);
if($pairs_array[0] == 'SUCCESS'){
$success = true; ////Not sure what you're trying to do here
}
for($x=1; $x< count($pairs_array); $x++) {
$pair = explode("=",$pairs_array[$x]);
$key = $pair[0];
$value = $pair[1];
$finished_array[$key] = $value;
}
return $finished_array;
}
I'm working on a project, and I've come across an issue that has me stumped. The code below is a class file and a test page to make sure it's working. It's for somebody else who is programming the site, otherwise I would code the JSON output differently. Basically, the person implementing it just has to pull a bunch of data (like below) from a database, and loop through, instantiating a class object for each result, and plugging each instance into an array, and passing the array to the printJson function, which will print the JSON string. Here is what I have:
Results.php
<?php
class Result
{
public $Category = NULL;
public $Title = NULL;
public $Price = NULL;
public function __construct($category, $title, $price)
{
$this->Category = $category;
$this->Title = $title;
$this->Price = $price;
}
public static function printJson($arrayOfResults)
{
$output = '{"results": [';
foreach ($arrayOfResults as $result)
{
$output += '{"category": "' . $result->Category . '",';
$output += '"title": "' . $result->Title . '",';
$output += '"price": "' . $result->Price . '",';
$output += '},';
}
$output = substr($output, 0, -1);
$output += ']}';
return $output;
}
}
?>
getResults.php
<?php
require_once('Result.php');
$res1 = new Result('food', 'Chicken Fingers', 5.95);
$res2 = new Result('food', 'Hamburger', 5.95);
$res3 = new Result('drink', 'Coke', 1);
$res4 = new Result('drink', 'Coffee', 2);
$res5 = new Result('food', 'Cheeseburger', 6.95);
$x = $_GET['x'];
if ($x == 1)
{
$array = array($res1);
echo Result::printJson($array);
}
if ($x == 2)
{
$array = array($res1, $res2);
echo Result::printJson($array);
}
if ($x == 3)
{
$array = array($res1, $res2, $res3);
echo Result::printJson($array);
}
if ($x == 5)
{
$array = array($res1, $res2, $res3, $res4, $res5);
echo Result::printJson($array);
}
?>
The end result is if I go to getResults.php?x=5, it will return $res1 thru $res5 (again, this is just to test, I would never do something like this in production) formatted as JSON. Right now, I get '0' outputted and I cannot for the life of me figure out why. Could my foreach loop not be written properly? Please, any help you could provide would be awesome!
It's because you're using + for concatenation rather than .:
$output .= '{"category": "' . $result->Category . '",';
$output .= '"title": "' . $result->Title . '",';
$output .= '"price": "' . $result->Price . '",';
$output .= '},';
But you should really not construct the JSON yourself, as it leads to a number of errors making for invalid JSON (trailing commas etc). Use something like this instead:
public static function printJson(array $arrayOfResults)
{
$results['results'] = array_map('get_object_vars', $arrayOfResults);
return json_encode($results);
}
I need to transfer the values from a PHP array into a JavaScript array so that it can be used in my application, I have managed to get up to this:
var Descriptions = array(<?php
foreach ($tasks as $task) {
$ID = $task['ID'];
$description = $task['description'];
echo $ID . "[" . $description . "]" . ",";
}
?>);
and it works fine except for one thing: I dont know how to tell PHP to not put a comma after the last array value. The extra comma is causing a syntax error so it breaks my code.
Thanks in advance for any ideas,
RayQuang
The quick and dirty way:
for($i = 0, $c = count($tasks); $i < $c; $i++) {
$task = $tasks[$i];
...
echo $ID . "[" . $description . "]" . (($i != $c-1) ? "," : '');
}
There are obviously other ways of accomplishing this, one way would be to build up a string and then use the trim() function:
$tasks_str = '';
foreach(...) {
...
$tasks_str .= ...
}
echo trim($tasks_str, ',');
Or, (my favorite), you could build up an array and then use implode on it:
$tasks_array = array();
foreach(...) {
...
$tasks_array[] = ...
}
echo implode(',', $tasks_array);
don't try to build it manually, use json_encode
var Descriptions = <?=json_encode($tasks);?>;
var DescriptionsString = <?php
foreach ($tasks as $task) {
$ID = $task['ID'];
$description = $task['description'];
echo $ID . "[" . $description . "]" . ",";
}
?>;
var Descriptions = DescriptionsString.split(',');
try,
var Descriptions = array(<?php
$str = '';
foreach ($tasks as $task) {
$ID = $task['ID'];
$description = $task['description'];
$str .= $ID . "[" . $description . "]" . ",";
}
echo trim($str,',');
?>);
Not one to miss out on a trend:
$out = array();
foreach ($tasks as $task) {
$ID = $task['ID'];
$description = $task['description'];
$out[] = $ID . "[" . $description . "]";
}
echo implode(',', $out);
Using implode().