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
Related
I would like to be able to save a JSON file that is in a database to the user's PC. In summary, I'm storing setup files from a sim racing game, that use a JSON format, in a database, and I'd like the user to be able to upload/download these JSON files (to share with others, etc).
I've got the upload working, using PDO, so there is a column called setup that is a text data type. I'm using a form, with a $FILES() to fetch the uploaded json file, with some checks to ensure it's a valid setup json.
$setup = file_get_contents($_FILES['setupjson']['tmp_name']); //get json from file uploaded
$setupJSON = json_decode($setup); //decode into object
$car = $setupJSON->carName; //carName from object
if ($obj->searchCarName($car) > 0) // if search matches (car exists)
{
if($obj->insertSingleSetup($_POST["name"], $_POST["description"], $_POST["type"], $car, $_POST["track"], $setup) !== false)
{
header('Location: add.php?success');
exit();
}
else
{
header('Location: add.php?error=Error+adding+the+setup');
exit();
}
}
else
{
header('Location: add.php?error=Please+submit+a+valid+setup');
exit();
}
}
The issue i'm having is downloading the file again. I've been able to view the JSON directly
<?php
include('../db.php');
$setup_id = $_POST['setup'];
try {
$connectionString = sprintf("mysql:host=%s;dbname=%s;charset=utf8mb4",
DB::DB_HOST,
DB::DB_NAME);
$pdo = new PDO($connectionString, DB::DB_USER, DB::DB_PASSWORD);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = 'SELECT * FROM setups WHERE setup_id= :setupID';
$query = $pdo->prepare($sql);
$query->bindValue(':setupID', $setup_id);
$result = $query->execute();
$setup = $query->fetch(PDO::FETCH_ASSOC);
processSetup($setup);
} catch (PDOException $e) {
die("Could not connect to the database $dbname :" . $e->getMessage());
}
function processSetup($setupRow)
{
$setup = $setupRow['setup'];
$setupJSON = json_decode($setup);
echo '<pre>';
echo $setup;
echo '</pre>';
}
?>
but I can't work out how to download it. I've researched that it's related to headers, but everytime I try something, it never works. I just want the save file dialog to appear with the json, and preferably, the option to set the filename outputted to a chosen variable.
Just figured it out, on the processSetup function, I changed the code to this
function processSetup($setupRow)
{
$setup = $setupRow['setup'];
header('Content-type: application/json');
header('Content-disposition: attachment; filename=setup.json');
echo $setup;
}
If I add some code to give the JSON it's proper filename, it'll be perfect :D
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!
I would like to find out how a PHP page calls another PHP page, which will return JSON data.
I am working with PHP (UsersView.php) files to display my contents of a website. However, I have separated the MySQL Queries in another PHP (Get_Users.php) file.
In the Get_Users.php, I will have a MySQL statement to query the database for data. It will then encode in JSON and be echo-ed out.
In the UsersView.php, I will call the Get_Users.php in order to retrieve the Users JSON data. The data will then be used to populate a "Users Table".
The thing is, I do not know how to call the "Get_Users.php" from the "UsersView.php" in order to get the data.
Part of UserView.php
$url = "get_user.php?id=" . $id;
$json = file_get_contents($url);
$result = json_decode($json, true);
I am trying to call the file which is in the same directory, but this does not seem to work.
Whole of Get_Users.php
<?php
$connection = mysqli_connect("localhost", "root", "", "bluesky");
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " . mysqli_connect_error() . " (" . mysqli_connect_errno() . ") " .
"<br>Please retry your last action. Please retry your last action. " .
"<br>If problem persist, please follow strictly to the instruction manual and restart the system.");
}
$valid = true;
if (!isset($_GET['id'])) {
$valid = false;
$arr=array('success'=>0,'message'=>"No User ID!");
echo json_encode($arr);
}
$id = $_GET['id'];
if($valid == true){
$query = "SELECT * FROM user WHERE id = '$id'";
$result = mysqli_query($connection, $query);
if(mysqli_num_rows($result) == 1){
$row = mysqli_fetch_assoc($result);
$arr=array('success'=>1,'type'=>$row['type'],'user_id'=>$row['id'],'email'=>$row['email'],'name'=>$row['name'],'phone'=>$row['phone'],'notification'=>$row['notification']);
echo json_encode($arr);
}else{
$arr=array('success'=>0,'message'=>"Invalid User ID!");
echo json_encode($arr);
}
}
mysqli_close($connection);
?>
You have a couple of different ways to accomplish this:
You should be able to first set the actual id and then include the Get_Users.php file like this. Notice that you should not echo out the output from Get_Users.php, instead only return the encoded json data using return json_encode($arr);:
// set the id in $_GET super global
$_GET['id'] = 1;
// include the file and catch the response
$result = include_once('Get_Users.php');
You can also create a function that can be called from UserView.php:
// Get_Users.php
<?php
function get_user($id) {
// connect to and query database here
// then return the result as json
return json_encode($arr);
}
?>
// In UserView.php you first include the above file and call the function
include_once('Get_Users.php');
$result = get_user(1);
You could also use file_get_contents(). Notice that you need to make sure so that allow_url_fopen is enabled in your php.ini file for this to work:
$result = file_get_contents('http://example.com/Get_Users.php?id=1');
To enable allow_url_fopen you need to open up your loaded configuration file and set allow_url_fopen=1 and finally restart your webserver.
You could also use curl to achieve the same result:
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, 'http://example.com/Get_Users.php?id=1');
$result = curl_exec($ch);
curl_close($ch);
An ajax request could also be made to get the result. This example uses jQuery:
$(document).ready(function() {
$.get({
url: 'Get_Users.php',
data: 'id=1',
success: function(response) {
// response contains your json encoded data
// in this case you **must** use echo to transfer the data from `Get_Users.php`
}
});
});
Change UsersView.php to like this
$actual_link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['CONTEXT_PREFIX'];
$url = "get_users.php?id=" . $id;
$url = $actual_link.$url;
$json = file_get_contents($url);
$result = json_decode($json, true);
This will work fine.
I'm trying to build an API with a JSON output, the second function is producing the desired output however I can't call it from the web. Whereas the first function returns as expected a large mass of text. Am I using something that is not compatible? I'm using version PHP 5.5.9 on an Ubuntu 14.04 server.
I can view the result of this function in both the terminal and the browser;
<?php
class ArticlesAPI {
function top() {
$db = new mysqli("mysql-host.rds.amazonaws.com", "user", "password", "db_name");
$results = $db->query("SELECT article_id, title, summary FROM top_articles");
while ($row = $results->fetch_assoc()) {
echo $row['article_id'];
echo $row['title'];
echo $row['summary'];
}
$results->close();
}
}
$api = new ArticlesAPI;
$api->top();
?>
This function only returns a result in the terminal;
<?php
class ArticleAPI {
function top() {
$db = new mysqli("mysql-host.rds.amazonaws.com", "user", "password", "db_name");
$results = $db->query("SELECT article_id, title, summary FROM top_articles");
$articles = array();
while($article = $results->fetch_assoc()){
$article_id = $article['article_id'];
$articles[$article_id][] = $article['title'];
$articles[$article_id][] = $article['summary'];
}
$results->close();
$db->close();
$json = json_encode($articles);
echo $json;
}
}
$api = new ArticleAPI;
$api->top();
?>
There are 2 separate configuration files for CLI and for WEB check them and check server configuration(if http server parse php files etc.) you can do simple <?php echo 'hello world'; and see if output is correct. If you open it via browser and you see anything more than hello world then PHP parser is not enabled.
Also when you output JSON you should set proper header for browser application/json
Check your output buffering settings. Maybe you use ob_* functions and don't flush output to browswer
Try putting exit after echo and check script after.
Set error_reporting(E_ALL); and ini_set('display_errors', 1); in first line of your app to check if there are errors.
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.