I am trying to create loop inside of a HEREDOC in php. I know that it is not possible to do so, but it was the best way for me to tell what I need help for..
This is my code:
<?
$sth = $dbh->prepare("SELECT field1, field2 FROM table WHERE id = '".$_GET['id']."'");
$sth->execute();
echo <<<HERE_DOC
[
while($row = $sth->fetch()){
echo '{"optionValue":"'.$row['field1'].'", "optionDisplay": "'.$row['field2'].'"},';
}
]
HERE_DOC;
?>
and it tells me this
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in /public_html/test.php on line 7
I think it returns this because it is not possible to create a loop inside a HEREDOC – but how do I do this otherwise..?
The script is driving by AJAX with this script:
<script type="text/javascript">
$(function(){
$("select#state").change(function(){
$.getJSON("test.php",{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
}
$("select#city").html(options);
})
})
})
</script>
and the original test.php is like this:
if ($_GET['id'] == "1234") {
echo <<<HERE_DOC
[
{"optionValue":"000", "optionDisplay": "a"},
{"optionValue":"300", "optionDisplay": "s"},
{"optionValue":"600", "optionDisplay": "d"},
{"optionValue":"700", "optionDisplay": "cr"},
{"optionValue":"500", "optionDisplay": "Gı"},
{"optionValue":"400", "optionDisplay": "K"},
{"optionValue":"800", "optionDisplay": "S"},
{"optionValue":"900", "optionDisplay": "ik"},
{"optionValue":"350", "optionDisplay": "Tu"}
]
HERE_DOC;
else if ($_GET['id'] == "2345") { etc......
The thing is that I already have all the data in an SQL database, and I would like to just return the data based on the id from previous select list since there is a lot of options.
Don’t make the JSON yourself, use
json_encode.P.S. Don’t use
$_GETdirectly like that. You’re vulnerable to SQL injection. You’re already using PDO, use it correctly. You should do it like this: