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.
Related
I am new to php and am trying to return a json response in a particular structure. Here is what I have tried so far:
$response = array();
if ($con) {
$sql = "select * from admission_view";
$result = mysqli_query($con, $sql);
if ($result) {
$x = 0;
while ($row = mysqli_fetch_assoc($result)) {
$response[$x]['id'] = $row['id'];
$response[$x]['name'] = $row['name'];
$response[$x]['isActive'] = $row['isActive'];
$response[$x]['branchId'] = $row['branchId'];
$response[$x]['branch'] = $row['branch'];
$response[$x]['customerGroupId'] = $row['customerGroupId'];
$response[$x]['customerGroup'] = $row['customerGroup'];
$response[$x]['orderNo'] = $row['orderNo'];
$x++;
}
echo json_encode($response, JSON_PRETTY_PRINT);
}
} else {
echo "Connection error";
}
The code above returns this response:
However, instead of returning for example "branchId" and "branch" as individual properties, I want to pass their values inside a branchObject such that branch.id == "branchId" and branch.name == "branch".I mean, How may I return the response in the following structure:
And Here is how my database looks like:
How can I achieve this?
You ask for stuff that we are unsure if db result returns but as nice_dev pointed out, you need something like this:
$response = [];
if ($con) {
$sql = "select * from admission_view";
$result = mysqli_query($con, $sql);
if ($result) {
$x = 0;
while ($row = mysqli_fetch_assoc($result)) {
$response[$x]['id'] = $row['id'];
$response[$x]['name'] = $row['name'];
$response[$x]['isActive'] = $row['isActive'];
$response[$x]['branch']['id'] = $row['branchId'];
$response[$x]['branch']['name'] = $row['branch'];
$response[$x]['customerGroup']['id'] = $row['customerGroupId'];
$response[$x]['customerGroup']['name'] = $row['customerGroup'];
$response[$x]['customerGroup']['orderNo'] = $row['orderNo'];
$x++;
}
echo json_encode($response, JSON_PRETTY_PRINT);
}
} else {
echo "Connection error";
}
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"];
I have a php script which retrieves data from mysql db.
Everything works fine, but my problem is that this $result = $dao->joinedEvents($userId); returns an array of numbers and what I would like to do is to run this $secondResult = $dao->joinedEventsInfo($receivedIds); for every ID and this script I'm using right now returns data only for one ID.
This is part of my php script:
$userId = htmlentities($_REQUEST["userId"]);
$result = $dao->joinedEvents($userId); //This is getting the IDs array
if(!empty($result)) {
$receivedIds = $result["event_id"];
$ids = explode(",", $receivedIds);
foreach($ids as $id){
$secondResult = $dao->joinedEventsInfo($id);
if(!empty($secondResult)) {
$returnValue["finalResult"][] = $secondResult;
} else {
$returnValue["status"] = "error";
$returnValue["message"][] = "Could not find records for id" . $id;
}
}
} else {
$returnValue["status"] = "Empty error";
$returnValue["message"] = "Could not find records";
}
$dao->closeConnection();
echo json_encode($returnValue);
And this is joinedEvents script:
public function joinedEvents($userId){
$returnValue = array();
$sql = "SELECT event_id from MyTable WHERE userId= '$userId' LIMIT 0 , 30";
$statement = $this->conn->prepare($sql);
if (!$statement)
throw new Exception($statement->error);
$statement->execute();
$result = $statement->get_result();
while ($myrow = $result->fetch_assoc())
{
$returnValue[] = $myrow;
}
return $returnValue;
}
This is joinedEventsInfo script:
public function joinedEventsInfo($eventId){
$returnValue = array();
$sql = "SELECT * FROM Events WHERE eventId = '$eventId' LIMIT 0 , 30";
$statement = $this->conn->prepare($sql);
if (!$statement)
throw new Exception($statement->error);
$statement->execute();
$result = $statement->get_result();
while ($myrow = $result->fetch_assoc())
{
$returnValue[] = $myrow;
}
return $returnValue;
}
Edit: Tha reason I need this is that I have two tables. In the first one I have just IDs and in the second one I have info. So first I need to get the IDs and then I need to get data for every ID I have just received.
Thank you very much , I'm totally stuck.
Based on the updated code snippets and the discussion below, it is found that $result is indeed an array, and the solution is:
$userId = htmlentities($_REQUEST["userId"]);
$result = $dao->joinedEvents($userId);
if(count($result)){
foreach($result as $array){
$event_id = $array['event_id'];
$secondResult = $dao->joinedEventsInfo($event_id);
if(!empty($secondResult)) {
$returnValue["finalResult"][] = $secondResult;
} else {
$returnValue["status"] = "error";
$returnValue["message"][] = "Could not find records for id: " . $event_id;
}
}
}else {
$returnValue["status"] = "Empty error";
$returnValue["message"] = "Could not find records";
}
$dao->closeConnection();
echo json_encode($returnValue);
Have you tried array_map()?
That would allow you to call a php function on each member of an array easily.
Another way would be to use the common while ($row = mysql_fetch_array($result)) which would execute the code in the while loop for each row of your returned results. Note, you will likely have to change the mysql_fetch_array to something specific for your SQL connection.
I was trying to pull out data from my model, and its results are in array. I tried to pass the return object in to my controller, and echo the result in JSON, but it seems it cannot receive the object.
I making another php file not in MC pattern. And it work.
Here's my code for getting the objects (This one works - sequential approach):
if($_SERVER['REQUEST_METHOD'] == 'GET'){
require('dbConnect.php');
$SQLi_ORG_FEEDS = "SELECT organizationName,
organizationDescription,
organizationCategory,
organizationCurrentMembers,
organizationMaxMembersNo,
organizationType,
organizationLogo,
organizationLogoPath
FROM org_information";
$query = mysqli_query($dbConnect,$SQLi_ORG_FEEDS) or die("Error".mysqli_error($dbConnect));
$checkRow = mysqli_num_rows($query);
$response = array();
if($checkRow > 0){
while ($getRecord = mysqli_fetch_array($query)) {
$response[] = $getRecord;
}
echo json_encode($response);
}
else {
$response['failed'] = 'failed';
echo json_encode($response);
}
Result in POSTMAN
This method is from my model :
public function getAllOrgRegistered(){
//STATEMENT
$sql_show_org = "SELECT organizationName,
organizationDescription,
organizationCategory,
organizationCurrentMembers,
organizationMaxMembersNo,
organizationType,
organizationLogo,
organizationLogoPath
FROM org_information";
//EXECUTE
$result = mysqli_query($this->db->connect,$sql_show_org) or die(mysqli_error($this->db->connect));
$checkResults = mysqli_num_rows($result);
$response = array();
//CHECK FOR RESULTS
if ($checkResults > 0) {
while ($getRecord = mysqli_fetch_array($result)) {
$response[] = $getRecord;
}
return $response;
}else{
return FALSE;
}
}
I echo the json object. How do I catch this response from my model to my controller ?
if($_SERVER['REQUEST_METHOD'] == 'GET'){
//INCLUDE CLASS
require_once($_SERVER['DOCUMENT_ROOT'] .'/yayongeppn/OOP/models/orgCreateOrganization.php');
//NEW INSTANCE OF AN OBJECT
$orgCreate = new orgCreateOrganization();
//TAG
$tag = $_POST['tag'];
if($tag == 'org'){
$response = array();
$result = $orgCreate->getAllOrgRegistered();
if ($result != FALSE) {
// while ($getRecord = mysqli_fetch_array($result)) {
// $response[] = $getRecord;
// }
echo json_encode($result);
}else{
$response['error'] = "Failed to fetch data.";
echo json_encode($response);
}
}
}//END SERVER
I really need your help.
Here is my function in DB_Functions.php, i want to get two different values from two different tables in single function only here is the code what i have tried so far but the values are coming null.
public function getUserMetvalue($exname,$fname) {
$result = mysql_query("SELECT metvalue FROM fitnessactivitylist WHERE activityname='$exname'") or die(mysql_error());
$result1 = mysql_query("SELECT weight FROM users WHERE name='$fname'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
$no_of_rowss = mysql_num_rows($result1);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
if ($no_of_rowss > 0) {
$result1 = mysql_fetch_array($result1);
return $result1;
}
return $result;
} else {
//exercise name not found
return false;
}
}
here is my index.php
//TAG METVALUE
if ($tag == 'metvalue') {
$exname = $_POST['exname'];
$fname = $_POST['fname'];
$usermetvalue = $db->getUserMetvalue($exname,$fname);
if ($usermetvalue != false) {
$response["success"] = 1;
$response["usermetvalue"]["exname"] = $usermetvalue["exname"];
$response["usermetvalue"]["fname"] = $usermetvalue["fname"];
echo json_encode($response);
}
else {
$response["error"] = 1;
$response["error_msg"] = "No exercise found!";
echo json_encode($response);
}
}
Spot the differences:
$result = mysql_query("SELECT metvalue etc...
^^^^^^^^
$result1 = mysql_query("SELECT weight etc...
^^^^^^
$response["usermetvalue"]["exname"] = $usermetvalue["exname"];
^^^^^^
$response["usermetvalue"]["fname"] = $usermetvalue["fname"];
^^^^^
You fetch fields which aren't used later, then attempt to access fields which weren't fetched in the first place...
function a_function() {
$a = 'Learn';
$b = 'Programming.';
return array($a, $b);
}
list($one, $two) = a_function();
echo $one . ' ' . $two;