1

If I pass a ID in the URL the below query is not retrieving data based on the ID. How to retrieve JSON data based upon the ID?

<?php
$servername = "localhost";
$username = "testphp";
$password = "1234";
$dbname = "testphp";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
$sql = "select * from test where id =? order by count asc";
$result = $conn->query($sql);
$arr=array();
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
       array_push($arr, $row);
    }
    echo json_encode($arr);
} else {
    echo "0 results";
}
$conn->close();
?>
1
  • Where's your bind_param statement? Commented Sep 30, 2018 at 23:56

1 Answer 1

1

As mentioned in the comments, due to your code's vulenrability to SQL injection, you must change your code like this.

From

$sql = "select * from test where id = ? order by count asc";
$result = $conn->query($sql);

To

$sql = $conn->prepare("select * from test where id = ? order by count asc");
$sql->bind_param("i", $_GET["id"]);
$result = $conn->query($sql);

I am assuming column id is an number / integer field. More info about parameter binding - http://php.net/manual/en/mysqli-stmt.bind-param.php

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.