[Help Needed] - query failed when passing variable

Hello,

Im sending data with jquery ajax to another php page, the purpose of this
is to get data from database on the basis the selection of customer.

The problem is when im trying to get the data from the sql using $var , its return empty results, and when I replace the var for example to a string its working.

The ajax just work fine. the problem is in my php code.

<?php

$hotelName = $_POST[‘suggestions’];

$con = new mysqli(‘localhost’, ‘root’, ‘xxxxx’, ‘serviceproducts’);
$query = “select name from rooms where hotelname = '” . $hotelName . “’”;
$result = $con->query($query);

while ($row = $result->fetch_assoc()) {
echo $row[“name”];
}

?>

I also tried to set the variable like this: ‘$hotelName’
and like this: ‘{$hotelName}’

Also , tried … string real escape.
nothing worked.

Thank you In Advance.

NEVER EVER PUT VARIABLES IN A QUERY.

You need to use prepared statements

Ok thank you, What doe’s prepared statements means?

Following to this , I change my code to this, but not working, Im getting page error

  <?php

$hotelName = $_POST[“suggestions”];

$con = new mysqli(‘localhost’, ‘root’, ‘xxxx’, ‘serviceproducts’);
$query = “select name from rooms where hotelname = ?”;
$statement = $con->prepare($query)
$statement->bind_param(‘i’,$hotelName);
$statement->execute();
$result = $statement->get_result();

while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
echo $row[“name”];
echo “
”;
}
$result->close();

?>

Found the problem,
It was syntax.
B.T.W its working now, thanks for your help.

Sponsor our Newsletter | Privacy Policy | Terms of Service