I've been stuck for quite some time on this problem now. I have looked around a lot but I can't seem to figure out the answer. See the link below for the reference on google developers.
https://developers.google.com/chart/interactive/docs/reference#dataparam
I have this PHP script which pulls data from my DB and then builds the JSON.
My code is as follows :
<?php
header('content-type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin:*');//Include this header to make the requests cross-origin
include 'dbconnect.php';//File for database connection
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Check if query GET parameters are defined
if(isset($_GET['date1']) && isset($_GET['date2'])){
$parm1=$_GET['date1'];
$parm2=$_GET['date2'];
//We build the metadata node of our json object with chart info / update time / chart title
//date_default_timezone_set('Etc/GMT+8');
//$date = date('Y-m-d H:i:s');
//$array['meta'][]=array('title'=>'Sales data for year'.$parm1.'-'.$parm2);
//$array['meta'][]=array('LastUpdated'=>$date);
//$array['meta'][]=array('Info'=>'This chart displays sales data on an annual basis');
$array['data']['cols'][]=array('label'=>'2008','type' => 'number');
$array['data']['cols'][]=array('label'=>'2009','type' => 'number');
}else{
echo "No data available";
}
$sql = "CALL TEST('$parm1','$parm2');";
//We run the query, store all rows in an associative array, then json_encode it
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$i = 0;
while($row = $result->fetch_row()) {
$array['data']['rows'][]= array(
'c' => array(
array('v'=>intval($row[$i]))
));
echo $row[1];
$i++;
}
}else {
echo "0 results";
}
//unset($array['data']['rows'][0]);
echo $_GET['callback'].'('.json_encode($array).')';
$conn->close();//We close the database connection here
?>
The json output from this php script is as follows :
{
data: {
cols: [{
label: "2008",
type: "number"
}, {
label: "2009",
type: "number"
}],
rows: [{
c: [{
v: 3016207
}]
}]
}
}
My first problem is that in the c node, only one value is added, when there should be two v:{object}. The accepted format afaik should be in my particular case, two v:{object} nested in the c:[array]. I have a strong feeling that json_encode() is failing to build a complex JSON, but I've thrown much tougher stuff to it in the past and it worked. Can anyone help me ? Please :o
EDIT : The expected json format is :
{
data: {
cols: [{
label: "2008",
type: "number"
}, {
label: "2009",
type: "number"
}],
rows: [{
c: [{v: 3016207 },{v: 3000528}]
}]
}
}
My query is returning these :
+---------+---------+
| 2008 | 2009 |
+---------+---------+
| 3016207 | 3000528 |
+---------+---------+
So basically the second column's value is not being inserted :/
Whoever came up with that JSON format should be fired. Looks like someone was trying on purpose to make things difficult.
But it's not hard to generate if you understand what the database function return values are and how to manipulate those arrays. For example: you were looping over your result set, even though it always has a single row, but you had no loop over the columns. Then you were trying to fill in your c element with a single value $row[$i] and wondering why it was only a single value. (I suspect you may be misunderstanding how the $var[] construct works.) Read up on these functions if you want to have success in this. You're still vulnerable to SQL injection attacks, by the way.
Anyway, this is obviously untested but should at least get you started.
$sql = "CALL TEST('$parm1','$parm2')";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
foreach ($row as $name=>$val) {
$array['data']['cols'][] = array('label'=>$name, 'type'=>'number');
$c[] = array("v"=>$val);
}
$array['data']['rows'] = array(array('c'=>$c));
} else {
echo "0 results";
}
Related
I have sent data from my php script using `json_encode' function.
if I console.log(resp) below is the O/P I get.
data: "{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC001","emp_name":"Akshay S. Shrivastav"}
{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC003","emp_name":"Aakash Shrivastav"}" status: "success"
however, if I console.log(resp.data) I get the below data
{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC001","emp_name":"Akshay S. Shrivastav"}{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC003","emp_name":"Aakash Shrivastav"}
Now I'm trying to display this data in the data tables for which I am using the below code.
$('#grpList').DataTable().row.add([
resp.data.dept_name,
resp.data.city_name,
resp.data.emp_id,
resp.data.emp_name
]).draw(false);
I'm receiving the following error
DataTables warning: table id=grpList - Requested unknown parameter '0' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
when I am single handed displaying only console.log(resp.data.dept_name) it says undefined
I'll be having multiple JSON response if the data increases, for now, I only have two. I'm not able to figure out how to display multiple data using a loop and appending it to the data table.
I'm using below php code to generate JSON
$jsonArray = "";
if($data->num_rows > 0)
{
while($row = $data->fetch_assoc())
{
$jsonArray .= json_encode(
array(
"dept_name" => $row['department_name'],
"city_name" => $row['city_name'],
"emp_id" => $row['emp_id'],
"emp_name" => $row['name']
));
}
echo json_encode(array("data" => $jsonArray, "status" => 'success'));
}
Because resp.data is an array of objects. You need to get the index first - let's say index 0, or the first object in the array:
$("#grpList").DataTable().row.add([
resp.data[0].dept_name,
resp.data[0].city_name,
resp.data[0].emp_id,
resp.data[0].emp_name
]).draw(false);
And if you want the second object:
$("#grpList").DataTable().row.add([
resp.data[1].dept_name,
resp.data[1].city_name,
resp.data[1].emp_id,
resp.data[1].emp_name
]).draw(false);
Of course, row.add() accepts an array argument as well - so this would work too:
$("#grpList").DataTable().row.add(resp.data).draw(false);
The issue is on server side.
You define $jsonArray as a string ! That's wrong.
Try this instead:
$jsonArray = []; // An ARRAY here!
if($data->num_rows > 0)
{
while($row = $data->fetch_assoc())
{
array_push($jsonArray, json_encode( // Use array_push here
array(
"dept_name" => $row['department_name'],
"city_name" => $row['city_name'],
"emp_id" => $row['emp_id'],
"emp_name" => $row['name']
));
}
echo json_encode(array("data" => $jsonArray, "status" => 'success'));
}
EDIT
I don't if the above works... Since I did not test it.
But here's how I would have writen it (I guess you'll have more chances with it):
$jsonArray = [];
if($data->num_rows > 0) {
while($row = $data->fetch_assoc()) {
// A temp array to rename the one of the keys...
$tempArray = [];
$tempArray = ["dept_name"] = $row['department_name'];
$tempArray = ["city_name"] = $row['city_name'];
$tempArray = ["emp_id"] = $row['emp_id'];
$tempArray = ["emp_name"] = $row['name'];
// Push to the jsonArray now...
array_push($jsonArray,$tempArray);
}
// And finally the result array... To be json encoded
$result = [];
$result = ["status"] = "success";
$result = ["data"] = jsonArray;
echo json_encode($result);
}
Note that without renaming one key and if there's only 4 data per rows from the DB... You could have done array_push($jsonArray,$row); directly, without using the $tempArray.
So try this... AND then apply Jack's answer. ;)
I wrote some code a while back to retrieve a player's saved score when they logged into the website. It used AJAX, and looked a little something like this:
Javascript:
function getHighScore(user){
$.get("getScore.php?userName="+user,function(data){
console.log(data);
output = data;
});
}
PHP:
<?php
$username = strval($_GET['userName']);
$con = mysqli_connect('localhost','XXXX','XXXX','XXXX');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
} else {
$sql="SELECT * FROM users WHERE username = '".$username."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$wealth = $row['wealth'];
echo $wealth;
}
}
mysqli_close($con);
//return $wealth;
?>
I was faced with the fact today that I would have to grab a whole bunch of data from a database, so I had a look at the old high score code I wrote. I'll attach a screenshot of what the table looks like that I will be retrieving info from. Anyway, I need to grab info from 6 columns and 10 rows. I need to assign a PHP variable to the data from P1, P2, P3 etc on MON1; P1, P2, P3 etc on TUE1; so on and so forth until we reach P6 on FRI2. I'm really quite new to PHP, so what would be the best way to go around doing this?
I apologise if I worded the question strangely. Feel free to ask if you didn't understand something.
Thank you!
PS: Ignore the P#_WORK columns. I don't need to refer to them right now
https://ibb.co/gq8u5a
I'd suggest you use an object to store everything, using the "day" column as key, and as value the P* columns in another. Here's some code you can use right away:
<?php
$con = mysqli_connect('localhost','XXXX','XXXX','XXXX');
if(!$con) exit('Could not connect: ' . mysqli_error($con));
$username = $_GET['userName'];
$sql = "SELECT * FROM TABLE WHERE username = '%s'";
$results = $con->query(sprintf($sql, $con->escape_string($username))); // Always escape parameters to prevent SQL injection attacks
$data = new stdClass; // An empty object
while($result = $results->fetch_object()){
$day = $result->day; // Use the day as the key of the object
$data->{$day} = $result;
}
// Now we output the results below by accesing the data in a chain-like fashion by accesing the "data" object
echo $data->MON1->P1 . '<br>'; // will output "Geo E"
echo $data->FRI1->P4 . '<br>'; // will output "Maths"
echo $data->THU2->P6 . '<br>'; // will output "DT"
Be sure to replace "TABLE" in the SQL query with the actual table name, as that wasn't visible in the screenshot you attached.
I have a MySQL database ($database) set up, with a table ("gigdata") and column names as follows:
id
clientname
day
month
year
postcode
status
entered
Each column name has a few rows of test data under it. I have successfully connected to the database using PHP's mysqli class, as below.
So far, I have written this PHP:
//Connect to database
$conn = new mysqli(localhost, $username, $password, $database);
//Check connection
if ($conn->connect_error) {
die("Failed to connect to MySQL: " . $conn->connect_error);
}
echo "<p>Connected to database</p>";
//Select data from database
$sql = "SELECT id, clientname, day, month, year, postcode, status, entered FROM gigdata";
$result = mysqli_query($conn, $sql);
//Create an empty array
$gigarray = array();
//Check data exists, if YES store in array
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
foreach ($row as $r) {
array_push($gigarray, $r);
}
}
} else {
echo "0 results";
}
I'm then echoing the JSON string into Javascript, which works fine:
var gigdata = <?php echo json_encode($gigarray) ?>;
QUESTION
My aim is to adapt the original PHP so that the JSON ends up formatted such that:
each database row is a new array element
each database column name is the name in each JSON name/value pair
each database field is the value in each JSON name/value pair
Hope this makes sense, and thanks a lot in advance.
There's actually a very helpful mysqli function for getting all data from a result, exactly how you want it - mysqli_fetch_all
Try:
json_encode(mysqli_fetch_all($result, MYSQLI_ASSOC));
I am using this jQuery plugin: jQuery - Multiple Tag Select.
Visit the site to see the plugin.
In this plugin, when you enter a name, like, I want to tag "MARCH", I will just type "Mar", a help will appear with some detail and image.
Click to see.
The dropdown appear comes from an array like this:
$response = array(
array(
'id' => '1',
'name' => 'Hamza',
'email' => 'Minfo#mhk.me',
'picture_path' => 'assets/img/avatar2.jpg'
),
array(
'id' => '2',
'name' => 'Jackqueline Andre',
'email' => '8461493908',
'picture_path' => 'assets/img/avatar2.jpg'
)
};
Now I want to get this array fetch from database like.
My DB-Details:
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql = "SELECT * FROM author";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
Now I don't know how can I fetch data from the server like above give, can anyone help me?
If you want only one to in $row array then use
$row = mysqli_fetch_assoc($result);
If you want to get all the records to be fetched from the result then
$output = mysqli_fetch_all($result);
this will make it an array with multiple records as arrays
if you want to use a loop to fetch records one by one then while loop is very easy
while($row = mysqli_fetch_assco($result)){
//do your coding here...
}
Note: fetch_assoc will make it an associative array, var_dump($row) will give full variable details such as type of variable and data inside it.
I am currently making an auto-complete form. Right now, the values of suggestions are from inside a JavaScript list:
<script type="text/javascript">
$('#textarea').textext({
plugins : 'autocomplete suggestions tags filter',
suggestions: [
'Basic',
'Cobol',
'Go'
]
});
I am using a function to get my list of names from a database:
$users->selectFirstnameSurname();
$userQueryResult = $users->queryResult;
$listOfNames = $users->listOfNames;
I am taking the values by appending firstname and lastname from the database, like this:
public function selectFirstnameSurname() {
$query = $this->db->prepare("SELECT * FROM `users` ORDER BY `username`");
$listOfNames[] = '';
try{
$query->execute();
foreach ($query as $row) {
array_push ($listOfNames, $row['firstname'].' '.$row['lastname']);
}
$this->queryResult = $query->fetch();
$this->listOfNames = $listOfNames;
} catch(PDOException $e){
die($e->getMessage());
}
}
What I want to do is get the values of array $listOfNames and replace the suggestions from the script.
You need to have a way to deliver the dataset so that your javascript code can access it. If your dataset is static and JS does the filtering, you could just statically dump them as a JS Object (JSON) like
[
{
"id": 1,
"label": "user name"
},
{
"id": 2,
"label": "other user"
}
]
The exact format of the JSON of course depends on your autocomplete implementation.
Or to make it more dynamic (good idea if you have a big dataset) you could make a simple API called over AJAX to fetch the data. If you need more detail, you can refer a tutorial like http://www.pontikis.net/blog/jquery-ui-autocomplete-step-by-step