Load mysql data to Highcharts line chart using JSON - php

I'm trying to import my data from a database to a line chart (Highcharts). My code doesn't work.
Here is my PHP code:
<?php
require('../php/config.php');
$con=mysqli_connect("localhost", "root", "ginnastica", "progetto");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_GET['src']))
{
$records=array();
$records = select($mysqli,"SELECT Sesso AS name, Occupati AS data FROM occupazione WHERE Sesso='totale' AND Periodo LIKE '%2008'");
$rows = array();
$rows['name'] = 'Totale';
while($r = mysql_fetch_assoc($records)) {
$rows['data'][]=$r['data'];
}
return json_encode($rows);
}
else
return json_encode(array('status' => 'error', 'details' => 'no src provided'));
}
?>
It seems that "mysql_fetch_assoc" doesn't work. The output of my array $rows id that:
{
"name": "Totale"
}
There isn't an element called "data".
What am I doing wrong?

At first:
It would be worth to see what is in your ../php/config.php file, because the content of that file may impact the behavior of other lines you provided.
The structure and data (at least few lines of data) of occupazione table is also worth to see, because data or structure could change the output as well.
You are missing a { after the else, - as #Moppo already mentioned.
Warning on mysql_fetch_assoc
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Read more in php.net
After that and some more fixes I would finally write your code in the way close to that:
<?php
$con = mysqli_connect("localhost", "root", "ginnastica", "progetto");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_GET['src'])) {
$records = $con->query("SELECT Sesso AS name, Occupati AS data FROM occupazione WHERE Sesso='totale' AND Periodo LIKE '%2008'");
$rows = array();
$rows['name'] = 'Totale';
while ($r = $records->fetch_assoc()) {
$rows['data'][] = $r['data'];
}
return json_encode($rows, JSON_NUMERIC_CHECK);
} else {
return json_encode(array('status' => 'error', 'details' => 'no src provided'));
}
As I said, we know nothing about database you work with, so my guess would be that your select returns no lines as a result. And then you got no data (only {"name": "Totale"}), just because while has nothing to iterate throw.

Related

Checking to see if ID is already in database, if it is don't INSERT it again

When I run the page with an empty database, it will insert the data correctly. When I run the page again, it displays there is already an ID in the database, but it inserts it anyway. Not sure how or why but I've tried every combination of booleans inside the if statements and cant get it to chooch correctly.
//pass in an ID to compare:
function checkOrderID($orderID) {
//Connect to the database:
$mysqli = new mysqli("localhost", "root", "", "price");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//Ask the database for some sweet, sweet data:
$stmt1 = "SELECT orderID FROM orders";
$result = $mysqli->query($stmt1);
//flag (we want to believe that there are no similar IDS so lets make it true):
$flag = true;
//while we got some data, display that shit
while ($row = $result->fetch_assoc()) {
//asign data to variable:
$rowOrderID = $row['orderID'];
//Does it match? if it does set the flag to false so it doesnt get inserted.
if ($rowOrderID == $orderID) {
echo "Row ID" . $row["orderID"] . " Passed ID: " . $orderID . "<br>";
echo "This order is already in the database" . "<br>";
$flag = false;
}
}
//hand the flag over to who ever needs it
return flag;
}
.
if (checkOrderID($orderID) == true) {
//some mysql insert logic here
}
Why are you making this complicated. just do something like this:
$con=mysqli_connect("localhost","root","","price");
$check_query = mysqli_query($con,"SELECT * FROM orders WHERE orderID = $orderID");
if (mysqli_num_rows($check_query) == 0) {
//mysql insert logic here
}
(Noted of course you are going to have your connection logic as well)
Note: You are using Mysqli in object oriented manner but in this example i have not used object oriented manner of DB connection. The connection variable $con must be passed to mysqli_query() method.
Also... random side note, but it's generally a good idea to have a password for your root mysql user.
Here better and short, but please try to use DB connection globally not inside your mothod and try to use prepared statements. But except those you can use following code.
//pass in an ID to compare:
function checkOrderID($orderID) {
//Connect to the database: I suggest use global DB connection
$mysqli = new mysqli("localhost", "root", "", "price");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//gets recodrs based on $orderID passed to this method
$stmt1 = "SELECT * FROM orders where orderID=$orderID"; //Try to use prepared statement
$result = $mysqli->query($stmt1);
//Store number of rows found
$row_count = $result->num_rows;
if($row_count>0){
return true;
}
else{
return false;
}
}

PHP : 'json_encode' from Database not showing any values

It's not a duplicate question about UTF-8 Unicode.
I am new to php and I am trying to create a json response.
I added data into my database properly as follows.
Then I tried to connect to DB and i did it successfully .
but after that when I tried to create a json response by using the following code, it doesn't shows any json response .
My PHP code is :
<?php
define('HOST','localhost');
define('USER','root');
define('PASS','qwerty');
define('DB','carol');
$con = mysqli_connect(HOST,USER,PASS,DB);
if (!$con)
{
echo "Please try later..";
}
else
{
echo "DB Connected..";
}
$sql = "SELECT * from songs";
$res = mysqli_query($con,$sql);
if (!$res)
{
echo "query failed..";
}
else
{
echo "Query success..";
echo (mysqli_num_rows($res));
}
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('title'=>$row[0]),
array('url'=>$row[1]),
array('lyrics'=>$row[2])
);
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>
I'm getting only echo of DB Connected , Query Success and 14 (no of rows)
I'm trying PHP for the first time by using some online tutuorials.
if I did any mistake in my code,please help me to find my mistake.
Thank you in advance.
After I added echo var_dump($res);
I got

JSON returns [null,null] in my app

I want to send database records with a PHPH file via json to my app I am making with IntelXDK. Because I can't use PHP code with the Intel XDK, I needed to use JSON. I want to show the two records 'quote' and 'author' from my 'quotes' table on my screen. Someone helped me to this code but it just returns [null,null]instead of the two records I need.. I tried debugging but I am new to PHP so I can'get it to work.. Anyone who can help or sees an error in this code? Thanks!
PS: Yes I now there are already multiple questions asked on this subject by other people. I have read them all but none of them solves my question..
<?php
if(isset($_GET["get_rows"]))
{
//checks the format client wants
if($_GET["get_rows"] == "json")
{
$link = mysqli_connect("localhost", "xxxxx", "xxxxx", "xxxx");
/* check connection */
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
header("HTTP/1.0 500 Internal Server Error");
exit();
}
$query = "SELECT quote, author FROM quotes WHERE id = " . date('d');
$jsonData = array();
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
$row = $result->fetch_assoc($result);
// Create a new array and assign the column values to it
// You can either turn an associative array or basic array
$ret= array();
$ret[] = $row['quote'];
$ret[] = $row['author'];
//encode to JSON format
echo json_encode($ret);
}
else {
echo json_encode($ret);
}
/* close connection */
mysqli_close($link);
}
else
{
header("HTTP/1.0 404 Not Found");
}
}
else
{
header("HTTP/1.0 404 Not Found");
}
?>
You have a bug in fetch_assoc() function call - remove $result parameter. If you had error reporting enabling, you should see:
Warning: mysqli_result::fetch_assoc() expects exactly 0 parameters, 1 given
Just change it to:
$row = $result->fetch_assoc();
In javascript to parse this response, just do this:
var obj = JSON.parse(xmlhttp.responseText);
document.getElementById("quote").innerHTML = obj[0];
document.getElementById("author").innerHTML = obj[1];
I think your problem is with fetch_assoc()
Try to use that :
$row = mysqli_fetch_assoc($result);
instead of
$row = $result->fetch_assoc($result);
It's works for me with your example
change this
$row = $result->fetch_assoc($result);
to
$row = $result->fetch_assoc();
Just change it to:
$row = $result->fetch_assoc();
Updated:
response = JSON.parse(xmlhttp.responseText);
you can now access them independently as:
reponse.quote and response.author

empty response php sql json

i am developing a php server sending arrays response to Android client using JSON. Now i simply testing the php code but the result is empty. Please help!!
<?php
#Connect to Database
$con = mysqli_connect("localhost","root","", "leoonline");
#Check connection
if (mysqli_connect_errno()) {
echo 'Database connection error: ' . mysqli_connect_error();
exit();
}
//Check already exist account
$allaccount = mysqli_query($con, "SELECT * FROM usersacc");
$results = array();
while($row = mysqli_fetch_array($allaccount))
{
$results[] = array(
'id' => base64_decode($row['id']),
'phone' => $row['phone'],
'password'> $row['password']
);
}
$json = json_encode($results);
?>
Is this your final code? You are not outputting anything apart from the connection error message if it happens.
Change
$json = json_encode($results);
to
echo json_encode($results);
If its still blank, then it could be a db data problem.

MySQLi returns an object but won't return results in foreach loop

I have a basic MySQLi query that is returning a MySQLi object and looping through it in a foreach(); to display a dump of data from my db. When I test it locally running PHP 5.5.9 everything is fine but when I put it on my remote production server running PHP 5.3.3 it will return the object in a var_dump but it will not loop through the results and display them.
Here is the code:
if ($mysqli->connect_errno) {
echo "There was an error";
} else {
if ($result = $mysqli->query("SELECT * FROM acronyms")) {
}
else {
echo "query error";
}
foreach($result as $x=>$y) {
echo $y["definition"];
}
}
?>
It appears that mysqli is installed on my production server but just won't loop in an identical file that have in my testing server.
I have also rewritten the query in regular MySQL and have been able to get the data out of the database.
MySQLi->query returns a MySQLi_result class on successfully retrieving a resultset.
Iterator support to MySQLi_result was only added in PHP 5.4, if your version of PHP is earlier than that you will need to traverse these results in the traditional way using fetch_assoc:
while($y = $result->fetch_assoc()) {
echo $y["definition"];
}
You need to actually do something with the results like use fetch_assoc() to interate through the results.
$mysqli = new mysqli("localhost", "name", "pw", "db");
if ($mysqli->connect_errno) {
echo "There was an error";
}
else {
if ($result = $mysqli->query("SELECT * FROM acronyms")) {
}
else {
echo "query error";
}
while ($row = $result->fetch_assoc()) {
echo $row["definition"];
}
}
Note the while ($row = $result->fetch_assoc()) { which is a fairly standard method used to roll through MySQLi results like this.

Categories