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.
Related
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.
Im trying to store and get HTML data made with tiny mce into database using PHP.
Its giving me this error: Warning: mysql_fetch_object(): supplied argument is not a valid MySQL result resource
Here is what ive tried:
save.php
<?php
include "functions.php";
$data = file_get_contents("php://input");
update_field($data);
show.php
<?php
include "functions.php";
search_field();
functions.php
<?php
function connect(){
return $yhteys = new mysqli("localhost", "root", "", "harjoitus20");
}
function search_field(){
$result = connect()->query('SELECT sisalto FROM Taulu WHERE nimi="harkka"');
while($row = mysql_fetch_object($result)) {
echo $row;
}
}
function update_field($data){
connect()->query('UPDATE Taulu SET sisalto="$data" WHERE nimi="harkka"');
}
Been trying to figure this out for a while now so any help would be appreciated.
Edit: In database it says $data in sisalto but shouldnt there be the content of my textarea?.
try to use echo before connect() , like this
echo connect()->query('UPDATE Taulu SET sisalto="$data" WHERE nimi="harkka"');
it might solve your issue
Hi have you tried:
while($row = mysqli_fetch_assoc($result)) {
echo $row['sisalto'];
}
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
A little help if possible. I have a Page that pulls from two data tables (MySQL) and one function is providing empty results.
function ShowClient() {
global $agent;
$sql = 'SELECT * FROM nuke_bulletins WHERE user=\'' . $agent . '\' AND isActive="Y" ORDER BY id';
$client = mysql_query($sql) or die('ERROR: OOPS Something went wrong' . mysql_error());
echo '<center><p><b>Current Campaigns</b></p>';
// Pull the loop and display the data
while($row = mysql_fetch_array($client)) {
$agent = stripslashes($row['user']);
$campaign = stripslashes($row['id']);
$title = stripslashes($row['title']);
echo '<p><b>' . $title . '</b></p>';
}
echo '<p>Click the Campaign Title to get the Bulletin Code</p><p> </p>';
echo '<p align="center"><b>Return to All Client\'s</p>';
}
The $agent variable is pulled from a main function that creates a url based on the user ($agent).
What am I doing wrong here?
$agent is a global variable. Using global variables is generally considered bad practice, as this could be getting set or unset somewhere before this function is called.
Have you checked the PHP Error Log to see if you are getting any errors?
If no errors in log I would look to see if $agent conatins a value either by echoing to screen (if dev environment) or dumping the value in the error log file to see if it actually contains anything. http://www.php.net/manual/en/function.error-log.php
Then I would look at the SQL itself; do the Column headings in your table nuke_bulletins match the $row array keys exactly for instance are they the same case?
$row['title']
or
$row['Title']
Here we go...
Don't use the mysql extension. It is unmaintained and officially deprecated
Don't use globals. Relying on external state makes for smelly code
You're overwriting said global variable ($agent) in a loop. Terrible idea.
or die must die ~ http://www.phpfreaks.com/blog/or-die-must-die
I wouldn't recommend using echo within a function. Makes for spaghetti code
Your HTML is a bit of a mess
Here's my suggestion using the mysqli extension
function getCampaigns(mysqli $con, $agent) {
if (!$stmt = $con->prepare("SELECT id, title FROM nuke_bulletins WHERE user = ? AND isActive = 'Y' ORDER BY id")) {
throw new Exception($con->error, $con->errno);
}
$stmt->bind_param('s', $agent); // if the user column is a integer, use 'i' instead
if (!$stmt->execute()) {
throw new Exception($stmt->error, $stmt->errno);
}
$stmt->bind_result($id, $title);
$campaigns = []; // or array() if you're on PHP < 5.4
while ($stmt->fetch()) {
$campaigns[$id] = $title;
}
return $campaigns;
}
Now you can call this function like this...
<?php
// assuming you have a mysqli instance in a $con variable, eg $con = new mysqli(...)
// and an $agent variable
$campaigns = getCampaigns($con, $agent);
?>
<p><strong>Current Campaigns</strong></p>
<?php foreach ($campaigns as $id => $title) : ?>
<p>
<a href="bullies2.php?op=ShowCampaign&id=<?= $id ?>">
<strong><?= htmlspecialchars($title) ?></strong>
</a>
</p>
<?php endforeach ?>
<p>Click the Campaign Title to get the Bulletin Code</p>
<p> </p>
<p align="center"><strong>Return to All Client's</strong></p>
And, as always, your development environment should have the following properties set in your php.ini file
display_errors = On
error_reporting = E_ALL
The code below calls a PHP file for a true or false text result using the dojo.xhrGet method. When I load the PHP file by itself (replacing the $variable = $_GET("passedVariable"); with a hard-wired value), it correctly generates a "true" or "false" in my browser window. However, when I run the call in my larger web app, it returns the PHP source code instead of the results of my database query. Using JQuery's .get() method, I receive a XML object.
Here's the Javascript...
dojo.xhrGet({
url: "php/check.php",
handleAs: "text",
content: {guid: featureGuid},
load: function(response){
alert(response);
dojo.style(dojo.byId("photoLink"), "display", "");
}
});
Here's the PHP...
<?php
$guid = $_GET["guid"];
// Connect to Database
$server = "server";
$connectionSettings = array("Database"=>"db", "UID"=>"uid", "PWD"=>"pwd");
$connection = sqlsrv_connect($server, $connectionSettings);
if (!$connection){
die("Failed Connection");
}
// Prepare and Execute query
$sql = "sql";
$results = sqlsrv_query($connection, $sql);
if ($results){
$rows = sqlsrv_has_rows( $results );
if ($rows === true) {
header('Content-Type: text/plain');
echo "true";
}
else {
header('Content-Type: text/plain');
echo "false";
}
}
else{
header('Content-Type: text/plain');
echo "false";
}?>
Anything anybody see wrong with this?
Thanks.
I'd check the requests and responses using Firebug - check that the URLs and headers are the same when you call the URL directly from the browser as opposed to via the XHR.
I am not sure but:
Try making sure that your Main App is executing PHP properly, it seems odd that JavaScript can pull the source code.
Try adding: die() after echo true or echo false which will prevent it from going any further.
The reason I say to check the larger app for PHP execution is because it almost seems like the webserver is rendering the source code as html and not running it through the interpreter.