Highstock mysql json compare multiple series - mysql

Please help to create a query!
This is a working example of my query Retrieve data as JSON using PHP:
<?php
$con = mysql_connect("localhost","user","password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("admin_accounting", $con);
$result = mysql_query("SELECT unix_timestamp(date), sum(ksi2k) FROM accounting where lhc_vo like 'ops' group by year(date), month(date)");
$rows = array();
$rows['type'] = 'area';
$rows['name'] = 'Ops';
while($r = mysql_fetch_array($result)) {
$rows['data'][] = $r[0]*1000;
$rows['data'][] = $r[1];
array_push($rows);
}
print json_encode($rows, JSON_NUMERIC_CHECK);
mysql_close($con);
?>
The JSON results look like this:
{"type":"area","name":"Ops","data":[1167664515000,0,1170342915000,0,1172762115000,0,1175436915000,0,1178028915000,0]}
But I need the JSON results should look like this:
{"type":"area","name":"Ops","data":[[1167664515000,0],[1170342915000,0],[1172762115000,0],[1175436915000,0],[1178028915000,0]]}
I would be very grateful for the help

while($r = mysql_fetch_array($result)) {
$rows['data'][] = array($r[0]*1000, $r[1]);
}

In addition to my other answer, you ought to consider switching away from the ancient (and now deprecated, as of PHP v5.5) ext/mysql. Here is an example using PDO, in which you can see how simple your problem becomes:
<?php
$con = new PDO(
'mysql:hostname=localhost;dbname=admin_accounting',
'user',
'password'
);
$result = $con->query('
SELECT 1000*UNIX_TIMESTAMP(date), SUM(ksi2k)
FROM accounting
WHERE lhc_vo LIKE "ops"
GROUP BY YEAR(date), MONTH(date)
');
print json_encode([
'type' => 'area',
'name' => 'Ops',
'data' => $result->fetchAll(PDO::FETCH_NUM)
]);
?>
Note that:
I have moved the multiplication into the database layer in order that I can simply call fetchAll() to obtain the resulting array;
MySQL will select an indeterminate value from amongst those in each group for the first column in the resultset; should this be undesirable, you will need to apply a suitable aggregate function to the reference to the date column; and
I have used the short array syntax, which is only available from PHP v5.4—if you're using an earlier version, you will need to replace the [ … ] of the argument to json_encode() with array( … ).

Related

Sql to JSON/XML [duplicate]

I am trying to export my MySQL tables from my database to a JSON file, so I can list them in an array.
I can create files with this code no problem:
$sql=mysql_query("select * from food_breakfast");
while($row=mysql_fetch_assoc($sql))
{
$ID=$row['ID'];
$Consumption=$row['Consumption'];
$Subline=$row['Subline'];
$Price=$row['Price'];
$visible=$row['visible'];
$posts[] = array('ID'=> $ID, 'Consumption'=> $Consumption, 'Subline'=> $Subline, 'Price'=> $Price, 'visible'=> $visible);
}
$response['posts'] = $posts;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
Now this reads a table and draws it's info from the fields inside it.
I would like to know if it is possible to make a JSON file with the names of the tables, so one level higher in the hierarchy.
I have part of the code:
$showtablequery = "
SHOW TABLES
FROM
[database]
LIKE
'%food_%'
";
$sql=mysql_query($showtablequery);
while($row=mysql_fetch_array($sql))
{
$tablename = $row[0];
$posts[] = array('tablename'=> $tablename);
}
$response['posts'] = $posts;
But now i am stuck in the last line where is says: $ID=$row['ID']; This relates to the info inside the Table and I do not know what to put here.
Also as you can see, I need to filter the Tables to only list the tables starting with food_ and drinks_
Any help is greatly appreciated:-)
There is no 'table id' in MySQL and therefore the result set from SHOW TABLES has no index id. The only index in the resultset is named 'Tables_in_DATABASENAME'.
Also you should use the mysqli library as the good old mysql library is depreacted. Having prepared an example:
<?php
$mysqli = new mysqli(
'yourserver',
'yourusername',
'yourpassword',
'yourdatabasename'
);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") "
. $mysqli->connect_error;
}
$result = $mysqli->query('SHOW TABLES FROM `yourdatabasename` LIKE \'%food_%\'');
if(!$result) {
die('Database error: ' . $mysqli->error);
}
$posts = array();
// use fetch_array instead of fetch_assoc as the column
while($row = $result->fetch_array()) {
$tablename = $row[0];
$posts []= array (
'tablename' => $tablename
);
}
var_dump($posts);

Wordpress MySQL result resource is not valid

I have wp_places custom table and I am getting this when I am printing array:
[0] => stdClass Object
(
[home_location] => 24
)
[1] => stdClass Object
(
[home_location] => 29
)
Now I want to implode value like this way (24,29) but in my code I am getting this error:
<b>Warning</b>: mysql_fetch_array(): supplied argument is not a valid MySQL result resource
My Code
$getGroupType = $_POST['parent_category'];
$result = $wpdb->get_results( "SELECT home_location FROM wp_places WHERE blood_group LIKE '".$getGroupType."%'" );
$bgroup = Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$bgroup[] = implode(',',$row);
}
echo implode(',',$bgroup);
Any ideas or suggestions? Thanks.
$wpdb->get_results() already do the fetching for you, you don't need to call mysql_fetch_array
Given what you want to do, your code should look like this :
$getGroupType = $_POST['parent_category'];
$result = $wpdb->get_results( "SELECT home_location FROM wp_places WHERE blood_group LIKE '".$getGroupType."%'" );
$bgroup = Array();
foreach ($result as $location) {
$bgroup[] = $location->home_location;
}
echo '('.implode(',',$bgroup).')';
It's an PHP object that contains results, it isn't a MySQL Result.
Looking at the docs, it should be used like
foreach ($result as $row) {
$bgroup[] = $row->home_location;
}
echo implode(',',$bgroup)

Mysql UPDATE syntax, how to use as array

I'm having trouble understanding the documentation for the UPDATE command of MYSQL. I am viewing records in a PHP page from the database and I want to edit them.
To INSERT I have this code which is an array. I want to know if I can do the same with the UPDATE statement, to save me lots of this=$this 's.
Insert
mysql_query("INSERT INTO $tbl_name(title, pbDate, summary, blog) VALUES('$title', 'pbDate', '$summary', '$blog')")or die(mysql_error());
Update
mysql_query("UPDATE $tbl_name SET title='$title', pbDate='$pbDate' summary='$summary' blog='$blog' WHERE id='$id'")
I thinking something like this, but I'm not sure and can't find anything in the manual.
mysql_query("UPDATE $tbl_name SET (title, pbDate, summary, blog) VALUES('$title', 'pbDate', '$summary', '$blog') WHERE id='$id'")
You could use an array ...
Working phpFiddle:
http://phpfiddle.org/main/code/pi9-ckh
<?php
$array = array(
"column" => "some_value",
"title" => "some_title",
);
$setString = '';
foreach($array as $key => $value){
$tempArray[] = $key . ' = ' . "\"" . $value . "\"";
}
$setString = implode(",", $tempArray);
echo $setString;
?>

Drupal querying database table

I am a newbie in Drupal, I have a table in a drupal database. I wanted to query all the content of it and display in a tabular format. Whenever I execute the query the link directs me to the blank page and nothing appears. I have attached the PhP code for the reference. Any help will be highly appreciated.
<?php
$header = array('Name', 'Age', 'Sex','University');
$rows = array();
$sql = 'SELECT Name, Age, Sex,University FROM {data_pulling} ORDER BY Name';
$res = db_query($sql);
while ($row = db_fetch_array($res)) {
$rows[] = $row;
}
print theme('table', $header, $rows);
?>
At a guess you're using Drupal 7 but are trying to use API functions from Drupal 6.
Try this
foreach ($res as $row) {
$rows[] = (array) $row;
}
print theme('table', array('rows' => $rows, 'header' => $header));
Have a look at the docs for db_query and theme_table for more information

How to use agregate Mysql functions with CakePHP

There is a way to use agregate functions with cakephp? like sum() or avg() with find() method.
UPDATE:
I missed a line in the book
array('fields'=>array('Product.type','MIN(Product.price) as price'), 'group' => 'Product.type');
Showing the basic structure for doing that.
Thanks for the help
In the fields parameter of a find method call, you may pass the field processed by an aggregated function. Example:
$Model->find('all',
array(
'anything' => array(/* */),
'fields' => array(
'SUM (Model.attribute) AS total',
'OTHERFUNCTION(OModel.other_attribute) AS other'
),
'otherthing' => array(/* */)
)
);
In exactly the same way, since CakePHP is just a PHP framework.
<?php
// Make a MySQL Connection
$query = "SELECT type, SUM(price) FROM products GROUP BY type";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)){
echo "Total ". $row['type']. " = $". $row['SUM(price)'];
echo "<br />";
}
?>