Parsing MySQL to JSON array, with data manipulation in PHP - php

I'm tring to parse a MySQL request to a JSON file, with this PHP function,
<?php
//Define possible Argument request
$format = $_GET['format'];
if($format=='json') {
header("Content-type: text/json");
}
//Define database credential
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
try {
//Open connection to mysql_db from defined Database credentials
$connection = mysqli_connect($servername, $username, $password, $dbname) or die ("Error " . mysqli_error($connection));
//Fetch table rows from mysql db
$sql = "SELECT TS, time1, time2, time3 FROM time ORDER BY TS";
$result = mysqli_query($connection, $sql) or die ("Error in Selecting " . mysqli_error($connection));
//Create an array
$series0 = array();
$series0['name'] = 'TS';
$series1 = array();
$series1['name'] = 'time1';
$series2 = array();
$series2['name'] = 'time2';
$series3 = array();
$series3['name'] = 'time3';
while($r = mysqli_fetch_array($result))
{
$series0['data'][] = $r['TS'];
$series1['data'][] = $r['time1'];
$series2['data'][] = $r['time2'];
$series3['data'][] = $r['timez3'];
}
$result = array();
array_push($result,$series0);
array_push($result,$series1);
array_push($result,$series2);
array_push($result,$series3);
print json_encode($result, JSON_NUMERIC_CHECK);
mysqli_close($connection);
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
Who gives me this JSON output:
[{
"name": "TS",
"data": ["00:08:31.227","00:09:02.434","00:09:38.573"]
},{
"name":"time1",
"data":["00:05:11.220","00:05:05.420","00:03:32.540"]
},{
"name":"time2",
"data":["00:04:11.820","00:08:05.660","00:01:24.330"]
},{
"name":"time3",
"data":["00:02:11.990","00:09:05.570","00:15:25.200"]
}]
Now the problem is that I have to convert the times from "HH:MM:SS.fff", to seconds (SS.fff), but trying to apply my conversion function I came to an error becouse I cant applay my formulas to an array, is there a way to intercept the data and manipulate it before they goes inside the array?
And a second minor problem, becouse the final array will get 100+ dataseries, is there a way to don't assign manually the name to the series, but give them the same name as the column of MySQL table from where they came from??
Thank for all the suggestions,
Best regards.

You can use mysql TIME_TO_SEC function.
mysql> SELECT TIME_TO_SEC('22:23:00');
-> 80580
mysql> SELECT TIME_TO_SEC('00:39:38');
-> 2378
so change
$sql = "SELECT TS, time1, time2, time3 FROM time ORDER BY TS";
to
$sql = "SELECT TS, TIME_TO_SEC(time1), TIME_TO_SEC(time2), TIME_TO_SEC(time3) FROM time ORDER BY TS";

Related

PHP - MySql SELECT WHERE value = string JSON

through a cURL connection, I can pick up data, from Json files, placed on a remote server. In particular, the codes of some products, which thanks to a foreach
foreach($data['results'] as $key=>$val){
$codici_hotel = $val['hotel_code'];
echo $codici_hotel.",";
}
I can see on video:
1074d0,19f726,1072ba,107104,183444,112438,15d8ab,1b326e,19d885,189b95,1071bf,107155,193e61,10aab2,138752,18dd7d,19d7f9,117b0d,1071b8,1398c4,107039,110851,107124,110669
Now I need to use that string to run a select on a local database, such as:
$sql = "SELECT * FROM hotels WHERE code = ('$codici_hotel')";
What is the correct sql string?
Thanks for your help
CODE UPDATE USED
$codici_hotel_arr = array();
foreach($data['results'] as $key=>$val){
$codici_hotel_arr[] = $val['hotel_code'];
}
$codici_hotel = "'".implode(",",$codici_hotel_arr)."'";
$conn2 = new mysqli($servername, $username, $password, $dbname);
if ($conn2->connect_error) {
die("Connection failed: " . $conn2->connect_error);
}
$sql2 = "SELECT name FROM hotels WHERE code IN ('$codici_hotel')";
$result2 = $conn2->query($sql2);
if ($result2->num_rows > 0) {
// output data of each row
while($row2 = $result2->fetch_assoc()) {
$nome_hotel = $row2["name"] ;
}
} else {
echo "0 results";
}
$conn2->close();
echo $nome_hotel;
You have to convert your all codes in string enclosed with '. Then use IN clause of mysql. change your code as below
$codici_hotel_arr = array();
foreach($data['results'] as $key=>$val){
$codici_hotel_arr[] = $val['hotel_code'];
}
$codici_hotel = "'".implode(",",$codici_hotel_arr)."'";
$sql = "SELECT * FROM hotels WHERE code IN ($codici_hotel)";

Adding parameters to an already working webservice

I have the following already working great, but would like to add a parameter as this returns the whole data set.
<?php
$mysql_db_hostname = "localhost";
$mysql_db_user = "00000";
$mysql_db_password = "00000";
$mysql_db_database = "000000";
$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 mns";
$result = mysqli_query($con, $sql);
while($obj = mysqli_fetch_object($result)) {
$var[] = $obj;
}
echo '{"mns":'.json_encode($var).'}';
?>
For clarification, I was hoping to add a parameter in the url that is passed through to the php so that I get specific records. For example, if there is a field called [Customer], I would like to pass a customer id to it.

php display mysql table from user input? in the part of Json Restful web services?

I am new to PHP.
I followed this to Display JSON data from Mysql Tables
Here I am getting one table as output at a time..
So,in this I want to display tables from user input.
like
www.google.com/myjson.php?/tablename
www.google.com/myjson.php?=tablename
Here is the code
<?php
//Create Database connection
$db = mysql_connect("localhost","root","root");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("test_json",$db);
//Replace * in the query with the column names.
$result = mysql_query("select * from employee", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['id_employee'] = $row['id_employee'];
$row_array['emp_name'] = $row['emp_name'];
$row_array['designation'] = $row['designation'];
$row_array['date_joined'] = $row['date_joined'];
$row_array['salary'] = $row['salary'];
$row_array['id_dept'] = $row['id_dept'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
//Close the database connection
fclose($db);
?>
Here its for the part of Table name of employee
so this should be like
www.google.com/myjson.php?/employee
please suggest me of this kind,because I have n number of tables to Display and I want to use them in the Android/iphone.
<?php
//Create Database connection
$db = mysql_connect("localhost","root","root");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("test_json",$db);
$tableNm = isset($_GET['tablename']) ? trim($_GET['tablename']) : '';
if($tableNm){
//Replace * in the query with the column names.
$result = mysql_query("select * from $tableNm", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
foreach($row as $key=>$val){
$row_array[$key] = $val;
}
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
}
//Close the database connection
mysql_close($db);
Assumes you have input url's in the below formats.
$url ="www.google.com/myjson.php?/tablename";
//or
$url ="www.google.com/myjson.php?=tablename";
You can parse it using parse_url and str_replace to retrieve the table name.
Then assign tablename into query and make it run.
$url = parse_url($url);
if ($url['query'] <> '') {
$table = str_replace(array("/","="),'',$url['query']);
}
//Create Database connection
$db = mysql_connect("localhost","root","root");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("test_json",$db);
//Replace * in the query with the column names.
$result = mysql_query("select * from $table", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
foreach($row as $key=>$val){
$row_array[$key] = $val;
}
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
//Close the database connection
mysql_close($db);
P.S. Usage of mysql_* functions is not recommended.
Instead you can use mysqli* or pdo* functions.

MySQL select using an array

I edit my code working good but still one problem ... the data that selected from my database and displayed in my suggestion input ( only one row and last ID ) !!! How can I do it to display all data rows from my database ????
<?php
$q = strtolower($_GET["q"]);
if (!$q) return;
$host = "localhost";
$user = "root";
$password = "";
$database = "private_message_system";
//make connection
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
$query = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($query)){
$items = array($row["user_name"] => $row["user_email"]);
}
$result = array();
foreach ($items as $key=>$value) {
if (strpos(strtolower($key), $q) !== false) {
array_push($result, array(
"name" => $key,
"to" => $value
));
}
}
echo json_encode($result);
?>
As I know mysql doesn't have a array type like postgres so you have to fetch it one by one:
// here is where you get your to connection to the database
$conn = mysql_connect("your IP", "username", "password");
mysql_select_db("mydb", $conn);
// here you have to do the select to retrieve data from the table.
$query = "SELECT `name`, `to` from mytable";
// now you got all the records but you still need to iterate over this result
$result = mysql_query($query, $conn);
$array = array();
// retrieve a record and append it to the array
while($record = mysql_fetch_assoc($result)):
$array[] = $record;
endwhile;
// please close the door....
mysql_close($conn);
echo json_encode($array);
See below for a basic implementation of connecting to MySQL and searching for your $q, I've left a few comments for you to make it clearer what's going on!
<?php
// Get the query term from the url
$q = strtolower($_GET["q"]);
// Do nothing if it's empty or not set
if (empty($q)) return;
// Result array which we are going to get from MySQL
$result= array();
// Make a SQL Connection
mysql_connect("localhost", "admin", "password") or die(mysql_error());
// Try to connect to your DATABASE (change the name) or throw an error
mysql_select_db("DATABASE") or die(mysql_error());
// Get data from the "email" table
// Where the name field is LIKE the search term
$result = mysql_query("SELECT * FROM email WHERE name LIKE '%".mysqli_real_escape_string($q)."%'")
or die(mysql_error()); //throw an error if something went wrong
//Read all the results ($row) in a loop and put them in the result array
while($row = mysql_fetch_array( $result )) {
$result[] = array('name' => $row['name'], 'to' => $row['to']);
}
// Output the array as JSON
echo json_encode($result);
?>
For the more PHP experienced I am aware you can get an array from MySQL but have left it like this to make it clearer.
Enable error reporting
ini_set('display_errors', 1);
error_reporting(E_ALL);

translator in php and mysql

ok i make this one but i have 83000 words in mysql database when i execute this script it will take too much time and some time it not runs. i think this script match every title in mysql database wather it is in the $row['full_story'] or not. so this make the opreation unusable if there is any method i can make this process faster ? or it just match those titles which are used $row['full_story'] code is below
$user_name = "root";
$password = "";
$database = "salar";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SET NAMES 'utf8'";
mysql_query($SQL);
$SQL = "SELECT * FROM dle_mylinks ORDER BY LENGTH( title ) DESC";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
$row['full_story'] = str_replace ($db_field['title'],"" . $db_field['title'] . "" ,$row['full_story']);
$row['short_story'] = str_replace ($db_field['title'],"" . $db_field['title'] . "" ,$row['short_story']);
}
$mydata =$row['short_story'] . $row['full_story'];
mysql_close($db_handle);
}
else {
print "Database NOT Found ";
mysql_close($db_handle);
}
You'll want to iterate through each row in the table in a loop.
Example:
$query = mysql_query("SELECT * FROM `table`");
while($row = mysql_fetch_object($query)){
$mydata = str_replace($row->word,$row->meaning,$mydata);
}
Be careful with str_replace, If you want to replace 'distance' per 'thistance' and after it, replaces 'this' by 'dis' you get 'distance' again (it's a word game, an aproximation to the issue)
Use preg_replace.
Create two arrays (zend framework fetchCol or your favorite lib)
$aWords = $zfDb->fetchCol('select words from table');
$aMeans = $zfDb->fetchCol('select means from table');
And
$mydata = preg_replace($aWords, $aMeans, $mydata);

Categories