trouble with double quotes first record of PHP array - php

php5, Microsoft SQL Server Management Studio, OS 6.3.15063. i get $row data via mssql_fetch_assoc and stuff a PHP array with the $row data just fine when the first record does not have double quotes. subsequent row data can have double quotes, just not the first row. Error: "SyntaxError: missing ) after argument list" in jquery.min - so i cannot peruse and get helpful info from that. code:
$History_SQL = "
DECLARE #AID int;
SET #AID = $Activity_ID;
SELECT activityid, lpid, abstract, changeid, changestamp FROM cpy_activity_history
WHERE activityid = #AID ORDER BY changestamp DESC;
";
$History_results = mssql_query($History_SQL);
while ($row = mssql_fetch_array($History_results)) {
$HistoryRecords[] = $row;
}
This works when record index[0] does not have double quotes, but when double quotes, errors out.
Interestingly, if i use:
$HistoryRecords[] = json_encode($row);
RESULT>>SyntaxError: missing ) after argument list
then it gets past the error; but I am having trouble usind json_decode to get any useful information out of the array [not even getting js braces or anything, getting another record from another table, possibly because this value is not what it thought it was going to be/either way, not sure i am even starting down the right road with json_endode/decode.]
it could be i simply do need help learning how to decode each record coming out of the json encoded var. either way, does this problem look familiar, and any ideas for how to stop getting the error? NOTE: ultimately, i need to display the array information via javascript. other related posts do not seem to cover this scenario. these double quotes are proving maddening. thanks in advance!

thx, All for helping!
the SYMPTOMS included the [a]browser crashing with console/js error: "missing ) after arg list", [b]a var in the code to display an erroneous field, unrelated to the sql used to create info for that var.
the REASON this occurred was that i had within PHP, a console.log that contained a PHP variable. so i was mixing js and PHP. the PHP was firing late and so at the time, the js console.log had nothing to display.
the CLUE which led to fixing this was noticing that the js msg was crashing in the browser, YET the php LOG_IT stmts below the js were working. the js was trying to console.log a msg that had a null value, and somehow a js var was getting loaded with wrong information. sheeze.
the CODE - before the fix the php echo from within the console.log was the culprit. i tossed the original offending stmt, but it was something like this:
<?php here in php land....., now i want to do a console.log....
?><script>console.log("show me info!: " <?php echo $info; ?></script><?php
...back in php land...
i commented out the "echo $info;" and things worked. of course i ripped it out altogether. funny, it would've cleared itself up when i stopped banging my head on the wall and simply decided to clean up and remove all the troubleshooting console.logs.
the CONCLUSION - an old lesson, "don't mix js and php", even in error logging!
thx again for all your help!

Related

PHP Scripts Encapsulating Returned JSON Array with Number Above and Number Below

I'm having a problem where my PHP scripts are returning my json encoded array with a number above and a number below it. Like follows:
26
[0,"edited_token_string"]
0
I have not changed any of the scripts that I'm encountering this on, but it is happening with all of them. I don't have any other echos other than the one used to echo the array. Our server was returning "null" from all of the scripts all morning and now is returning the correct array, with these numbers surrounding it. Is it possible something was updated on the server that accidentally turned on some type of debugging? I've called our hosting service, but they are incredibly unhelpful.
Thanks in advance,
Max
Try adding header('Content-type: application/json'); directly above the line that outputs your JSON. If something else has already outputted something, you will get an error telling you where in your code that happened.
For the undesired output after the JSON, could it be that there is also an extra space after the closing ?> tag? A quick and dirty fix would be to just add die; after the last intentional echo;

PHP pass mysql query as variable to second php script when requested

I've been teaching myself php & mysql & have found this site invaluable. Thanks to all who answer questions.
I have found several q&a's that are close to this & they HAVE helped to point me in the right direction but I can't quite get this to work.
Here's what I'm trying to do: Pass a constructed SQL query to a second php script so that the results can be displayed in a new window. I can't quite seem to get the syntax right to pass the sql
query ($sql) to open.window correctly. A matter of quotes I
think. I have tried echo instead of print, single quotes with double quotes inside, using ('$sql'), but nothing seems to work.
I do need this to be called by a variable, so that it is after the submit is given. I would prefer not to have a second submit
Help?
if (isset($_POST['NEWWINDOW'])) {
echo "<script>window.open("results.php?sql=$sql)</script>";
}
This will concatinate your $sql-variable with the rest of the string, however doing this you should keep in mind to sanitize your sql in result.php before submiting it to your database.
if (isset($_POST['NEWWINDOW'])) {
echo "<script>window.open('results.php?sql=".$sql."')</script>";
}
Try this
<?php
if (isset($_POST['NEWWINDOW'])) {
echo "<script>window.open('results.php?sql=$sql')</script>";
}
?>
Thank you each for your responses. This query form is private, & I will be the only one using it... (behind firewall), so the risk is minimal. However, the point is well made & I would certainly rather learn to do it the right way than the wrong way. The database is important. Recommendations?
Neither of the two offered suggestions as to syntax work for me.
I made sure & copy the syntax exactly. In both (all three cases) the window.open fails to open a window. I finally cut & pasted to be sure, but the behavior is the same.. the window does not even open.

file_get_contents not waiting

I'm using a PHP call to a REST service to retrieve information from the eXist XML database, running on localhost, capturing the results with file_get_contents(), and using those results to populate a drop-down list in a query form. I thought that file_get_contents() was supposed to wait automatically for complete results, but apparently it doesn't; sometimes the list is fully populated and sometimes it's truncated. The truncation happens at various locations, and reloading the page (rerunning the PHP, and therefore the REST call) usually fixes it, although sometimes not on the first try.
If I've diagnosed the problem correctly as a matter of file_get_contents() not waiting for results, can anyone advise me about how to fix it? Or is there an alternative explanation? Here's the relevant snippet from the PHP:
$getPersonNamesQuery = <<< EOQ1
{for \$i in doc('/db/genealogy/genealogy.xml')//person[not(.//firstName eq "unknown")]
order by string-join(\$i/name/*," ")
return
{normalize-space(concat(
\$i/name/firstName,
" ",
if (\$i/name/epithet) then concat("â",\$i/name/epithet,"â) else "",
" ",
\$i/name/patronymic," ",
if (not(\$i/#origin eq "Rus'" or \$i/#origin eq "unknown")) then concat("of ",\$i/#origin) else ""
))}
}
EOQ1;
$contents = "http://localhost:8080/exist/rest/db/genealogy?_howmany=10000&_wrap=no&_query=" . urlencode($getPersonNamesQuery);
$personNames = file_get_contents($contents);
Thanks,
David
Same thing happened with me, I was using http_build_query to build query string, and the result of file_get_contents and cURL both were responding prematurely. Passing the complete query string without http_build_query in both of the functions resulted in a success. Weird!
This resulted is truncated data:
$pUrl=array('username'=>'_username_',
'variable'=>'value',
'variable2'=>'value2',
'variable3'=>'value3');
$cURL=http_build_query($pUrl);
print_r(file_get_contents("http://www.example.com/api/?$cURL"));
This returned the complete data everytime:
print_r(file_get_contents("http://www.example.com/api/?username=_username_&variable=value&...."));

Not able to parse this json

I am trying to parse the json output from
http://www.nyc.gov/portal/apps/311_contentapi/services/all.json
And my php json_decode returns a NULL
I am not sure where the issue is, I tried running a small subset of the data through JSONLint and it validated the json.
Any Ideas?
The error is in this section:
{
"id":"2002-12-05-22-24-56_000010083df0188b4001eb56",
"service_name":"Outdoor Electric System Complaint",
"expiration":"2099-12-31T00:00:00Z",
"brief_description":"Report faulty Con Edison equipment, including dangling or corroded power lines or "hot spots.""
}
See where it says "hot spots." in an already quoted string. Those "'s should've been escaped. Since you don't have access to edit the JSON perhaps you could do a search for "hot spots."" and replace it with \"hot spots.\"" like str_replace('"hot spots.""', '\\"hot spots.\\""\, $str); for as long as that's in there. Of course that only helps if this is a one time thing. If the site continues to make errors in their JSON output you'll have to come up with something more complex.
What I did to identify the errors in the JSON ...
Since faulty quoting is the first thing to look for, I downloaded the JSON to a text file, opened in a text editor (I used vim but any full featured editor would do), ran a search and replace that removed all characters except double-quote and looked at the result. It was clear that correct lines should have 4 double-quotes so I simply searched for 5 double-quotes together and found the first bad line. I noted the line number and then undid the search and replace to get the original file back and looked at that line. This gives you what you need to get the developers of the API to fix the JSON.
Writing code to automatically fix the bad JSON before giving it to json_decode() would be quite a bit harder but doable using techniques like those in another answer.
According to the PHP manual:
In the event of a failure to decode, json_last_error() can be used to determine the exact nature of the error.
Try calling it to see where the error is.

Problem with mixing Javascript the PHP

I am trying to assign values in javascript assigned from PHP and the use document.write() to output them. The problem is when I do this, a complete blank screen shows up but no errors are ever thrown. But if I take the PHP out and put in a value such as 'ABC' it works. And example of my code can be this:
var comment_text="<?php echo $value['comment_text'];?>";
var bodyelement = document.getElementsByTagName('body')[0];
var newdiv = document.createElement('div');
newdiv.style.textAlign = 'center';
newdiv.style.zIndex = 10001;
newdiv.style.left = (<?php echo $comment_x;?>+getPos('browserwindow',"Left")-23) + 'px';
newdiv.style.top = (<?php echo $comment_y;?>+getPos('browserwindow',"Top")-90) + 'px';
newdiv.style.position = 'absolute';
newdiv.innerHTML = comment_text;
bodyelement.appendChild(newdiv);
I do have an PHP error log and no errors are beign thrown either. The values are retrieved from the database, the probem comes with outputting them.
*UPDATE*
Ok, I had this problem before.
Basically a newline is created like this:
var comment_text="cool Beans
";
I have tried to remove the newline with string replace but doesn't seem to work. Why would a new line like this cause this error?
Your issue is cleary in the output from PHP. If you get a blank page, means you most likely have a PHP issue that is HALTING the processing of said page.
As PHP is parsed before anything is sent to the viewer, this will result in a blank / error page.
When you substitute your $value['comment_text'] for ABC you remove the location that causes the error.
I am going to assume that $value['comment_text'] is either a result of a function, or a Database query, try just outputting the $value['comment_text'] first, then worry about sticking it in JS (which will work if your PHP code works).
As I don't see any of your PHP code, I cannot help you further.
Use
var comment_text=String(<?php echo json_encode($value['comment_text']);?>);
instead of
var comment_text="<?php echo $value['comment_text'];?>";
This will protect you from cross-site-scripting attacks by escaping all special characters like backslashes, quotes or line feeds.
The String(...) ensures that comment_text has type String and is not interpreted as a number (if $value['comment_text'] is has a number type).
If PHP is causing an error (sounds like it is) you can turn on your error reporting to see the issues
error_reporting(E_ALL)
The solution was just using trim.
echo trim($value['comment_text']);
I recommend you use a heredoc for the javascript code with %s in the js. and use sprintf to substitute the variables.

Categories