I have the following table:
| id | name | age |
|----|-------|-----|
| 1 | Peter | 23 |
| 2 | Amie | 34 |
| 3 | Eddy | 45 |
| 4 | Peter | 56 |
| 5 | Eddy | 67 |
I now want to retrieve the age of all users with the name Peter
.
JS:
function getAge() {
$.ajax({
type : "POST",
url : "backend.php",
data : {
q : "user",
name : 'Peter'
},
success : function(data) {
console.log(data)
if (data.length > 0) {
} else {
console.log("empty")
}
},
error : function(jqXHR, status, error) {
console.log(status, error);
}
});
}
PHP:
if (isset ( $_POST )) {
if ($_POST ['q'] == "user") {
$name = $_POST ["name"];
$stmt = $link->prepare ( "SELECT age FROM tab1 WHERE name= ?" );
$stmt->bind_param ( "s", $name );
$stmt->execute ();
$stmt->store_result ();
if ($stmt->num_rows >= 1) {
echo "Yes"; // only this Yes is being returned
$arr = array ();
while ( $stmt->fetch () ) {
$arr [] = $name;
}
return $arr;
} else {
echo "0 records found";
}
$link->close ();
}
Instead of an array with 23
and 56
, I only get a Yes
.
So how can I get the array with the ages?
just add this into your php function. this means you want to return json into this page
header('Content-Type: application/json');
change your return $arr to echo json_encode($arr); to convert your array into a json object also remove your echo "Yes";
echo json_encode($arr);
your php function will look like this
if (isset ( $_POST )) {
if ($_POST ['q'] == "user") {
header('Content-Type: application/json');
$name = $_POST ["name"];
$stmt = $link->prepare ( "SELECT age FROM tab1 WHERE name= ?" );
$stmt->bind_param ( "s", $name );
$stmt->execute ();
$stmt->store_result ();
if ($stmt->num_rows >= 1) {
$arr = array ();
while ( $stmt->fetch () ) {
$arr [] = $name;
}
echo json_encode($arr);
} else {
echo "0 records found";
}
$link->close ();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.