HighChart for PHP 5.1 lower - javascript

I am new to PHP and Highchart. Currently, I am trying to:
1. Query my data from MySQL using PHP.
2. To display HighChart :: Javascript, get data from json_encode in PHP.
Problem now, my PHP is 5.1.6 (I have a few applications running since few years back, try not to upgrade the php). I cannot use the json_numeric_check.
Help Needed :
Question 1: is there any alternative way to get the value without json_numeric_check?
Question 2: Is there any package I can add in to php 5.1.6 to use json_numeric_check?
This is the code I want to use ::
print json_encode($result,json_numeric_check);
My Full Code
<?php
header("Content-Type:application/json");
include_once "shift.php";
list($s1,$e1,$shift) = shift_frame();
$servername = 'localhost';
$username = "";
$password = "";
$select = "SELECT EH_CELLNUM, COUNT(EH_SERIALID)";
$table = " FROM T_EEDATA";
$rule1 = " WHERE (EH_END_DT between ".$s1." and ".$e1.") group by EH_CELLNUM";
$conn = mysql_connect($servername,$username,$password) or die("Connection failed: " . mysqli_connect_error());
mysql_select_db("eedata",$conn) or die(mysql_error());
$sql = $select.$table.$rule1;
$query = mysql_query( $sql, $conn );
$category = array();
$category['name'] = 'Cellnum';
$series1 = array();
$series1['name'] = 'SerialID';
while($row = mysql_fetch_array($query)){
$category['data'][] = $row['EH_CELLNUM'];
$series1['data'][] = $row['COUNT(EH_SERIALID)'];
}
////////////code add here???/////////////////////////////
$result = array();
array_push($result,$category);
$result2 = array();
array_push($result,$series1);
print json_encode($result,json_numeric_check);
mysql_close($conn);
?>

you can do someting to $result before json_encode
for example:
$result = array("1", "2", "3", "4");
$result = array_str_to_int($result);
// only for simple array,you can optimize the code
function array_str_to_int($array){
$tmp_arr = array();
foreach( $array as $k => $v ){
$tmp_arr[] = intval($v);
}
return $tmp_arr;
}

Related

Build and send PHP Array to JS via Ajax

I want to build an array in PHP from SQL query and send it back via ajax to my JS file.
$id = clear(filter_input(INPUT_POST, 'id'));
$sql = 'SELECT * FROM `counties` WHERE `id`="'.$id.'"';
$query = mysqli_query($con, $sql);
$array = array();
while($result = mysqli_fetch_array($query)) {
$id = $result['id'];
$name = $result['name'];
$array[] = array('id' => $id, 'name' => $name);
}
echo json_encode($array);
This is my code. In response I have always just one element. There's a lot of more. How could i do that correctly? I was browsing whole Internet and I didn't find anything useful... :(
$id = $_POST['id'];
$query = mysqli_query($con, "SELECT id,name FROM `counties` WHERE `id`='$id'");
$array = mysqli_fetch_all($query,MYSQLI_ASSOC);
echo json_encode($array);
this may simplified code

PHP/MYSQL Query Print Results in HTML Form Field

Recently I have been assigned a group project for a college class and I will need to query a customers name from a database and then print out the rest of the row in form fields. I have the select menu working correctly and it will print to the form field. However, the problem occurring is the query results will only show the last row in the MYSQL table I selected. Any help here would be greatly appreciated. I have been spinning my wheels for a few days on this issue. I am only a beginner coder, so it might be a little messy.
Thanks,
Connection.PHP File
<?php
function Connect()
{
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "medley";
// Create connection
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname) or die($conn->connect_error);
return $conn;
}
?>
My Query Page
<?php
require 'connection.php';
$conn = Connect();
$sql = "SELECT * FROM cust_info";
$result = $conn->query($sql);
echo "<select id='firstName' name='firstname' onchange=populatesecondbox()>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['F_Name'] . "', '" . $row['L_Name'] . "'> " . $row['F_Name'] . " " . $row['L_Name'] . "</option>";
$pphone = $row['P_Phone'];
}
echo "</select>";
?>
<input id="secondinputbox" type="text" />
<script type="text/javascript">
function populatesecondbox(val) {
var dropdown = document.getElementById("firstName");
var pphone = document.getElementById("secondinputbox");
var secondfname = document.getElementById("thirdinputbox");
var str = "<?php echo $pphone ?>";
var sfname = "<?php echo $sfname ?>";
pphone.value = str;
secondfname.value = sfname;
}
</script>
​
Instead of using
$row = mysqli_fetch_array($result)
on line 10, use
$row = $result->fetch_assoc()
or
$row = $result->fetch_array()
The difference between fetch_assoc and fetch_array is that fetch_array contains both numeric indices and named indices. For example echo $row[0] will output as same as echo $row['id']. Whereas, fetch_assoc only contains named indices.
Based on the provided loop statement
$pphone = $row['P_Phone'];
$pphone is getting assigned to the last row on termination of the loop because each iteration is overriding $pphone with the current row until at which point in the loop $pphone gets the last value.
Instead of using
$pphone = $row['P_Phone'];
Try the following in the loop.
$pphone[] = $row['P_Phone'];
Your concatenated phones should be provided after the loop.
$pphones = "['".join("','" , $pphone)."']";
In your js script tag just get $pphones as a string;
var pphones = <?php echo $pphones; ?>;
ddl = document.getElementById('firstname');
pphone.value = pphones[ddl.selectedIndex];

Fetch data from database and send it to javascript function

I am selecting input values from the database and I want to send it to the javascript function addVal() so that I can retrieve this value. I do not want to use echo. It is not working right now and I don't know how I can make it work.
<h1>trial,</h1>
<div id ="val"> </div>
<?php
$name = $_POST['postname'];
$host = 'localhost';
$user = 'root';
$pass = 'root';
$db_name="big";
$conn = new mysqli($host, $user, $pass, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "connected";
$sql = "SELECT input FROM trial_db";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while( $row = $result->fetch_assoc()) {
$value = $row['input'];
addVal ($value);
}
}
?>
<script>
function addVal (value){
document.getElementById("val").innerHTML+= value ;
}
</script>
Calling js function from php will not work remove that code from php.
And change in js.
<script>
function addVal (){
var value = "<?php echo $value; ?>";
document.getElementById("val").innerHTML+= value ;
}
</script>
Will only work if js and php codes are in same php file.

Access DB from html file via custom PHP file

Right now I have working a DB connection to mysql. The html -> PHP -> query -> data reception works. I show the relevant code:
From the html file matters:
d3.json("http://path/file.php", function(error, data) {
console.log (data);
});
file.php:
<?php
$username = "myusername";
$password = "mypassword";
$host = "myhost";
$database="myDB";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "select * from `mytable`";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
What I want is to have only 1 .php file instead of 1 php file for every query. That means I need to send from the html a variable inputquery to the php file. I've tried several things such as changing:
`$myquery = "select * from `mytable`; into `$myquery = inputquery`;
And I think that the wrong point is the definition of the function that requests the data from the DB. What I tried (wrong, the following code does not work as expected):
var inputquery = "select * from `mytable`"
d3.json("http://serverhost/path/file.php", function(error, data) {
console.log (data);
});
Maybe this is not working because I am not telling the function I want as an input to the .php file the variable inputquery. I tried to put it inside the function, but got "data is not defined" errors, so I think it is not worth it to show the wrong code.
How can I input that var inputquery to the .php file? It could not be the way I planned it.
Thank you
You have to send the inputquery variable with the http request as POST data,
then in you php file you can do :
$myquery = $_POST['inputquery'];
You surely will find some documentation about sending post data with the request you're sending.
The simplest way is using get parameter in d3.json:
var yourparam = 'mytable';
d3.json("http://path/file.php?query=" + yourparam, function (error, json) {
...
});
You can retrieve the variable from the $_GET array.
Finally don't put mysql commmands into your js, and don't use mysql library. It's very dangerous.
This is a very bad idea, since you become very vulnerable to SQL Injection, even so I will try to help you
I assume you have JQuery if you have so
you can do the following
html.file
var inputquery = "select * from `mytable`";
$.post("relative/path/to/file.php",
{query : inputquery},
function (data) {
alert(data); // See output
},'json);
file.php
<?php
$username = "myusername";
$password = "mypassword";
$host = "myhost";
$database="myDB";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = $_POST['query'];
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>

json_encode a MySQL table and urldecode Each Row

Here's what I got. I have a MySQL table, in this case 'businesses' which has a many rows of urlencode() data. I am trying to use a php script (getTable.php) to grab the table urldecode() each row and then use a json_encode to send the data as an array back to javascript. Here's what i have so far.
$table = $_GET['table'];
$query = "SELECT * FROM $table";
$jsonOut = array();
while($result = mysql_fetch_array(mysql_query($query)))
{
foreach($result as &$value)
{
$value = urldecode($value);
}
$jsonOut[] = $result;
}
echo (json_encode($jsonOut));
Obviously, I'm doing something wrong because I'm causing an infinite loop and nothing ends up working. Any help wold be greatly appreciated.
Try this code:
$table = $_GET['table'];
$query = "SELECT * FROM $table";
$jsonOut = array();
$result = mysql_query($query);
while($result = mysql_fetch_array($result))
{
$jsonOut[] = $result;
}
echo (json_encode($jsonOut));
In fact the query has to be executed only once, not once for each iteration of the while loop, or else you'll end up with an infinite loop!
Also, as a side note, you should avoid using mysql_* functions as they're now deprecated, try to switch to PDO if you can.
EDIT:
If you need to urldecode each row, replace
$jsonOut[] = $result;
with
$jsonOut[] = array_map('urldecode', $result);
inside the while loop.
This is the infinite loop you're talking about
while($result = mysql_fetch_array(mysql_query($query)))
Try
$recordset=mysql_query($query);
while($result = mysql_fetch_array($recordset)){
}
Note: MySQL API is long deprecated, better move away from it before you are forced to
You should do like this:
$query = mysql_query($query);
while($result = mysql_fetch_array($query)) {
You could retrieve and decode your parameters with the following code. (Based on #Matteo Tassinari answer)
$table = $_GET['table'];
//This could be a SQL injection
$query = "SELECT * FROM " . mysql_real_escape_string($table);
$jsonOut = array();
$result = mysql_query($query);
while($result = mysql_fetch_array($result))
{
$newArray = array();
foreach ($result as $k => $v) {
$newArray[$k] = urldecode($v);
}
$jsonOut[] = $newArray;
}
echo (json_encode($jsonOut));

Categories