In this code I am trying to search a database with two columns, retrieve 11 pairs of those based on one of the matches (companyname; this was sent from JavaScript using POST). Then I am trying to create a JSON data.
<?php
header("Content-Type: application/json");
$db = new PDO('mysql:host=localhost;dbname=pl;charset=UTF-8', 'user', 'password');
if(isset($_POST['companyname']) == true && empty($_POST['companyname']) == false) {
$searchterm = $_POST['companyname'];
$i=0;
$jasondata = '{';
$query = $db->query("SELECT companyname, axiscategory FROM axispl WHERE companyname LIKE '$searchterm%' LIMIT 11");
$c = 1;
while (($row=$query->fetchAll(PDO::FETCH_ASSOC)) !==false && $c<11) {
$i++;
$companyname = $row["companyname"];
$axiscategory = $row["axiscategory"];
$jasondata .='"combi'.$i.'":{"companyname":"'.$companyname.'","axiscategory":"'.$axiscategory.'"},';
$n=$row['companyname'];
$l=strlen($n);
if($l>50){$c = $c+2;}else{$c = $c+1;}
}
$jasondata = chop($jasondata, ",");
$jasondata .= '}';
echo $jasondata;
}
?>
What should you change? Well, I mentioned using
json_encodeearlier, and Charles quite rightly points out the security vulnerability.I’d also work on the code formatting as well – my recommendation is to work to a sensible margin. This used to be 80 characters for historical reasons, but 100-120 is quite a good limit now – it means you can have several code viewers stacked left-to-right on your screen without the need to scroll horizontally in each one. And you can post to StackOverflow similarly without wrapping issues!
Consider this snippet of yours:
Also:
Much more readable, eh? My motto: give your code room to breathe.