Identify JSON object from different table - php

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

Related

PHP - MySql SELECT WHERE value = string JSON

through a cURL connection, I can pick up data, from Json files, placed on a remote server. In particular, the codes of some products, which thanks to a foreach
foreach($data['results'] as $key=>$val){
$codici_hotel = $val['hotel_code'];
echo $codici_hotel.",";
}
I can see on video:
1074d0,19f726,1072ba,107104,183444,112438,15d8ab,1b326e,19d885,189b95,1071bf,107155,193e61,10aab2,138752,18dd7d,19d7f9,117b0d,1071b8,1398c4,107039,110851,107124,110669
Now I need to use that string to run a select on a local database, such as:
$sql = "SELECT * FROM hotels WHERE code = ('$codici_hotel')";
What is the correct sql string?
Thanks for your help
CODE UPDATE USED
$codici_hotel_arr = array();
foreach($data['results'] as $key=>$val){
$codici_hotel_arr[] = $val['hotel_code'];
}
$codici_hotel = "'".implode(",",$codici_hotel_arr)."'";
$conn2 = new mysqli($servername, $username, $password, $dbname);
if ($conn2->connect_error) {
die("Connection failed: " . $conn2->connect_error);
}
$sql2 = "SELECT name FROM hotels WHERE code IN ('$codici_hotel')";
$result2 = $conn2->query($sql2);
if ($result2->num_rows > 0) {
// output data of each row
while($row2 = $result2->fetch_assoc()) {
$nome_hotel = $row2["name"] ;
}
} else {
echo "0 results";
}
$conn2->close();
echo $nome_hotel;
You have to convert your all codes in string enclosed with '. Then use IN clause of mysql. change your code as below
$codici_hotel_arr = array();
foreach($data['results'] as $key=>$val){
$codici_hotel_arr[] = $val['hotel_code'];
}
$codici_hotel = "'".implode(",",$codici_hotel_arr)."'";
$sql = "SELECT * FROM hotels WHERE code IN ($codici_hotel)";

How to get an array instead of json object?

<?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");
}
?>

php's mysqli_multi_query not working

I've been trying to execute a multiple query, so I've searched for a better approach on how to do this and I've read this mysqli_multi_query in php.
I tried it on my own to see the results, but it keeps on giving me error. Here's the code:
$studid = $_GET['stud_id'];
$classcode = $_GET['class'];
$conn = new MySQLi($host, $username, $password, $dbname) or die('Can not connect to database');
$sql = "SELECT * FROM tbl_students WHERE stud_id = '".$studid."'";
$sql.= "SELECT * FROM tbl_classes WHERE class_code = '".$classcode."'";
if (mysqli_multi_query($conn, $sql)) {
do {
/* store first result set */
if ($result = mysqli_store_result($conn)) {
while ($row = mysqli_fetch_row($result)) {
$studname = $row[3].", ".$row[1];
}
mysqli_free_result($result);
}
/* print divider */
if (mysqli_more_results($conn)) {
printf("-----------------\n");
$studname = $row['fname'];
}
} while (mysqli_more_results($conn));
}else{ echo "error";}
$conn->close();
With the code above, it will just print error from the else statement I set. I also tried changing the second query to $sql .= "SELECT * FROM tbl_classes WHERE class_code = '".$classcode."'"; and also tried putting semicolon after the first query to tell the SQL that I'm done with the first query since I'm putting 2 strings together, but still no luck.
try this
$studid = $_GET['stud_id'];
$classcode = $_GET['class'];
$conn = new MySQLi($host, $username, $password, $dbname) or die('Can not connect to database');
$sql = "SELECT * FROM tbl_students WHERE stud_id = '$studid';";
$sql.= "SELECT * FROM tbl_classes WHERE class_code = '$classcode'";
if ($conn->multi_query($sql)) {
do {
/* store first result set */
if ($result = mysqli_store_result($conn)) {
while ($row = mysqli_fetch_row($result)) {
$studname = $row[3].", ".$row[1];
}
mysqli_free_result($result);
}
/* print divider */
if (mysqli_more_results($conn)) {
printf("-----------------\n");
$studname = $row['fname'];
}
} while (mysqli_more_results($conn));
}else{ echo "error";}
$conn->close();
Make one query instead of two :
"SELECT ts.*, tc.*
FROM tbl_students as ts, tbl_classes as tc
WHERE ts.stud_id = '$studid'
AND tc.class_code = '$classcode'"
Note : If you get redundant data then use group by.

PHP code to encode DB data in JSON not working

I'm currently stuck with some PHP code. I want to access a table in my database and retrieve the data in a JSON format. Therefore, I tried the following code :
<?php
$con = mysqli_connect("......","username","pwd","DBName");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM users";
if ($result = mysql_query($con, $sql))
{
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object())
{
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray);
}
mysqli_close($con);
?>
However, it's getting me an empty page. It worked once but only with a special number of row in the table, so not very efficient as you might guess.
Does anybody have an idea why i'm getting those weird results?
EDIT 1 :
I Just tried to add this to my code :
echo json_encode($resultArray);
echo json_last_error();
And it's returning me 5. It seems to be an error from the data encoding in my table. Therefore I added that code :
$tempArray = array_map('utf8_encode', $row)
array_push($resultArray, $tempArray);
And I got the following output : [null,null,null]0 (The zero comes from the echo json_last_error();)
So here I am, can anybody help me with this ?
I would start by changing if ($result = mysql_query($con, $sql)) to if ($result = mysqli_query($con, $sql)) because they are different database extensions
Another thing would be to change while($row = $result->fetch_object()) to while ($row = mysqli_fetch_object($result)) { (Procedural style vs. Object oriented style)
If you still see blank screen, try adding error_reporting(E_ALL); at the top of your script, and you'll be able to know exactly where the bug is
<?php
$con = mysqli_connect("......","username","pwd","DBName")
or die("Failed to connect to MySQL: " . mysqli_connect_error());
$sql = "SELECT * FROM users";
$query = mysqli_query($con, $sql) or die ("Failed to execute query")
if ($result = $query)
{
$resultArray = array();
while($row = $result->fetch_object())
{
array_push($resultArray, $row);
}
$result->close()
echo json_encode($resultArray);
}
mysqli_close($con);
?>
This code works for me, try it out:
<?php
$con = mysqli_connect("......","username","pwd","DBName");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM users";
if ($result = mysqli_query($con, $sql))
{
while($row = $result->fetch_object())
{
$resultArray[] = $row;
}
echo json_encode($resultArray);
}
mysqli_close($con);
?>
EDIT 1:
As a test replace this code:
while($row = $result->fetch_object())
{
$resultArray[] = $row;
}
echo json_encode($resultArray);
with this code:
while($row = $result->fetch_assoc())
{
print_r($row);
}
What output do you get?
I finally found a solution ! That was indeed an encoding problem, the json_encode() function accepts only strings encoded in utf8. I changed the interclassement of my table to utf8_general_ci and I modified my code as follows :
<?php
//Create Database connection
$db = mysql_connect(".....","username","pwd");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("DBName",$db);
//Replace * in the query with the column names.
$result = mysql_query("SELECT * FROM users", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['name'] = utf8_encode($row['name']);
$row_array['lastName'] = utf8_encode($row['lastName']);
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
//Close the database connection
fclose($db);
?>
And I got the expected output.

Errors when adding data to a database with PHP

I have to make a web app that gets information from my database, that gets its info from an API). Then I have to show items under certain conditions.
But when I try to add the data from the API, I got a strange message:
Notice: Trying to get property of non-object in c:\xampp\htdocs\IMP03\inleveropdracht3\libs\php\function.php on line 21
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\IMP03\inleveropdracht3\libs\php\function.php on line 21
Here is my PHP code:
<?php
require_once 'settings.php';
$mysqli = mysqli_connect($db_host, $db_user, $db_password, $db_database);
if (mysqli_connect_error()) {
echo mysqli_connect_error($mysqli) . "We are not able to connect to the online database";
}
jsondecode($mysqli);
if (isset($_GET['club']) && !empty($_GET['club'])) {
jsondecode($mysqli);
} else if (isset($_GET['thuisPoint']) && !empty($_GET['thuisPoint']) && ($_GET['uitPoint']) && ($_GET['uitPoint'])) {
updatePoints($mysqli);
} else {
getWedstrijd($mysqli);
}
function jsondecode($mysqli) {
$apiLink = 'http://docent.cmi.hr.nl/moora/imp03/api/wedstrijden?club=';
// $club = $_GET['club'];
$data = json_decode(file_get_contents($apiLink . "Ajax"));
foreach ($data->data as $info) {
$thuisClub = $info->homeClub;
$uitClub = $info->awayClub;
addWestrijden($mysqli, $thuisClub, $uitClub);
}
}
//querys
function addWestrijden($mysqli, $thuisClub, $uitClub) {
$query = "INSERT INTO wedstrijd VALUES(null, '$thuisClub', '$uitClub')";
$resultAddWedstrijd = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
getWedstrijd($mysqli);
}
function getWedstrijd($mysqli) {
$query = "SELECT * FROM wedstrijd ORDER BY thuisClub DESC";
$resultGetWedstijd = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
while ($result = mysqli_fetch_assoc($resultGetWedstijd)) {
$rows [] = $result;
}
header("Content-Type: application/json");
echo json_encode($rows);
exit;
}
function updatePoints($mysqli) {
$id = $_GET['id'];
$thuisPoints = $_GET['thuisPoint'];
$uitPoints = $_GET['uitPoint'];
$query = "UPDATE wedstrijd "
. "SET thuisPunt = '$thuisPoints', uitPunt = '$uitPoints') "
. "WHERE id = '$id'";
mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
getWedstrijd($mysqli);
}
I did modify it a bit so it would add data from the API. I really would appreciate it if someone could help me.
Change your foreach to:
foreach ($data as $data => $info)

Categories