php - Check If JSON Array Contains Data

I have a small piece ofPHP
that queries a database to find a matching value, the code successfully prints the returned value when there is a matching row in the database (As displayed in the second code sample below), The issue occurs when there is no matching row as it prints "[ ]"(As displayed in the third code sample below).
PHP Code:
$QueryString = $_POST['QueryString'];
//Query Database For ID
$result = $connection->query("$QueryString");
//Initialize array variable
$query = array();
//Fetch into associative array
while ($row = $result->fetch_assoc())
{
$query[] = $row;
}
if (isset($query)) {
echo json_encode($query, JSON_PRETTY_PRINT);
} elseif (empty($query)) {
echo json_encode("No Matching Record Found", JSON_PRETTY_PRINT);
} else {
echo json_encode("An Unkown Error Occurred", JSON_PRETTY_PRINT);
}
Matching Row:
[
{
"A": "One",
"B": "Two",
"C": "Three",
}
]
No Matching Row:
[]
Answer
Solution:
You need to change your condition like below:
if (count($query) > 0 ) { //check array have any value or not?
echo json_encode($query, JSON_PRETTY_PRINT);
} else{
echo json_encode("No Matching Record Found", JSON_PRETTY_PRINT);
}
Reference: count()
Note: you can use sizeof() as well.
Sample example: https://3v4l.org/i5sZ8 And https://3v4l.org/8rtb1
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: call to undefined function str_contains()
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.