How to get an array instead of json object? - php

<?php
$link = mysql_connect('localhost', 'root', 'admin')
or die('There was a problem connecting to the database.');
mysql_select_db('hospitalmaster');
$hnum = (int)$_POST["hnum"];
$sql = "SELECT d.doctorid, d.doctorname
from hospitalmaster.doctor_master d
inner join pharmacymaster.pharbill e
where e.hnum = '$hnum'
and e.presid = d.d_empno
group by e.presid";
$result = mysql_query($sql);
$response = array();
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$response = $row;
}
echo json_encode(array("Doctor"=>$response));
} else {
echo ("no DATA");
}
?>
i have the api shown above, but this api is returning me as json objects not an json array? i would like to know how to get dotorid an doctorname as a array, since i have many doctor names and id, i want each doctor and their corresponding id as an idividual array, right now they are returning as individual objects. Since this is my first time writing an api, i dont know how to modify the code.

You are over writing the array each time round the loop.
while ($row = mysql_fetch_assoc($result)) {
$response[] = $row;
//change ^^
}
You should use either mysqli_ or PDO. Here is a suggestion for mysqli_
<?php
$link = mysqli_connect('localhost', 'root', 'admin','hospitalmaster')
or die('There was a problem connecting to the database.');
$sql = "SELECT d.doctorid, d.doctorname
from hospitalmaster.doctor_master d
inner join pharmacymaster.pharbill e
where e.hnum = ?
and e.presid = d.d_empno
group by e.presid";
$stmt = $link->prepare($sql);
$stmt->bind_param('i', (int)$_POST["hnum"]);
$stmt->execute();
if ($stmt->num_rows() > 0) {
$result = $stmt->get_result();
$response = array();
while ($row = $result->fetch_assoc()) {
$response[] = $row;
}
echo json_encode(array("Doctor"=>$response));
} else {
echo ("no DATA");
}
?>

Related

PHP - queries on mySQL database and failure upon showing result in JSON format

So we recently set up a mySQL database for a project in our university and are currently working on the data access files written in php. In order to use the data on our front end we need it formatted as JSON. While putting an array of objects in the result of a certain object is working it won't work with 2 arrays of objects.
Working code:
<?php
include_once 'db.php';
$email = "email#online.com";
$conn = connect();
$conn->set_charset('utf8');
$resultArr = array();
$sql = "SELECT * FROM `customer` WHERE email = '$email'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$resultArr['customer'][$row['email']] = array('email' => $row['email'], 'address' => $row['address']);
$sql2 = "SELECT id, name, address FROM shop INNER JOIN rel_shop_customer WHERE customer_email='".$row['email']."' AND rel_shop_customer.shop_id = shop.id";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc()) {
$resultArr['customer'][$row['email']]['shops'][] = $row2;
}
}
$resultArr['customer'] = array_values($resultArr['customer']);
} else {
echo "failure";
}
echo json_encode($resultArr, JSON_UNESCAPED_UNICODE);
?>
And here is the not working code:
<?php
include_once 'db.php';
$email = "email#online.com";
$conn = connect();
$conn->set_charset('utf8');
$resultArr = array();
$sql = "SELECT * FROM `customer` WHERE email = '$email'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$resultArr['customer'][$row['email']] = array('email' => $row['email'], 'address' => $row['address']);
$sql2 = "SELECT id, name, address FROM shop INNER JOIN rel_shop_customer WHERE customer_email='".$row['email']."' AND rel_shop_customer.shop_id = shop.id";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc()) {
$resultArr['customer'][$row['email']]['shops'][] = $row2;
}
$sql3 = "SELECT img, name FROM ad INNER JOIN rel_customer_ad WHERE customer_email='".$row['email']."' AND rel_customer_ad.ad_name = ad.name";
$result3 = $conn->query($sql3);
while($row3 = $result3->fetch_assoc()) {
$resultArr['customer'][$row['email']]['ads'][] = $row3;
}
}
$resultArr['customer'] = array_values($resultArr['customer']);
} else {
echo "failure";
}
echo json_encode($resultArr, JSON_UNESCAPED_UNICODE);
?>
Both SQL queries provide the expected result when run directly on the database and I have no idea why the second one won't work in the PHP script.

JSON encoding not working

Here is my code to encode data in JSON format, but it doesn't work. The result is []. Where is my mistake?
<?php
$conn = new mysqli('localhost','root','','project');
$data =array();
if(!empty($_GET['masp'])){
$masp =$_GET['masp'];
$sql ="SELECT *FROM sanpham WHERE masp='$masp'";
$result = mysqli_query($conn,$sql);
if($result){
while($r = mysqli_fetch_assoc($result)){
$r['masp'] =$data['masp'];
$r['loai'] =$data['loai'];
$r['hangsx']=$data['hangsx'];
$r['tensp']=$data['tensp'];
$r['img']=$data['img'];
$r['gia']=$data['gia'];
$r['nx']=$data['nx'];
}
}
}
print json_encode($data);
?>
You are setting your variables wrong.
In every while cycle you get a new $r variable that you want to add to your $data variable.
$conn = new mysqli('localhost', 'root', '', 'project');
$data = array();
if (!empty($_GET['masp'])) {
$masp = $_GET['masp'];
$sql = "SELECT *FROM sanpham WHERE masp='$masp'";
$result = mysqli_query($conn, $sql);
$i = 0;
if ($result) {
while ($r = mysqli_fetch_assoc($result)) {
$data[$i]['masp'] = $r['masp'];
$data[$i]['loai'] = $r['loai'];
$data[$i]['hangsx'] = $r['hangsx']];
$data[$i]['tensp'] = $r['tensp'];
$data[$i]['img'] = $r['img'];
$data[$i]['gia'] = $r['gia'];
$data[$i]['nx'] = $r['nx'];
$i += 1;
}
}
}
print json_encode($data);
You make mistake. You should swap variable data with r inner loop, but probably than also will works unpropely. write in while loop $data [] = $r;

PHP - Insert Value with Key from another array into Array in Specific Place

I am trying to create a JSON object as an array from the data received from the SQL Query. Currently the encoded JSON I have got is:
[{"firstname":"Student","lastname":"1"},{"firstname":"Student","lastname":"2"},{"firstname":"Student","lastname":"3"}]
The values I want to insert from another array, the values are in corresponding order to the each array in the JSON above: (JSON)
["85.00000","50.00000","90.00000"]
So the JSON should look like:
{"firstname":"Student","lastname":"1","grade":"85.00000"}
My Current Code:
//Provisional Array Setup for Grades
$grade = array();
$userid = array();
$sqldata = array();
foreach($json_d->assignments[0]->grades as $gradeInfo) {
$grade[] = $gradeInfo->grade;
$userid[] = $gradeInfo->userid;
}
//Server Details
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "moodle";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
foreach($userid as $id) {
$sql = "SELECT firstname, lastname FROM mdl_user WHERE id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$sqldata[] = $row;
}
} else {
echo "ERROR!";
}
}
$sqlr = json_encode($sqldata);
$grd = json_encode($grade);
echo $sqlr;
echo $grd;
mysqli_close($conn);
try this code:
foreach($userid as $x => $id) {
$sql = "SELECT firstname, lastname FROM mdl_user WHERE id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$row['grade'] = $grade[$x];
$sqldata[] = $row;
}
} else {
echo "ERROR!";
}
}
I added the Variable $x and added $row['grade'] with the same index on the $gradearray
function set_column_values($arr, $column_name, $column_values) {
$ret_arr = array_map(function($arr_value, $col_value) use ($column_name) {
$arr_value[$column_name] = $col_value;
return $arr_value;
}, $arr, $column_values);
return $ret_arr;
}
$sqldata = set_column_values($sqldata, 'grades', $grade);
$sqlr = json_encode($sqldata);
var_dump($sqlr);
Hope it helps!

Identify JSON object from different table

I am trying to get data from three different tables (MySQL) using php script in xcode.
I know how to fetch elements from one table but I don't know how I can extend this method to be able to get the data from two other tables using the same php script and NSURLSession in xcode.
My php script for one table (working):
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno(). ') ' . mysqli_connect_error());
}
$sql = "SELECT * FROM table1";
$test = $mysqli->query($sql);
$Nrows = $test->num_rows;
$resultArray = array();
if ($result = mysqli_query($mysqli, $sql)) {
while ($row = $result->fetch_assoc()) {
$resultArray[] = $row;
}
echo json_encode($resultArray);
}
else {
echo 'oups.';
}
Now the problem is that I would like to do the same with two others tables. I tried to incorporate my fetching method in a separate php file (say getElementFunction.php) and calling this method in the main file:
getElementFunction.php
<?php
function getElements()
{
$test = $mysqli->query($sql);
$Nrows = $test->num_rows;
$resultArray = array();
if ($result = mysqli_query($mysqli, $sql)) {
while ($row = $result->fetch_assoc()) {
$resultArray[] = $row;
}
echo json_encode($resultArray);
}
else {
echo 'oups.';
}
}
?>
main_file.php:
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno(). ') ' . mysqli_connect_error());
}
include 'getElementFunction.php';
$sql = "SELECT * FROM table1";
getElements() // --> how can I flag the json object as being returned from table 1
$sql = "SELECT * FROM table2";
getElements() // --> how can I flag the json object as being returned from table 2
$sql = "SELECT * FROM table3";
getElements() // --> how can I flag the json object as being returned from table 3
But I don't know if it is correct and how I could "flag" the different json objects that will be returned in order to be used in my xcode script. I would like to run the fetching process in one loop with only one URL.
Just in case, my objective-C script where I need a way to specify from which table is the json object returned...
XCODE script with NSURLSession:
id jsonObject = [NSJSONSerialization JSONObjectWithData:_downloadedData options:NSJSONReadingAllowFragments error:&error];
if ([jsonObject isKindOfClass:[NSArray class]]) {
NSArray *deserializedArray = (NSArray *)jsonObject;
if (deserializedArray.count > 0) {
dispatch_async(dispatch_get_main_queue(), ^{
...
}
If someone could help me...
Thanks!
Not sure to clearly understand.. But you can try a foreach in getElements().
I mean :
function getElements(array $allSQL)
{
//Final array to json_encode
$finalResultsArray = array();
foreach($allSQL as $tableName => $sqlStatement) {
$arrayResults = array();
$test = $mysqli->query($sqlStatement);
$Nrows = $test->num_rows;
if ($result = mysqli_query($mysqli, $sqlStatement)) {
while ($row = $result->fetch_assoc()) {
$arrayResults[] = $row;
}
//echo json_encode($arrayResults);
$finalResultsArray[$tableName] = $arrayResults;
}
else {
echo 'oups.';
}
}
echo json_encode($finalResultsArray);
}
And this part :
$sql = "SELECT * FROM table1";
getElements() // --> how can I flag the json object as being returned from table 1
$sql = "SELECT * FROM table2";
getElements() // --> how can I flag the json object as being returned from table 2
$sql = "SELECT * FROM table3";
getElements() // --> how can I flag the json object as being returned from table 3
Become this :
$sql1 = "SELECT * FROM table1";
$sql2 = "SELECT * FROM table2";
$sql3 = "SELECT * FROM table3";
getElements(["table1"=> $sql1, "table2" => $sql2, "table3" => $sql3]);

How to do a simple mysqli query for a similar value?

I am looking for just a basic query using mysqli to search table for a particular value. For example; If 'a' exist in a table then echo 'already exists'.
Please help as I am still learning to move away from deprecated code.
$mysqli = new mysqli('localhost', 'root', 'pass', 'agents');
$result = $mysqli->query('select * from project');
if ($result)
{
$check = array();
while ($row = $result->fetch_assoc())
{
$check[] = $row['projectname'];
}
}
$a = 'a';
if ($a = $check)
{
echo "<script type='text/jscript'>
alert('already exists.')
</script>";
}
Databases are designed to do searching for you with WHERE clauses. There's no need to read the entire table when you can let the database do it for you.
$result = $mysqli->query("SELECT COUNT(*) AS found FROM project WHERE projectname = '$a'");
$row = $result->fetch_assoc();
if ($row['found'] > 0) {
echo "<script type='text/jscript'>alert('already exists.')</script>";
}
$mysqli = new mysqli('localhost', 'root', 'pass', 'agents');
$result = $mysqli->query("select * from project where projectName = 'a'");
if($result->num_rows > 0)
echo "already exists";
You have a logic error in your code. You try to compare array ($check) with string ($a). Try something like this:
$mysqli = new mysqli('localhost', 'root', 'pass', 'agents');
$result = $mysqli->query('select * from project');
if ($result) {
$check = array();
while ($row = $result->fetch_assoc()) {
$projectname = $row['projectname'];
if($projectname == 'a')
{
echo "<script type='text/jscript'>alert('already exists.')</script>";
break;
}
$check[] = $row['projectname'];
}
print_r($check);
}
else
{
echo "<script type='text/jscript'>alert('mysqli error')</script>";
}
This code will check every projectname in your table and will show alert if it exists projectname = 'a'.
P.s. If you want to contact with your database in really good way read about PDO driver (http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html)

Categories