Returning JSON message in PHP - php

I have written a PHP script to connect to a MySQL database and extract some information. I know that the majority of the script is working as it actually inserts a MAC address into the table (which is what it should do when the value of the MAC address in the DB table is NULL).
However, the resulting message from my script is "No license found (3)".
My question is, how can it be returning this message if it's inserting a MAC address? The else statement would only be entered if if (mysqli_num_rows($result) > 0) returned false.
What I want is for the MAC address to be checked (or inserted if NULL in the DB) and to return the message "Licensed".
Apologies for the nested if/else statements.
<?php
// Array for JSON response.
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
// Check for GET data.
if (isset($_GET["LicenseKey"])
&& isset($_GET["SoftwareId"])
&& isset($_GET["MacAddress"])) {
$licenseKey = $_GET['LicenseKey'];
$softwareId = $_GET['SoftwareId'];
$macAddress = $_GET['MacAddress'];
// Import database connection variables.
require_once __DIR__ . '/get_license_SQL.php';
$query = SQL_GET_LICENSE;
$query = str_replace("%1", $softwareId, $query);
$query = str_replace("%2", $licenseKey, $query);
$result = mysqli_query($db->connect(), $query);
if (!empty($result)) {
// Check for empty result.
if (mysqli_num_rows($result) > 0) {
// Get the result.
$result = mysqli_fetch_array($result);
$license = array();
$license["ExpiryDate"] = $result["ExpiryDate"];
// Check if MAC address exists.
$query = SQL_GET_MAC_ADDRESS;
$query = str_replace("%1", $licenseKey, $query);
$result = mysqli_query($db->connect(), $query);
if (!empty($result)) {
$result = mysqli_fetch_array($result);
echo json_encode($result);
if ($result["MacAddress"] == $macAddress
|| $result["MacAddress"] == NULL) {
// Device MAC address matches MAC address on record.
$response["success"] = 1;
$response["license"] = array();
if ($result["MacAddress"] == NULL) {
// Insert new MAC address into the database.
$query = SQL_INSERT_MAC_ADDRESS;
$query = str_replace("%1", $macAddress, $query);
$query = str_replace("%2", $licenseKey, $query);
mysqli_query($db->connect(), $query);
}
// Add MAC address to license array.
$license["MacAddress"] = $result["MacAddress"];
$response["message"] = "Licensed";
array_push($response["license"], $license);
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "License has already been used by another device";
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "No license found (2)";
array_push($response["license"], $license);
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "No license found (3)";
array_push($response["license"], $license);
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "No license found (4)";
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "Required field(s) missing";
echo json_encode($response);
}
?>
db_connect.php :
<?php
class DB_CONNECT {
function __construct() {
$this->connect();
}
function connect() {
require_once __DIR__ . '/db_config.php';
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE);
$db = mysqli_select_db($con, DB_DATABASE) or die(mysqli_error()) or die(mysqli_error());
return $con;
}
}
?>
get_license_SQL.php :
<?php
define('SQL_GET_LICENSE', "SELECT licenses.ExpiryDate
FROM licenses
WHERE licenses.SoftwareId=%1 AND licenses.LicenseKey=%2");
define('SQL_GET_MAC_ADDRESS', "SELECT licenses.MacAddress
FROM licenses
WHERE licenses.LicenseKey=%1");
define('SQL_INSERT_MAC_ADDRESS', "UPDATE licenses
SET MacAddress=%1
WHERE licenses.LicenseKey=%2");
?>

Please look at the following lines of code
if ($result["MacAddress"] == NULL) {
// Insert new MAC address into the database.
$query = SQL_INSERT_MAC_ADDRESS;
$query = str_replace("%1", $macAddress, $query);
$query = str_replace("%2", $licenseKey, $query);
mysqli_query($db->connect(), $query);
}
// Add MAC address to license array.
$license["MacAddress"] = $result["MacAddress"];
You are running the following query but you are not storing the result in a variable after insertion in the database:
mysqli_query($db->connect(), $query);
In the following line the $result array has the old values from the database which were fetched prior to insertion. Please try to store the values in a variable and use that variable after the insertion.
$license["MacAddress"] = $result["MacAddress"];

Related

How to encode multiple results from mysql in php...I am getting 5 results but when i run the API it doesn't show any data as JSON format

I made an API in php to search from mysql database and database is giving me 5 results but in my php API when i run it...it isn't showing any data as response below is my API code.
This is my API of Php i am taking packagename as input in header and then find that input in mysql database which should return me with 5 results and i have to encode these 5 results into json nd send it as response.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "package";
//Create Connection
$conn = new mysqli($servername, $username, $password, $dbname);
//Check Connection
if($conn->connect_error) {
die("Connection Failed: " . $conn->connect_error);
}
$packagename = (print_r($_SERVER['HTTP_PACKAGENAME'],true));
//$pass = (print_r($_SERVER['HTTP_PASSWORD'],true));
//print_r($_SERVER);
//print_r(apache_request_headers());
$sql = "select * from `package_details` where Package_Name='$packagename' ";
$result = $conn->query($sql);
if($result->num_rows>0) {
//$response["package_details"] = array();
//Output data of each row
while($row = $result->fetch_assoc()) {
//temp user array
$user = array();
$user["id"] = $row["id"];
$user["Package_Name"] = $row["Package_Name"];
$user["Package_Day"] = $row["Package_Day"];
$user["Package_Description"] = $row["Package_Description"];
//push single product into final response array
//array_push($response["package_details"], $user);
}
//success
//$response["success"] = "valid";
//echoing JSON response
echo json_encode($user);
} else {
//no products found
$response["package_details"] = array();
while($row = null) {
$user = array();
$user["id"] = $row[null];
$user["Name"] = $row[null];
$user["Contact_Number"] = $row[null];
$user["Email_Id"] = $row[null];
//push single product into final response array
array_push($response["package_details"], $user);
}
$response["success"] = "invalid";
//$response["success"] = "invalid";
//$response["message"] = "No Products Found";
//echo no users JSON
echo json_encode($response);
}
?>
You were only json encoding the last $user and not the array of users that you should be putting in $response['package_details']
See the amended code below
$response = array();
if($result->num_rows>0) {
while($row = $result->fetch_assoc()) {
$user = array();
$user["id"] = $row["id"];
$user["Package_Name"] = $row["Package_Name"];
$user["Package_Day"] = $row["Package_Day"];
$user["Package_Description"] = $row["Package_Description"];
//push single product into final response array
$response["package_details"][] = $user;
}
//success
$response["success"] = "valid";
} else {
//no products found
$response["success"] = "invalid";
$response["message"] = "No Products Found";
}
echo json_encode($response);

Same mysqli query but different result while using with php

I have two php scripts to access data from my database table.
index.php
<?php
require "init.php";
$name = "Jack";
$user_query = "SELECT * FROM employee WHERE employeeName like '$name';";
$result = mysqli_query($con,$user_query);
$data = array();
$no_of_rows = mysqli_num_rows($result);
if($no_of_rows > 0)
{
$data["error"] = TRUE;
$data["message"] = "User Found";
echo json_encode($data);
}
else
{
$data["error"] = FALSE;
$data["message"] = "User Not Found";
echo json_encode($data);
}
?>
Here if I echo out the $no_of_rows, I get 1 which is correct since I have only one row corresponding to the name Jack.
Here is another approach to access the same data from the same table:
test.php
<?php
require "userTester.php";
$name = "Jack";
$mUser = new UserCheck();
$testResult = $mUser -> userPresent($name);
$data = array();
if($testResult == true)
{
$data["error"] = TRUE;
$data["message"] = "User Found";
echo json_encode($data);
}
else
{
$data["error"] = FALSE;
$data["message"] = "User Not Found";
echo json_encode($data);
}
?>
userTester.php
<?php
require "init.php";
class UserCheck
{
function userPresent($name)
{
echo "Name = " .$name;
$my_query = "SELECT * FROM employee WHERE employeeName like '$name';";
$result = mysqli_query($con,$my_query);
echo json_encode($result);
$num_of_rows = mysqli_num_rows($result);
echo "Rows = " .$num_of_rows;
if($num_of_rows > 0)
{
return true;
}
else
{
return false;
}
}
}
?>
In this case, the $num_of_rows always returns 0. In fact the sql query output is always null.
I am using the same db tables in both cases. I don't understand whats wrong.
Note:- the init.php is used to make the connection to the database and it works fine.
You failed to pass in the $con variable in your method.
You must change the method signature to pass in both the name variable and the connection variable.
You are getting no results because it doesn't have a database connection.

Memory Leak or Connection not closed

I am having three files index.php, DB_Function, DB_Connect to connect through mysql server. But response is very slow and task is almost running according to the hosting server people.
index.php
if (isset($_POST['tag']) && $_POST['tag'] != '') {
// get tag
$tag = $_POST['tag'];
// include db handler
require_once 'DB_Functions.php';
$db = new DB_Functions();
// response Array
$response = array("tag" => $tag, "success" => 0, "error" => 0);
// check for tag type
if ($tag == 'login') {
// Request type is check Login
$email = $_POST['email'];
$password = $_POST['password'];
// check for user
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false) {
// user found
// echo json with success = 1
$uservalue= $user["userid"];
$usercal = $db->getUserByuserid($uservalue);
if ($usercal != false) {
$response["usercal"]["userid"] = $usercal["userid"];
$response["usercal"]["newcalorie"] = $usercal["newcalorie"];
$response["usercal"]["oldcalorie"] = $usercal["oldcalorie"];
$response["usercal"]["flag"] = $usercal["flag"];
$response["usercal"]["fat"] = $usercal["fat"];
$response["usercal"]["carbohydrate"] = $usercal["carbohydrate"];
$response["usercal"]["protein"] = $usercal["protein"];
$response["usercal"]["startdate"] = $usercal["startdate"];
$response["usercal"]["enddate"] = $usercal["enddate"];
$response["usercal"]["createddate"] = $usercal["createddate"];
$response["usercal"]["updateddate"] = $usercal["updateddate"];
$response["usercal"]["createdby"] = $usercal["createdby"];
$response["usercal"]["updatedby"] = $usercal["updatedby"];
}
$response["success"] = 1;
$response["user"]["userid"] = $user["userid"];
$response["user"]["fname"] = $user["fname"];
$response["user"]["email"] = $user["email"];
$response["user"]["altemail"] = $user["altemail"];
$response["user"]["age"] = $user["age"];
$response["user"]["gender"] = $user["gender"];
$response["user"]["weight"] = $user["weight"];
$response["user"]["unit"] = $user["unit"];
$response["user"]["height"] = $user["height"];
$response["user"]["weightgoal"] = $user["weightgoal"];
$response["user"]["activitylevel"] = $user["activitylevel"];
$response["user"]["exerciselevel"] = $user["exerciselevel"];
$response["user"]["disease"] = $user["disease"];
$response["user"]["createddate"] = $user["createddate"];
$response["user"]["updateddate"] = $user["updateddate"];
$response["user"]["createdby"] = $user["createdby"];
$response["user"]["updatedby"] = $user["updatedby"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
}
else {
echo "Access Denied";
}
?>
DB_Function.php
<?php
class DB_Functions {
private $db;
//put your code here
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$this->db = new DB_Connect();
$this->db->connect();
}
// destructor
function __destruct() {
}
/**
* Get user by email and password
*/
public function getUserByEmailAndPassword($email, $password) {
$result = mysql_query("SELECT * FROM userDetails WHERE email = '$email' AND password = '$password'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
return $result;
} else {
// user not found
return false;
}
}
/**
* Get user by email and password
*/
public function getUserByuserid($uservalue) {
$result = mysql_query("SELECT * FROM CalorieInfo WHERE userid= '$uservalue' ") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
return $result;
} else {
$calresult = mysql_query("INSERT INTO CalorieInfo( userid,startdate, createddate, updateddate,createdby,updatedby) VALUES('$uservalue' ,NOW(), NOW(), NOW(),'$uservalue','$uservalue')");
if ($calresult) {
$id = mysql_insert_id();
$calresult = mysql_query("SELECT * FROM CalorieInfo WHERE id = $id");
return mysql_fetch_array($calresult);
}else{
// user not found
return false;
}
}
}
?>
DB_Connect.php
<?php
class DB_Connect {
// constructor
function __construct() {
//this->connect();
}
// destructor
function __destruct() {
//closing db
}
// Connecting to database
public function connect() {
require_once 'config.php';
// connecting to mysql
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(mysql_error());
// selecting database
mysql_select_db(DB_DATABASE) or die(mysql_error());
// return database handler
return $con;
}
// Closing database connection
public function close() {
mysql_close();
}
}
?>
Is there anything more optimized that i should be aware of ?
Is something missing in my code. Hosting people says that tomcat and mysql is consuming more task.
Here are my recommendations
1.- Always close the connection after retrieving the data.
2.- If you are expecting just one row for a query like this
"SELECT * FROM userDetails WHERE email = '$email' AND password = '$password'
you should add LIMIT 1 at the end of the query for retrieving the only possible row
3.-Add indexes to the table
4.-Test your performance with mysqlslap

MySQL query returns null results when used in php

I am getting null results when I use the following Like query in PHP Script
$MasjidName = $_GET['MasjidName'];
$Percent = "%";
$search = $Percent.$MasjidName.$Percent;
echo $search;
$sql = "SELECT * FROM `MasjidMaster` WHERE `MasjidName` LIKE '".$search."'";
// get a product from products table
$result = mysql_query($sql) or die(mysql_error());
I have tried the following too
$result = mysql_query("SELECT * FROM `MasjidMaster` WHERE `MasjidName` LIKE '%moh%'") or die(mysql_error());
The following is the null result I have been getting
{"masjids":[{"MasjidName":null,"Address":null,"Latitude":null,"Longitude":null}],"success":1,"masjid":[]}
whole code added below the following is the script i have been trying to get work
<?php
$response = array();
require_once dirname(__FILE__ ). '/db_connect.php';;
$db = new DB_CONNECT();
if (isset($_GET["MasjidName"]))
{
$MasjidName = $_GET['MasjidName'];
$MasjidName = mysql_real_escape_string($MasjidName); // you have to escape your variable here.
$sql = "SELECT * FROM `MasjidMaster` WHERE `MasjidName` LIKE '%$MasjidName%'";
$result = mysql_query($sql) or die(mysql_error());
$response["masjids"] = array();
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$row = mysql_fetch_array($result);
$masjid = array();
$masjid["MasjidName"] = $row["MasjidName"];
$masjid["Address"] = $row["Address"];
$masjid["Latitude"] = $row["Latitude"];
$masjid["Longitude"] = $row["Longitude"];
// success
$response["success"] = 1;
// user node
$response["masjid"] = array();
array_push($response["masjids"], $masjid);
}
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
Try this:
$MasjidName = $_GET['MasjidName'];
$MasjidName = mysql_real_escape_string($MasjidName); // you have to escape your variable here.
$sql = "SELECT * FROM `MasjidMaster` WHERE `MasjidName` LIKE '%$MasjidName%'";
$result = mysql_query($sql) or die(mysql_error());
Try using
$sql = "SELECT * FROM MasjidMaster WHERE MasjidName LIKE '".$search."'";
I tried SELECT * FROM Customers WHERE City LIKE 's%'; and it gave me perfectly fine result. But when i tried SELECT * FROM 'Customers' WHERE 'City' LIKE 's%'; it gave me a null result.
Just remove '' and give it a try. Hope it helps.

MySQL like Query fails in PHP

$result = mysql_query("SELECT * FROM MasjidMaster WHERE MasjidName LIKE ('%moh%')") or die mysql_error();
The error i get is
Parse error: syntax error, unexpected T_STRING in /home/maximtec/public_html/masjid_folder/MasjidFinderScripts/find_by_name.php on line 24
This query does work when i use it in MySQL but it doesn't when I place it in a PHP Script
Please suggest a solution
------------EDIT :After changing query from the received answers-------------------------------------
Well I updated my query but now I am getting null results
{"masjids":[{"MasjidName":null,"Address":null,"Latitude":null,"Longitude":null}],"success":1,"masjid":[]}
Following is my full script :
<?php
/*
* Following code will get single product details
* A product is identified by product id (pid)
*/
// array for JSON response
$response = array();
// include db connect class
//require_once __DIR__ . '/db_connect.php';
require_once dirname(__FILE__ ). '/db_connect.php';;
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["MasjidName"])) {
$MasjidName = $_GET['MasjidName'];
// get a product from products table
$result = mysql_query("SELECT * FROM `MasjidMaster` WHERE `MasjidName` LIKE '%moh%'") or die(mysql_error());
$response["masjids"] = array();
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$row = mysql_fetch_array($result);
$masjid = array();
$masjid["MasjidName"] = $row["MasjidName"];
$masjid["Address"] = $row["Address"];
$masjid["Latitude"] = $row["Latitude"];
$masjid["Longitude"] = $row["Longitude"];
// success
$response["success"] = 1;
// user node
$response["masjid"] = array();
array_push($response["masjids"], $masjid);
// array_push($response["masjid"], $masjid);
}
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
$result = mysql_query("SELECT * FROM `MasjidMaster` WHERE `MasjidName` LIKE '%moh%'") or die(mysql_error());
A little more tweaking, for good practice wrap table names and table columns in ``.
You also shouldn't need () around ('%moh%')
Try this-
$result = mysql_query("SELECT * FROM MasjidMaster WHERE MasjidName LIKE ('%moh%')") or die(mysql_error());
You forget parentheses with die(mysql_error())
try this:
$result = mysql_query("SELECT * FROM MasjidMaster WHERE MasjidName LIKE '%moh%' ") or die(mysql_error());
use die() like this die(mysql_error()) .

Categories