How to retrieve info from MySQL using JSON? - php

I'm practicing using JSON but seems it's not retrieving the info intended.
The page shows the user details from database using JSON directly on the HTML output.
getjson
</p>
<?php
$mysql_db_hostname = "host";
$mysql_db_user = "user";
$mysql_db_password = "pass";
$mysql_db_database = "db";
$con = #mysqli_connect($mysql_db_hostname, $mysql_db_user, $mysql_db_password,
$mysql_db_database);
if (!$con) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
$var = array();
$sql = "SELECT * FROM users";
$result = mysqli_query($con, $sql);
while($obj = mysqli_fetch_object($result)) {
$var[] = $obj;
}
echo '{"users":'.json_encode($var).'}';
?>
<p style="text-align: justify;">
and in showjson
</p>
<table class="mGrid" id="jsondata">
<thead>
<th>Id</th>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
<th>Location</th>
</thead>
<tbody></tbody>
</table>
</div>
<script type="text/javascript">
$(document).ready(function(){
var url="getjson.php";
$("#jsondata tbody").html("");
$.getJSON(url,function(data){
$.each(data.users, function(i,user){
var newRow =
"<tr>"
+"<td>"+user.id+"</td>"
+"<td>"+user.name+"</td>"
+"<td>"+user.age+"</td>"
+"<td>"+user.gender+"</td>"
+"<td>"+user.location+"</td>"
+"</tr>" ;
$(newRow).appendTo("#jsondata tbody");
});
});
});
</script>
<p style="text-align: justify;">
database users with id,name,gender,location

You have a trailing <p style="text-align: justify;"> on your JSON which renders it invalid so it will not parse.
Remove it.
You should have examined the data you got back from the PHP (either by accessing it though your browser's developer tools Net tab or accessing the URL directly). You could have then tested the JSON with a tool like JSON Lint.
PHP will, by default, claim that anything it outputs is HTML. While your use of getJSON will tell jQuery to ignore that and parse it as JSON anyway, best practise would be to include header("Content-Type: application/json");.
Best practise would also be to generate all your JSON using json_encode instead of wrapping {"users": and } around it with string concatenation.

Related

Pulling nested variable from json API

I'm trying to pull the highlighted variable from this API:
{
"timestamp":{
"total":1486424886,
"exchanges":{
"NEG":1486423855,
"MBT":1486424738,
"LOC":1486422237,
"FOX":1486424483,
"FLW":1486411044,
"B2U":1486424811,
"ARN":1486405596
}
},
"ticker_24h":{
"total":{
"last":**3011.8756088755**, // <---
"high":4073.32,
"low":2631.58,
...
http://api.bitvalor.com/v1/ticker.json
This is my code so far:
<html>
<script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
<table width="auto">
<tr><td>BTC/BRL (Bitvalor)</tr></td>
<tr><td>
<?php
$url1 = "http://api.bitvalor.com/v1/order_book_stats.json";
$fgc1 = file_get_contents($url1);
$json1 = json_decode($fgc1, true);
$price1 = $json1["ticker_24h.total.last"];
echo $price1;
?>
</tr></td>
</table>
</html>
What am I missing?
You access decoded JSON like an associative array:
$price1 = $json1['ticker_24h']['total']['last'];
Make sure you use an isset in case the format of data changes or the response is not what you expect.

How can I add a SQL result of a PHP statement (fromMySQL) in an existing HTML file

I have an html file that contains a table with table rows
<table style="width:auto">
<tr>
<td contenteditable="true"><select id="so"></select></td>
</tr>
</table>
I have a PHP that selects from mySQL DB and returns username
if ($results->num_rows > 0) {
// output data of each row
while($row = $results->fetch_assoc()) {
$name=$row["first_name"];
echo "<option>
$name
</option>";
}
} else {
echo "0 results";
}
I am trying to incorporate the result of the php into my index.html file within the table so that the option shows up in the table
How can I get the data from PHP into an already built html table row?
Any help would be appreciated.
Two way to get the job done:-
1)Use a class, that is you should, and using its object you can retrieve the data and use it on the webpage .
ex:- see this class, it needs a lot of improvements and changes, but still can give you some idea . I am also trying to learn PDO well, not a PRO, but can be helpful to you.Comments on this class will help you get the idea .
2)Using AJAX, You can request for this data on loading the document or you can request it via get, post, request.. on any event.If you know ajax, you can use that class and ajax, or if you do not have an idea about AJAX, you can get a lot of resources to learn ajax. after this if you need my assistant, I will try to help you.
for this work you should use ajax to load data in html file ...
you can do it with javascript :
create a function for load your php file :
function loadAjax(address,elementId) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById(elementId).innerHTML = xhttp.responseText;
}
}
xhttp.open("GET", address, true);
xhttp.send();
}
after create it you can use it when you want (for example after load of page). you should pass address of your php file and id of html element that you want the answer load into it .
for more learn :
http://www.w3schools.com/ajax/
There are couple of methods that can be used here. If the HTML and PHP are in the same file you could do this:
<?php
if ($results->num_rows > 0) {
$options = ''; // declare the variable to hold the options
// output data of each row
while($row = $results->fetch_assoc()) {
$name=$row["first_name"];
$options .= "<option>$name</option>"; // add the options to the variable
}
} else {
$options = "0 results";
}
?>
And then add the $options to the HTML:
<table style="width:auto">
<tr>
<td contenteditable="true">
<select id="so">
<?php echo $options; ?>
</select>
</td>
</tr>
</table>
Another option, though not as neat, is to embed the PHP in the HTML:
<table style="width:auto">
<tr>
<td contenteditable="true">
<select id="so">
<?php
if ($results->num_rows > 0) {
// output data of each row
while($row = $results->fetch_assoc()) {
$name=$row["first_name"];
echo "<option>
$name
</option>";
}
} else {
echo "0 results";
}
?>
</select>
</td>
</tr>
</table>
Yet another option would be to use AJAX to call the PHP from the HTML page and return the results to the right location. For instance, if you wanted to use jQuery you could follow a tutorial to learn the basics and then apply that to your code.

mikehaertl/phpwkhtmltopdf wrapper - Works when running PHP file from command line

I have made the following file:
test.php
<?php
require 'vendor/autoload.php';
use mikehaertl\wkhtmlto\Pdf;
$htmlString = <<<EOT
<!DOCTYPE html>
test
</html>
EOT;
$pdf = new Pdf($htmlString);
$pdf->setOptions(array(
'orientation' => 'landscape'
));
$pdf->saveAs('new.pdf');
?>
When I run from the command line (Ubuntu 12.x):
sudo php test.php
I get a file that shows up in my directory and works as intended. However now take the following file where I am trying to apply the above to a real world scenario - note: when I echo $htmlString I get a valid and expected string.
testPDF.php
<?php
// Start session and check if user is logged in
session_start();
if(!isset($_SESSION['permission']))
{
die('Please login.');
}
// Dependencies
require 'vendor/autoload.php';
use mikehaertl\wkhtmlto\Pdf;
require 'database.php';
// Initialize
$client = $db->real_escape_string($_GET['client']);
$start_date = $db->real_escape_string($_GET['start_date']);
$end_date = $db->real_escape_string($_GET['end_date']);
$jobs = array();
$htmlString = '';
// Get list of jobs from DB & save to array
$query = "SELECT somecolumns FROM mydatabase WHERE start_date > '{$start_date}' AND end_date < '{$end_date}' AND client = '{$client}'";
if(!$result = $db->query($query))
{
die('There was an error running the query [' . $db->error . ']');
}
while($r = mysqli_fetch_assoc($result))
{
$jobs[] = $r;
}
// Loop through jobs array and formulate HTML string
foreach($jobs as $value)
{
$id = $value['id'];
$name = $value['name'];
$tech = $value['tech'];
$time_closed = $value['time_closed'];
$time_total = $value['time_total'];
$time_charged = $value['time_charged'];
$description = $value['description'];
$htmlString = $htmlString . <<<EOT
<h4 style="text-align: center;">{$id} - {$name}</h5>
<table id="simple-table" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th style="width: 180px;">Date</th>
<th>Description</th>
<th style="width: 50px;">Duration</th>
<th style="width: 150px;">Time Charged</th>
<th style="width: 150px;">Technician</th>
</tr>
</thead>
<tbody id="jobs_start">
<tr>
<td>{$time_closed}</td>
<td>{$description}</td>
<td>{$time_total}</td>
<td>{$time_charged}</td>
<td>{$tech}</td>
</tr>
</tbody>
</table>
EOT;
}
$pdf = new Pdf($htmlString);
$pdf->setOptions(array(
'orientation' => 'landscape'
));
$pdf->saveAs('new.pdf');
?>
When I try to run the above by browsing to testPDF.php as a logged in user, I get nothing. No file is generated and no error/warning in the error logs. I've tried using $pdf->send() as well but no success.
My initial thought that this is a permissions issue, however I've tried setting testPDF.php to owner root and permission 755 but it still does not resolve the issue.
The issue is that when sending a HTML string to the pdf object, it looks for the tag to determine if it's html.
The first example has a HTML tag, while the 2nd file does not have any html tag thus is fails, silently.
https://github.com/mikehaertl/phpwkhtmltopdf/blob/master/src/Pdf.php

PHP autocomplete

I trying to fine tune an autocomplete text box. What I have here works (albeit a bit messy). But I would like to display the values available when clicking into the text box, then filter down as you type. Also, is there a simpler way to code this?
<?php
session_start();
if(isset($_SESSION['myusername'])) {
$User = $_SESSION['myusername'];}
$db1 = realpath('C:\AccessBackEnds\CETracker\CETracker.accdb');
$conn1 = odbc_connect("Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=$db1",'','') or die ("Unable to connect to server");
?>
<link rel="stylesheet" href="../datepicker/jquery-ui2.css" />
<script src="../datepicker/jquery-1.9.1.js"></script>
<script src="../datepicker/jquery-ui.js"></script>
<script>
$(function() {
var availableTasks = [
<?php
$info0 = "SELECT DISTINCT TaskName FROM CT:MyTasks WHERE UserName = '$User'";
$rs0=odbc_exec($conn1,$info0);
while($row = odbc_fetch_array($rs0)) {
$TaskName = "" . $row['TaskName'] . "";
echo '"';
echo $TaskName;
echo '", ';
}
?>""];
$( "#Tasks" ).autocomplete({
source: availableTasks
});
});
</script>
<div class="ui-widget">
<label for="Tasks">Tasks: </label>
<input name="tasks" id="Tasks" style="width: 400px">
</div>
I think you could enhance the readibility of your script if your split it in two files:
A frontend file, that one has HTML and JS code
A backend file, which has PHP code that generate JSON code.
The frontend file can call the backend file by a json invocation, take into account that the "Autocomplete" widget of jQuery UI has this functionlity built-in. Have a look here in "Remote JSONP Source".
Also PHP can easily generate JSON data by json_encode function.

How can I send JSON data from a PHP script to be used by jQuery?

I have a problem with some JSON data. I don't know how to take some data generated in PHP and turn that into something that I can use in my jQuery script. The functionality I need is this: I need to be able to click on images on the page, and depending on the selected element, I need to show results from my DB.
Here's the HTML page that I've got:
<html>
<head>
<title>pippo</title>
<script><!-- Link to the JS snippet below --></script>
</head>
<body>
Contact List:
<ul>
<li><a href="#">
<img src="contacts/pippo.png" onclick="javascript:change('pippo')"/>pippo
</a></li>
<li><a href="#">
<img src="contacts/pluto.png" onclick="javascript:change('pluto')"/>pluto
</a></li>
<li><a href="#">
<img src="contacts/topolino.png" onclick="javascript:change('topolino')"/>topolino
</a></li>
</ul>
</body>
</html>
Here's PHP code being called:
<?php
include('../dll/config.php');
$surname = $_POST['surname'];
$result = mysql_query("select * from profile Where surname='$surname'") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$_POST['name'] = ucfirst($row['name']);
$_POST['tel'] = $row['telephone'];
$_POST['companymail'] = $row['companymail'];
$_POST['mail'] = $row['email'];
$_POST['fbid'] = $row['facebook'];
}
?>
Here's the Ajax JavaScript code I'm using:
<script type="text/javascript">
function change(user) {
$.ajax({
type: "POST",
url: "chgcontact.php",
data: "surname="+user+"&name=&tel=&companymail=&mail=&fbid",
success: function(name,tel,companymail,mail,fbid){
alert(name);
}
});
return "";
}
</script>
Someone told me that this JS snippet would do what I want:
$.getJSON('chgcontact.php', function(user) {
var items = [name,surname,tel,companymail,email,facebook];
$.each(user, function(surname) {
items.push('surname="' + user + "'name='" + name + "'telephone='" + telephone + "'companymail='" + companymail + "'mail='" + mail + "'facebook='" + facebook);
});
/*
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
*/
});
But it is not clear to me - I don't understand how I need to use it or where I should include it in my code.
You will have to create a proper JSON string in your PHP script, and then echo that string at the end of the script.
A simple example:
$person = new stdClass;
$result = mysql_query("select * from profile Where surname='$surname'")
or die(mysql_error());
while ($row = mysql_fetch_array( $result )) {
$person->name = ucfirst($row['name']);
$person->tel = $row['telephone'];
$person->companymail = $row['companymail'];
$person->mail = $row['email'];
$person->fbid = $row['facebook'];
}
echo json_encode($person);
There are several problems with your code I have tried to explain via the corrected and commented code here:
HTML & JavaScript
<html>
<head><title>pippo</title>
<!-- added link to jQuery library -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<!-- javascript can go here -->
<script type="text/javascript">
$.ajax({
type: "POST",
url: "chgcontact.php",
// use javascript object instead of `get` string to represent data
data: {surname:user, name:'', tel:'', companymail:'', mail:'', fbid:''},
success: function(data){
// removed name,tel,companymail,mail,fbid
alert(JSON.parse(data));
}
});
return "";
}
</script>
</head>
<body>
Contact List:
<ul>
<!-- removed `javascript` form onclick handler -->
<li><img src="contacts/pippo.png" onclick="change('pippo')"/>pippo</li>
<li><img src="contacts/pluto.png" onclick="change('pluto')"/>pluto</li>
<li><img src="contacts/topolino.png" onclick="change('topolino')"/>topolino</li>
</ul>
</body>
</html>
PHP
<?php
$surname = $_POST['surname'];
$result = mysql_query("select * from profile Where surname='$surname'")
or die(mysql_error());
while ($row = mysql_fetch_array( $result )){
// create data object
$data = new stdClass();
// add values to data object
$data->name = ucfirst($row['name']);
$data->tel = $row['telephone'];
$data->companymail = $row['companymail'];
$data->mail = $row['email'];
$data->fbid = $row['facebook'];
// send header to ensure correct mime type
header("content-type: text/json");
// echo the json encoded data
echo json_encode($data);
}
?>
All code is untested, but you should be able to see what I have done at each step. Good luck.
And to expand on Brian Driscoll's answer. You will need to use the user.name format to access the name field from the returned $.getJSON("blah", function(user){});
so...
items.push('surname="'+user+"'name='"+user.name+"'telephone='"+user.telephone+"'companymail='"+user.companymail+"'email='"+user.email+"'facebook='"+user.facebook+);
In this format that you have created it will just push a long ugly looking string so you might want to spend some time making it look better. Good luck!
JSON that is POSTed to a PHP page generally isn't in the $_POST variable, rather it is in $HTTP_RAW_POST_DATA.

Categories