PHP : check if num rows is zero - php

I am trying to check if result returned by database is zero but it always falls to zero following is my code
if(isset($_POST['cust_id'])){
$cust_id = $_POST['cust_id'];
$stmt = $connect->prepare("SELECT DISTINCT send_stamp, message, time, status FROM `chat` WHERE cust_id=?");
$stmt->bind_param('i', $cust_id);
}
else if(isset($_POST['receiverid'])) {
$receiverid = $_POST['receiverid'];
$stmt = $connect->prepare("SELECT DISTINCT send_stamp, message, time, status FROM `chat` WHERE receiverid=?");
$stmt->bind_param('i', $receiverid);
}
if($stmt->execute()){
$data = array();
if($stmt->num_rows ==0){
$data[] = array(
'message'=> 'No messages found',
'status'=>0,
);
}
else{
$result = $stmt->get_result();
while ($row =mysqli_fetch_array($result)) {
$data[] = array(
'message'=> $row['message'],
'time'=> $row['time'],
'status'=> $row['status'],
);
}
}
}
echo json_encode( $data);
Please help me to figure out this situation . Thanks

try with this one
execute query and get data into result like $result=$stmt->execute() and that
result compare in if() condition like if($result) and inside if($result == 0) so it give an result
$result=$stmt->execute();
if($result)
{
$data = array();
if($result ==0){
$data[] = array(
'message'=> 'No messages found',
'status'=>0,
);
}
else{
$result = $stmt->get_result();
while ($row =mysqli_fetch_array($result)) {
$data[] = array(
'message'=> $row['message'],
'time'=> $row['time'],
'status'=> $row['status'],
);
}
}
}
OR
also write $result = $stmt->get_result(); after if($stmt->execute()) and compare if($result->num_rows ==0) like this way

Related

php file else condition output is wrong

Login.php
<?php
include 'Connection.php';
if(isset($_REQUEST["insert"]))
{
$user = $_GET['user'];
$pwd = $_GET['pass'];
//$sql =sqlsrv_query($conn,"select RegNo,UserName,password from Std_Reg where Username= '$user' and Password = '$pwd'");
$sql = "select RegNo,UserName,password from Std_Reg where Username= '$user' and Password = '$pwd'";
$stmt = sqlsrv_query($conn, $sql);
$result = array();
if (!empty($stmt)) {
// check for empty result
if (count($stmt) > 0) {
$stmt = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$product = array();
$product["RegNo"] = $stmt["RegNo"];
$product["UserName"] = $stmt["UserName"];
$product["password"] = $stmt["password"];
// success
$result["success"] = 1;
// user node
$result["product"] = array();
array_push($result["product"], $product);
// echoing JSON response
echo json_encode($result);
} else {
// no product found
$result["success"] = 0;
$result["message"] = "No product found";
// echo no users JSON
echo json_encode($result);
}
//sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); //Close the connnection first
}
}
?>
I have connected to MS SQL Server to PHP File.if condition work properly but else part is not work.I have wrong parameter passed its give output
{"success":1,"product":[{"RegNo":null,"UserName":null,"password":null}]}.
but right else part output is
{
"success": 0,
"message": "No product found"
}
After
$stmt = sqlsrv_query($conn, $sql);
$stmt is either FALSE (when there is a connectivity issue, a syntax error in the query or it refers an object that doesn't exist) or a PHP resource.
Because $stmt is neither an array nor an object that implements the Countable interface, count($stmt) always returns 1.
Use sqlsrv_num_rows() to get the number of rows returned by the query or (if you don't care about the number) use sqlsrv_has_rows():
$stmt = sqlsrv_query($conn, $sql);
if ($stmt) {
if (sqlsrv_has_rows($stmt) > 0) {
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$product = array(
'RegNo' => $row['RegNo'],
'UserName' => $row['UserName'],
'password' => $row['password'],
);
$result = array(
'success' => 1,
'product' => array($product),
);
} else {
// no product found
$result = array(
'success' => 0,
'message' => 'No product found',
);
}
echo json_encode($result);
}
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);

JsonArray return null value

Below is my php code:
public function getMainChatList($myPhoneNo){
$stmt = $this->conn->prepare("SELECT receiverPhoneNo,name FROM users,friend WHERE users.phoneNo=friend.receiverPhoneNo AND senderPhoneNo=? AND chatted = 'y' ORDER BY update_time DESC");
$stmt->bind_param("s", $myPhoneNo);
$stmt->execute();
$stmt->store_result();
$result = array();
while($row = $stmt->fetch()){
array_push($result,array('receiverPhoneNo'=>$row['receiverPhoneNo'],'name'=>$row['name'],));
}
//echo json_encode(array("result"=>$result));
echo json_encode($result);
echo json_last_error();
$stmt->close();
}
And the json return
[{"receiverPhoneNo":null,"name":null},{"receiverPhoneNo":null,"name":null}]0
json_last_error() returns 0. I have no idea why it return null.
And I execute the sql statement on xampp MySQL server directly.
Below is the result.
result.jpg
Thanks!
Just use bind_result() instead:
public function getMainChatList($myPhoneNo)
{
$stmt = $this->conn->prepare("
SELECT receiverPhoneNo, name FROM users, friend
WHERE users.phoneNo = friend.receiverPhoneNo
AND senderPhoneNo = ?
AND chatted = 'y'
ORDER BY update_time DESC
");
$stmt->bind_param('s', $myPhoneNo);
$stmt->execute();
// bind
$stmt->bind_result($receiverPhoneNo, $name);
$result = array();
while($stmt->fetch()){
$result[] = array(
'receiverPhoneNo' => $receiverPhoneNo,
'name' => $name,
);
}
echo json_encode($result);
}
this should put the associative array from the entire query directly into your $result array
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

My php file does not return all values in JSON form

So I have a database and I have written a php file that inserts value to the table and then returns all the values in this table.
However, my code only returns just one random value from the table and not all of them. I am not sure why, but this is my code:
<?php
include_once "init.php";
if(!empty($_POST['names'])){
$contactname = $_POST['names'];
$query = "INSERT INTO contacts (contactID, names)
VALUES('NULL', ?)";
$results = $conn -> prepare($query);
$results->bind_param('s', $contactname);
$results->execute();
$results->close();
echo json_encode("Success");
$query_two = "SELECT names FROM contacts";
$result = mysqli_query($conn, $query_two);
$response = array();
if(mysqli_num_rows($result)){
while($row = mysqli_fetch_assoc($result)){
$response["names"][] = $row["names"];
}
}
echo json_encode($response);
}
else{
echo json_encode("Something went wrong");
}
?>
EDIT: Thank you guys for providing me a solution so quickly! I fixed it and it works but the first echo json_encode("Success"); is not being executed.
In your line here:
$response["names"] = $row["names"];
You are replacing the value of $response["names"]. Instead, try adding it to an array:
$response = array("names" => array());
if(mysqli_num_rows($result)){
while($row = mysqli_fetch_assoc($result)){
$response["names"][] = $row["names"];
}
}
To use one JSON object, you'd initialize $response at the top and change the values as needed.
<?php
include_once "init.php";
$response = ['success' => false, 'message' => null, 'names' => []];
if(empty($_POST['names'])) {
$response['message'] = 'No names were provided in the request';
} else {
$contactname = $_POST['names'];
$query = "INSERT INTO contacts (contactID, names) VALUES('NULL', ?)";
$results = $conn->prepare($query);
$results->bind_param('s', $contactname);
$results->execute();
$results->close();
$response['success'] = true;
$query_two = "SELECT names FROM contacts";
$result = mysqli_query($conn, $query_two);
if(mysqli_num_rows($result)){
while($row = mysqli_fetch_assoc($result)){
$response['names'][] = $row['names'];
}
}
}
echo json_encode($response);

Sqlsrv query doesn't show any result

SELECT * FROM dbo.Warehouse returns result, but when I change to SELECT * FROM dbo.Accessories, it neither shows any result nor echo 'Rows not found'. Both Warehouse and Accessories tables have rows. Here is my script.
<?php
require('db_connect.php');
$query = 'SELECT * FROM dbo.Warehouse';
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query($conn, $query, $params, $options);
if(!$stmt){
die(print_r(sqlsrv_errors(),true));
}
$c = 0;
$result[] = array();
if(sqlsrv_num_rows($stmt) != 0){
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)){
$row = array($c => $row);
$result[$c] = $row;
$c++;
}
} else {
echo("Rows not found");
}
echo json_encode($result);
?>
Please help me, thanks in advance. :(

PDO: Like condition doesn't work using bindParam

well... why doesn't work this sql statement?
public function searchProfile() {
$termino = $this->term;
$termino = "%".$termino."%";
$sql = "SELECT * FROM cat_perfiles WHERE UPPER(Nombre) LIKE UPPER(:term)";
$result = $this->dbConnect->prepare($sql) or die ($sql);
$result->bindParam(':term',$termino,PDO::PARAM_STR);
$numrows = $result->rowCount();
$jsonSearchProfile = array();
if ($numrows > 0) {
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$jsonSearchProfile[] = array(
'IdPerfil' => $row['Id'],
'NomPerfil' => $row['Nombre'],
'DesPerfil' => $row['Descripcion'],
'EdoPerfil' => $row['Activo']
);
}
$jsonSearchProfile['success'] = 'success';
return $jsonSearchProfile;
} else {
return false;
}
}
I check data from $this->term and is correct! But when compare with LIKE doesn't work.
I hope can help me!
You forgot to execute the query
$result->execute();

Categories