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
$_POST? This looks like you are building SQL directly from a form POST, which is really dangerous and easily vulnerable to tampering. I also see what appears to be manual construction of JSON with string ops. Really you should be usingjson_encode()which will save you all the trouble of getting the formatting and looping right. It really might be as simple asecho json_encode($data);to produce valid JSON from your SQL output.SQLobject, but you may want to look into prepared statements to harden your code a bit.json_encode()to produce the JSON.foreachloop is way wrong. As others have mentionedjson_encode()on the structure you want.