php file else condition output is wrong - php

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);

Related

Incorrect json output from mysql

I made a request from MySQL and my code below is not working:
$email =$_POST['email'];
$parola =$_POST['parola'];
$rez = mysqli_query($con, "SELECT * FROM utilizatori WHERE email='$email' AND parola='$parola'");
if($rez){
$succes = 1;
} else {
$succes = 0;
}
$data = array("succes" => $succes);
echo json_encode($data);
In postman it shows me this:
You missed the data variable or your query doesn't not return any output. Please try to use the MySQL query in Phpmyadmin or CLI. If it is OK then use the code like :
$email =$_POST['email'];
$parola =$_POST['parola'];
$rez = mysqli_query($con, "SELECT * FROM utilizatori WHERE email='$email' AND parola='$parola'");
while($result = mysqli_fetch_array($rez))
{
$data[] = $result;
}
if(mysqli_num_rows($rez) != 0) {
$data = array("success" => "Success", "data" => $data );
} else {
$data = array("success" => "Failed", "data" => array() );
}
echo json_encode($data);

odbc_num_rows is not work

$stmt is execute and give Result in Print_r($stmt). Result is this "Resource id #4" but when Print_r($stmt) is put in if (odbc_num_rows($stmt) > 0) {Print_r($stmt);}. it's not give Result. and gone else conditon give message else condition.so How to Put odbc function instead of odbc_num_rows($stmt).if right Parameter pass query execute and gone if condition.
which Odbc function used in if condtion.
<?php
include 'Connection.php';
if(isset($_REQUEST["insert"]))
{
$user = $_GET['user'];
$pwd = $_GET['pass'];
$yid = $_GET['yid'];
$sql = "select RegNo, UserName, Pasword from Std_Reg where UserName= '$user' and Pasword = '$pwd' and YearID = $yid and IsActive = True";
$stmt = odbc_exec($conn, $sql);
$result = array();
if (!empty($stmt)) {
// check for empty result
if (odbc_num_rows($stmt) > 0)
{
print_r($stmt);
$stmt1 = odbc_fetch_array($stmt);
$product = array();
$product['RegNo'] = $stmt1['RegNo'];
$product['UserName'] = $stmt1['UserName'];
$product['Pasword'] = $stmt1['Pasword'];
// 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["succes"] = 0;
$result["message"] = "No product found";
// echo no users JSON
echo json_encode($result);
}
//sqlsrv_free_stmt($stmt);
odbc_close($conn); //Close the connnection first
}
}
?>
For INSERT, UPDATE and DELETE statements odbc_num_rows() returns the number of rows affected. The manual says-
Using odbc_num_rows() to determine the number of rows available after a SELECT will return -1 with many drivers.
one way around this behaviour is to do a COUNT(*) in SQL instead. See here for an example.

PHP : check if num rows is zero

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

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. :(

Categories