I'm trying to send a value from my phonegap app via ajax to php and then check that value with my sql db. Now since there is an undefined index gli2 the php file won't even receive or send data to my sql db, but it will give me the result 'You can eat'. Can somebody help my ?
Here is my php file:
<?php
$conn = new mysqli('localhost', 'root', '', 'test');
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
$gli2 = $_POST['gli2'];
$result = $conn->query("SELECT smt FROM product WHERE smt='${gli2}' and BarCode =0");
$row = $result->fetch_assoc();
if ($row['smt'] == '0' ) {
echo '<script language="javascript">';
echo 'alert("You can eat")';
echo '</script>';
}else{
echo '<script language="javascript">';
echo 'alert("You cannot eat")';
echo '</script>';
}
?>
And here is my ajax:
$.ajax({
type: "POST",
url: 'http://localhost/test/testing.php',
data: {gli2: document.getElementById("galima1").value,},
success: function() {
console.log('success');
},
dataType: 'application/json',
});
答案 0 :(得分:1)
The variable in query ${gli2}
does not evaluate to anything.
As it has a curly brace after $
sign.
Change
$result = $conn->query("SELECT smt FROM product
WHERE smt='${gli2}' and BarCode =0");
To
$result = $conn->query("SELECT smt FROM product
WHERE smt='{$gli2}' and BarCode =0");
答案 1 :(得分:1)
This is wrong syntax here:
smt='${gli2}'
You need to use, for inline variable expansion:
smt='{$gli2}'
So that the full code becomes:
$result = $conn->query("SELECT smt FROM product WHERE smt='{$gli2}' and BarCode=0");
It is also better (not compulsory) to use backticks for better readability and safety.
$result = $conn->query("SELECT `smt` FROM `product` WHERE `smt`='{$gli2}' and `BarCode`=0");
See the position of the {
and $
. This is not like Rails or other templating engines. Also, your code is susceptible to SQL Injection Attack. It would be better to pass $gli2
to the built-in function mysqli_real_escape_string()
to get it cleaned.