get json data in function php - php

I am new in this json chapter.I have a file named mysql_conn.php .This file have a php function to call data from mysql database.So can anyone help me to create one json file to get data from mysql_conn.php.Below is my code
mysql_conn.php
function getWrkNoTest($wrkno){
$conf = new BBAgentConf();
$log = new KLogger($conf->get_BBLogPath().$conf->get_BBDateLogFormat(), $conf->get_BBLogPriority() );
$connection = MySQLConnection();
$getWrkNoTest ="";
$lArrayIndex = 0;
$query = mysql_query("
SELECT
a.jobinfoid,
a.WRKNo,
a.cate,
a.det,
a.compclosed,
a.feedback,
a.infoID,
b.callerid,
b.customername
FROM bb_jmsjobinfo a
LEFT JOIN bb_customer b
ON a.customerid = b.customerid
WHERE a.WRKNo = '$wrkno';"
);
$result = mysql_query($query);
$log->LogDebug("Query[".$query."]");
while ($row = mysql_fetch_array($result)){
$getWrkNoTest = array("jobinfoid"=>$row['jobinfoid'],
"WRKNo"=>$row['WRKNo'],
"cate"=>$row['cate'],
"det"=>$row['det'],
"compclosed"=>$row['compclosed'],
"feedback"=>$row['feedback'],
"infoID"=>$row['customerid'],
"customerid"=>$row['infoID'],
"callerid"=>$row['callerid'],
"customername"=>$row['customername']);
$iList[$lArrayIndex] = $getWrkNoTest;
$lArrayIndex = $lArrayIndex + 1;
}
$QueryResult = print_r($getWrkNoTest,true);
$log->LogDebug("QueryResult[".$QueryResult."]");
closeDB($connection);
return $iList;
}
json.php
if ($_GET['action']=="getJsonjms"){
$wrkno = $_GET["wrkno"];
if($wrkno != ""){
$jms = getWrkNoTest($wrkno);
if(!empty($jms)){
echo json_encode($jms);
}else{
echo "No data.";
}
}else{
echo "Please insert wrkno";
}
}
I dont know how to solve this.Maybe use foreach or something else.Sorry for my bad english or bad explanation.I'm really new in this json things. Any help will appreciate.Thanks

If I understand your question right, you want to convert the results you receive from your MySQL query into JSON and then store that data into a file?
If this is correct, you can build off of what you currently have in json.php. In this block here, you use json_encode():
if(!empty($jms)){
echo json_encode($jms);
}
We can take this data and pass it to file_put_contents() to put it into a file:
if (!empty($jms)) {
$json = json_encode($jms);
// write the file
file_put_contents('results.json', $json);
}
If this is a script/page that's visited frequently, you'll want to make the filename (above as results.json) into something more dynamic, maybe based on the $wrkno or some other schema.

Related

JSON is overwriting the old data how to keep on adding data with new ID

so, I am working on a JSON file that should keep on incrementing IDs.
However I get stuck at id:0 and when I insert new data the old data will be replaced by the new one (it keeps id:0).
I am not entirely sure what code is related and what not, so I will post whatever I think should be related and if someone with more knowledge related to JSON could adjust (in case it needs any) it, I would appreciate it a lot.
The include database_json.php contains the following code:
$databaseFile = file_get_contents('json_files/database.json');
$databaseJson = json_decode($databaseFile, true);
$database = $databaseJson['data'];
// below starts a new page, the page that submits the form called saveJson.php
include_once('database_json.php');
$data = $_POST;
//Setup an empty array.
$errors = array();
if (isset($data)) {
$newExerciseData = $data;
$exerciseArray = $data['main_object'];
$databaseFile = 'json_files/database.json';
$textContent = file_get_contents($databaseFile);
$database = json_decode($textContent, true);
if ($data['id'] === 'new') {
if (count($database['data']) == 0) {
$ID = 0;
} else {
$maxID = max($database['data']);
$ID = ++$maxID["id"];
}
$newJsonFile = 'jsonData_' . $ID . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData = array(
'id' => $ID,
// a lot of variables that aren't related to the problem
);
$database['data'][] = $newArrayData;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
} else {
$index = array_search((int) $_POST['id'], array_column($database['data'], 'id'));
$correctJsonFile = 'json_files/jsonData_' . $_POST['id'] . '.json';
$newJsonFile = 'jsonData_' . $_POST['id'] . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData2 = array(
'id' => (int) $_POST['id'],
// more not related to problem variables
);
$database['data'][$index] = $newArrayData2;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE));
}
echo json_encode($newExerciseData, JSON_UNESCAPED_UNICODE);
}
EDIT: someone wanted me to post how the JSON itself looked like... so this is how it looks:
The file is called: database.json
{
"data":
[
{
"id":0,
"exercisetitle":"Test300520180924",
"exerciseWord":["huiswerk"],
"syllables":["Huis","werk"],
"file":"jsonData_.json",
"audio":null,"language":null
}
]
}
(do not mind the audio and language, that's something for later on.
The best I could do was this, yes I read the stuff about making a post and how to properly format stuff etc. but I people would often say I need to include certain code etc etc. and it mostly would turn out messy as hell, so I would rather have a bit too much code (the code I think is related) then not have enough.
Cheers!

FullCalendar, JSON array empty but working on PHP file

I am configuring FullCalendar with a MySQL DB, using PHP to process and return a JSON.
db-connect.php - fetches results from my Db and encodes to JSON.
get-events.php - reads JSON, converts to FullCalendar
json.html - is my front-end calendar view
File contents below, but before reading: db-connect.php successfully outputs JSON that I have verified on JSONLint.
[{"title":"Test new calendar","start":"2015-07-21","end":"2015-07-22"}]
get-events.php is successfully 'reading' db-connect.php as the "php/get-events.php must be running." error message on my front-end view has disappeared (shows if for example it can't establish that db-connect.php is in the directory, or spelling error in file name, etc).
However when I either pass the query via params or check in Firebug console, the JSON array is empty.
/cal/demos/php/get-events.php?start=2015-07-01&end=2015-07-31
returns [] whereas my test calendar entry does fall within these parameters.
I'm convinced it's my db-connect.php that is the error, but I'm scratching my head about it. Relative newbie so I'm sure it's obvious!
db-connect.php
<?php
$db = mysql_connect("localhost:3306","root","");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
mysql_select_db("test",$db);
$result = mysql_query("select * from cal", $db);
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['title'] = $row['title'];
$row_array['start'] = $row['start'];
$row_array['end'] = $row['end'];
array_push($json_response,$row_array);
}
echo json_encode($json_response);
mysql_close($db);
?>
get-events.php
<?php
// Require our Event class and datetime utilities
require dirname(__FILE__) . '/utils.php';
if (!isset($_GET['start']) || !isset($_GET['end'])) {
die("Please provide a date range.");
}
$range_start = parseDateTime($_GET['start']);
$range_end = parseDateTime($_GET['end']);
$timezone = null;
if (isset($_GET['timezone'])) {
$timezone = new DateTimeZone($_GET['timezone']);
}
$json = file_get_contents(dirname(__FILE__) . '/db-connect.php');
$input_arrays = json_decode($json, true);
$output_arrays = array();
if (is_array($input_arrays) || is_object($input_arrays))
{
foreach ($input_arrays as $array) {
$event = new Event($array, $timezone);
if ($event->isWithinDayRange($range_start, $range_end)) {
$output_arrays[] = $event->toArray();
}
}
}
echo json_encode($output_arrays);
file_get_contentsdoesn't parse the php file. It will output the programmcode in this case. Add this function to your get-events.php
function loadPhpFile($file) {
ob_start();
include $file;
$content = ob_get_contents();
ob_end_clean();
return $content;
}
And then replace
$json = file_get_contents(dirname(__FILE__) . '/db-connect.php');
with
$json = loadPhpFile(dirname(__FILE__) . '/db-connect.php');
And as a hint: Please use objects (OOP) and mysqli. PHP Mysqli

PHP - getting image from database

I want to save user's image to a database.
p9_member (member_no ,member_name , .... , member_photo)
Now, I am using a BLOB to save the image for "member_photo" column
What I want to do now is that:
1. I have an application that need to connect the database and get the image from the database.
2. I have also a website doing the same things.
I am implementing the application now. As I need to send the image with some information of the member like name or id. So I create an object to save all the things. This is my PHP code:
<?PHP
Class Friends{
var $no;
var $name;
var $photo;
var $status;
var $admin;
public function __construct($no,$name,$photo,$admin,$status){
$this->name = $name;
$this->photo = $photo;
$this->no = $no;
$this->status=$status;
$this->admin=$admin;
}
};
include ("../../server_config.php");
$friends = array();
$SQL = "SELECT p9_member.member_no,p9_member.photo AS PHOTO,p9_member.name,p9_member.photo FROM p9_member, p9_friends WHERE p9_member.member_no = p9_friends.member_no2 AND p9_friends.member_no1 =".$_POST['memberno'];
$result = mysqli_query($con,$SQL);
if (mysqli_num_rows($result)>0) {
while($row = mysqli_fetch_array($result)){
$friends[] = new Friends($row['member_no'],$row['name'],$row['photo'],null,null);
}
}else
$friends[] = 0;
echo json_encode($friends);
?>
The SQL CODE:
SELECT p9_member.member_no,p9_member.photo AS PHOTO
FROM p9_member, p9_friends
WHERE p9_member.member_no = p9_friends.member_no2
AND p9_friends.member_no1 =".$_POST['memberno']
I cannot get the data back from the application after json decode.
What is the best solution for me?
TRY the below code it will work..
$image_qry=mysql_query("SELECT * FROM tabel_name WHERE your condition");
$image=mysql_fetch_assoc($image_qry);
$get_image=$image['image_column']; //BLOB DATA TYPE
header("Content-type: image/jpeg"); // need to add the header content type in your code
echo $get_image;

From PHP to Javascript

I have the following code on my PHP webapp, it uses PHP to look for products in a Sqlite3 Databse file locally. I was tryng to convert it into an Android App with Phonegap, but sadly Phonegap does't work with PHP, so I thought I could make a JavaScript file replacing the PHP.
However, I can't get it to work. In case what I am trying to do is impossible, I guess there should be a way to execute the PHP files on the server and just display the results on the app.
($_GET['busq']){
$busq=$_GET['busq'];
function ultlet($cadena) {
$cant = strlen($cadena);
$cant--;
$let = substr($cadena, $cant);
if ($let == "s") {
$cadena = substr($cadena, 0, $cant);
}
return $cadena;
}
str_replace("-",$busq," ");
$arreg=explode(" ",$busq);
$cuent=count($arreg);
for($a=0;$a<$cuent;$a++){
$arreg[$a] = ultlet($arreg[$a]);
}
$query="SELECT * from MyTable WHERE";
for($i=0;$i<$cuent;$i++){
if ($i>=1){
$query=$query." AND ";
}
$query=$query." (col1 LIKE \"%$arreg[$i]%\" OR col6 LIKE \"%$arreg[$i]%\") ";
}
$db = new PDO('sqlite:MyDatabase.sqlite');
$result = $db->query($query);
foreach ($result as $row) {
if ($row['codigo_cat']!=null){
$class = 'class="image"';
}else{
$class = 'class="row"';
}
echo '<div '.$class.' alt="'.$row['col4'].'">';
echo 'Codigo: '.$row['col2']." / ".$row['col3']."<br>";
echo 'Nombre: '.$row['col1']."<br>";
echo '</div>';
}
}
There is also another file wich based on the user's input on a search bar creates the variable 'busq' which is used to display the products and its prices.
Modify the PHP script to output its contents as an xml file, and use javascript's XMLHttpRequest function to create a request to the file, and get the information you need.

Multiple save on upload plus save on database errors

I have set of questions have you ever encounter some issues when multiple save on database?my problem is this, i have a database called "album" where fields are 'album_id,album_title,album_user'.
The html output would be there is a login section where there is a input type file where you want to add more and once you have uploaded it. and array of set of names will be stored and that array will be our que to save the file on the multiple format the problem is that. it says and error on the database whichs is sql specified twice.Do you have an idea on how to save in multiple using php?
code will be like this.
<?php
class Album extends olib{
function __construct(){
parent::olib();
}
function upload_submit() {
$allow = array("jpg","png","gif");
$directory = "upload";
$pictures = array();
$counter = 0;
$error = '';
if($this->jpost('upload')) {
for($getupload = 0;$getupload<count($_FILES['uploadpictures']['name']);$getupload++){
$extension = end(explode(".",$_FILES['uploadpictures']['name'][$getupload]));
if(in_array(strtolower($extension),$allow)){
if(move_uploaded_file($_FILES['uploadpictures']['tmp_name'][$getupload],$directory."/".$_FILES['uploadpictures']['name'][$getupload])){
$pictures[$getupload] = $_FILES['uploadpictures']['name'][$getupload];
$counter++;
// $this->save_user_album($_FILES['uploadpictures']['name'][$getupload],$this->setSession('user_id'));
}else{
$error[$getupload] = "Sorry seems some of the data invalid";
}
}else{
$error = '1';
}
}
print_r($pictures);
print_r($error);
foreach($pictures as $urpics){
$this->save_user_album($urpics,$this->setSession('user_id'));
}
}
}
function save_user_album($albumtitle,$session){
$_firewall = ($this->setSession('user_id') !=="") ? $this->setSession('user_id') : "";
$this->jfields('album_pics_title',$albumtitle);
// $this->jfields('album_pics_user',$session);
return $this->jSave('album_pics');
}
}
any response will greatly appreciated!!
Hi I'm sorry seems i have a solution for this i have unset after it has been save..
unset($this->jfields); problem has been solved

Categories