Access DB from html file via custom PHP file - javascript

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);
?>

Related

D3 javascript pulling data from mysql Uncaught typeError

Im currently getting my data from a mysql database using this php :
<?php
$username = "*****";
$password = "******";
$host = "localhost";
$database="db";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "
SELECT `this`, `that` FROM `table`
";
$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);
}
$fp = fopen('empdata.json', 'w');
fwrite($fp, json_encode($data));
fclose($fp);
mysql_close($server);
?>
I then run this html with the previous json file that I generated
d3.json("mypreviouslygeneratedjson.json", function (error, data) {
data.forEach(function (d)
{
...
}
...
It all goes well, I can generate bar charts, pie charts etc. But as soon as I replace the 3 fopen,fwrite and fclose lines with this line:
echo json_encode($data);
(plus I replace "mypreviouslygeneratedjson.json" with the php file that I mentioned before)
As soon as I try to do this, I get an error in the console:
Uncaught TypeError: Cannot read property 'forEach' of undefined
What is going on here? Im practically using the same json in both cases.
The problem was that the json generated by my php file included the following mysql warning in it :
Deprecated: mysql_connect(): The mysql extension is deprecated and
will be removed in the future: use mysqli or PDO instead
This resulted in filling my json file with html, making it unreadable by the d3.json

HighChart for PHP 5.1 lower

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;
}

Accessing MySQL database in d3.js with php file

I need some help with MySQL and D3 with a php file.
I am trying to get access to my database using D3. I have created a php file where I make the connection to MySQL.
My problem is however that I get an empty array when printing out my output to the console from D3. I can't seem to find what I am doing wrong. Below is my code for both the D3 call and the php file: (I have appropriate names from username, password and database name.)
<?php
$host = "localhost";
$port = 8889;
$username = "********";
$password = "********";
$database="***datebasename***";
if (!$server) {
die('Not connected : ' .mysql_error());
}
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
if (isset($_GET['type'])) {
$type = $_GET['type'];
} else {
$type = "null";
echo "Type not passed";
}
if($type=='load'){
$string = '';
$gene = $_GET["gene"];
$data = $_GET["data"];
$myquery = "select gene_data.gene_data from genes inner join gene_data on genes.id=gene_data.g_id where genes.name ='$gene' and genes.type='$data'";
$query = mysql_query($myquery);
if ( !$myquery || !$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);
}
?>
My file are all running from a server. The MySQL server is also on the same server, so I jut call localhost to get access. Also since I need several different parameters for my SQL calls I send the values from D3 ("gene" and "human").
The following the call I make from D3:
d3.json("getdata.php?type=load&gene=CLL5&data=human", function(error, data) {
console.log(data);
});
Also it is worth mentioning that my query is tested and works.
Some help would be greatly appreciated! Any ideas on how to debug with and prints or write.outs would be appretiated as well!

Does SJCL content need to be json_encode(d) when it is read from a database?

Overview
I am attempting to encrypt data, send it to a database, then decrypt the data using the Stanford Javascript Crypto Library (SJCL).
Problem
Whenever I attempt to call the data from the database, I get a "CORRUPT: ccm: tag doesn't match" error. I have looked this up and it seems as if my content or password is corrupted, and because the password is being straight from a textbox, I have narrowed it down to the content.
Code Snippet
(PHP)
$paste = $_GET['url'];
$query = "SELECT * FROM posts WHERE url='$paste'";
$result = mysqli_query($db, $query);
$row = mysqli_fetch_array($result);
$t = $row['title'];
$c = $row['content'];
$con = json_encode($c);
$e = $row['encode'];
$ca = $row['Catagory'];
$en = $row['encrypted'];
(Javascript) -Invokes SJCL-
<script type="text/javascript">
var content = <?php echo $con; ?>;
function decryptPaste() {
try {
sjcl.decrypt(document.getElementById("decrypt-pass").value, content)
} catch (e) {
alert("Can't decrypt: " + e);
}}
Any and all help appreciated, thanks in advance!

Should this file be loaded as a valid .js file?

I am trying to create a PHP file that the browser will see as a js file, and are using the content-type header. But there's something not working, even though. So my question is, should this be interpreted as a valid .js file?:
<?php
header('Content-Type: application/javascript');
$mysql_host = "localhost";
$mysql_database = "lalalala";
$mysql_user = "lalalalal";
$mysql_password = "lalalallaala";
if (!mysql_connect($mysql_host, $mysql_user, $mysql_password))
die("Can't connect to database");
if (!mysql_select_db($mysql_database))
die("Can't select database");
mysql_query("SET NAMES 'utf8'");
?>
jQuery(document).ready(function() {
var urlsFinal = [
<?php
$result = mysql_query("SELECT * FROM offer_data ORDER BY id_campo DESC");
while($nt = mysql_fetch_array($result)) {
?>
"<?php echo $nt['url']; ?>",
<?php
};
?>
"oiasdoiajsdoiasdoiasjdioajsiodjaosdjiaoi.com"
];
scriptLoaded();
});
In order for your Browser to see your PHP file like a .js file, echo or print the entire PHP page into a string, there will be no need to use any headers, just something like:
// First let's make a secure page called database.php - put in a restricted folder
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
// now let's go over a new technique you'll cherish in the future - page.php
<?php
include 'restricted/database.php'; $db = db();
if($db->connect_errort)die("Can't connect to database. Error:".$db->connect_errno);
$db->query("UPDATE tabelName SET names='utf8' WHERE column='value'");
$sel = $db->query('SELECT * FROM offer_data ORDER BY id_campo DESC');
if($sel->num_rows > 0){
while($nt = $db->fetch_object()){
$output[] = $nt->url;
}
}
else{
die('No records were returned.')
}
$sel->free(); $out = implode("', '", $output); $db->close();
echo "jQuery(document).ready(function(){
var urlsFinal = ['$out'];
// more jQuery here - you may want to escape some jQuery \$ symbols
}"
?>
Now just make sure your script tag looks like:
<script type='text/javascript' src='page.php'></script>

Categories