Accessing MySQL database in d3.js with php file - javascript

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!

Related

Trying to get results of a MySQL query into a JavaScript array

I've got a MySQL database of offices with geo data. I'm trying to get a list of the office cities into a JavaScript array. For now, I just wanted to set up a simple $.ajax() to log the list into the console, but it's returning null. I'm just running my JavaScript function "query()" in console after the page loads.
Here's my JavaScript.
function query() {
$.ajax({
url: "query.php",
method: "POST",
dataType: 'json',
success: function(data) {
let output = JSON.parse(data)
console.log(output)
}
})
}
Here's query.php
<?php
include 'database.php';
$sql="SELECT `Office City` FROM `offices`";
$result = $link->query($sql);
if ($result) {
while($row = $result->fetch_assoc()) {
array_push($result_array, $row);
}
}
header('Content-type: application/json');
echo json_encode($result_array);
$link->close();
?>
Here's database.php. I'm able to write to MySQL using this PHP, so I assume it's correct.
<?php
$hostname = "hostus.mostus.com";
$username = "name";
$password = "pw";
$database = "db";
$link = mysqli_connect($hostname, $username, $password,$database);
if (mysqli_connect_errno()) {
die("Connect failed: %s\n" + mysqli_connect_error());
exit();
}
When I run query() in the console, it responds "undefined" then null.
Your sql is invalid.
I would also init the $result_array before. Currently if the result is empty, you are returning null.
<?php
include 'database.php';
$sql="SELECT `Office`, `City` FROM `offices`";
$result = $link->query($sql);
$result_array = [];
if ($result) {
while($row = $result->fetch_assoc()) {
array_push($result_array, $row);
}
}
header('Content-type: application/json');
echo json_encode($result_array);
$link->close();
?>

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

my ajax call is returning html with json data

I am having a weird problem, I am trying to populate the datatable using ajax call to my php program which internally gets data from database.
php:
<?php
require_once('config.php');
$query = mysql_query("select * from productdetails");
while($fetch = mysql_fetch_array($query))
{
$output[] = array ($fetch[0],$fetch[1],$fetch[2],$fetch[3],$fetch[4],$fetch[5]);
}
echo json_encode($output, JSON_FORCE_OBJECT);
?>
Html(ajax call):
$.ajax({
url: 'process.php?method=fetchdata',
data: "json",
success: function(s){
console.log($(s).text());
oTable.fnClearTable();
for(var i = 0; i < s.length; i++) {
oTable.fnAddData([
s[i][0],
s[i][1],
s[i][2],
s[i][3],
s[i][4],
s[i][5]
]);
} // End For
},
error: function(e){
console.log(e.responseText);
}
});
This generates the output as
( ! ) Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\wamp\www\datatableone\process.php on line 2
Call Stack
#TimeMemoryFunctionLocation
10.0010242552{main}( )..\process.php:0
20.0010242840http://www.php.net/function.mysql-connect' target='_new'>mysql_connect
( )..\process.php:2
{"0":{"0":"1","1":"Iron","2":"AX12","3":"Google","4":"21.95","5":"HW"},"1":{"0":"2","1":"DartBoard","2":"AZ52","3":"Apple","4":"12.95","5":"SG"},"2":{"0":"3","1":"BasketBall","2":"BA74","3":"Microsoft","4":"29.95","5":"SG"},"3":{"0":"4","1":"Compopper","2":"BH22","3":"Google","4":"24.95","5":"HW"},"4":{"0":"5","1":"Gas Grill","2":"BT04","3":"Apple","4":"149.95","5":"AP"},"5":{"0":"6","1":"Washer","2":"BZ66","3":"Google","4":"399.99","5":"AP"}}
But my required output should be: (only json)
{"0":{"0":"1","1":"Iron","2":"AX12","3":"Google","4":"21.95","5":"HW"},"1":{"0":"2","1":"DartBoard","2":"AZ52","3":"Apple","4":"12.95","5":"SG"},"2":{"0":"3","1":"BasketBall","2":"BA74","3":"Microsoft","4":"29.95","5":"SG"},"3":{"0":"4","1":"Compopper","2":"BH22","3":"Google","4":"24.95","5":"HW"},"4":{"0":"5","1":"Gas
Grill","2":"BT04","3":"Apple","4":"149.95","5":"AP"},"5":{"0":"6","1":"Washer","2":"BZ66","3":"Google","4":"399.99","5":"AP"}}
any suggestions please.
Thanks
Sai
Solution:
PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "123456";
try {
$conn = new PDO("mysql:host=$servername;dbname=holt", $username, $password);
$statement=$conn->prepare("SELECT * FROM productdetails");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
echo $json;
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Thanks for suggestions.
As noted in the comments, you should turn off warnings, or better yet, write your code in a manner that doesn't produce warnings.
On turning off warnings:
Turn off warnings and errors on php/mysql
You can suppress errors inline with the # symbol, which is the error control operator in php. Putting # at the beginning of your mysql_connect() line should get rid of it, but you should switch to PDO!
On PDO (which I recommend and use):
http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
PDO protects you against SQL injection and allows queries to be sent to the database and constructed beforehand, and you send the inputs afterwards via "placeholders".

Using json_encode without displaying it on my webpage via echo or print

basically I'm trying to pass an array from PHP to JavaScript, so far it is all working the methods I'm using are:
PHP:
echo json_encode($arrayname);
JavaScript:
$.getJSON( 'myphppage.php', {}, function(data){
// Do stuff here
});
Obviously this echo's the text onto my webpage but I do not want this text to be displayed, I'm just wondering if there is anyway for me to use this without having a chunky array at the top of my webpage. (I tried it without the echo and it doesn't work, I've also gone through countless tutorials on this but no one seems to do it without using echo)
Thanks a lot in advance
---------- Edit -------------
index.js
$.getJSON( 'myphppage.php', {}, function(data){
// I loop through the data here
}
}).done(function() {});
myphppage.php
<?php
$servername = "name";
$username = "username";
$password = "";
$dbname = "dbname";
$connection = mysql_connect($servername,$username);
if(!$connection) {
die("Database connection failed: " . mysql_error());
}else{
$db_select = mysql_select_db($dbname,$connection);
if (!$db_select) {
die("Database selection failed:: " . mysql_error());
}
$result = mysql_query("select * FROM tablename");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$array= array();
while($row = mysql_fetch_array($result)) {
array_push($array, $row);
}
echo json_encode($array);
}
Minimal example:
index.html
$.getJSON( 'myphppage.php', {}, function(data){
// Do stuff here
});
myphpwebpage.php
echo json_encode($arrayname);

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

Categories