Including PHP files for json application - javascript

Trying to execute tleft in another file, using ajax.
But it is not showing any result.
Tried:
<?php
require_once '../class.user.php';
$user_home = new USER();
header('Content-Type: application/json');
$reg = $user_home->runQuery("SELECT COUNT(Sr) AS Sr FROM students");
$reg->execute();
$reg_rst = $reg->fetch(PDO::FETCH_ASSOC);
$registered= ($reg_rst['Sr']);
echo json_encode([
'tleft' => $registered
]);
?>
When I remove require_once '../class.user.php'; it gives me result.

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

trying to use simplexml to access the name from ean hotel list

I am trying to use simplexml to access the hotelname from an api, showing a hotel list.
I have used this code so far. It seems right to me, but I still can't get it to work.
<?php
$xml_file = 'http://dev.api.ean.com/ean-services/rs/hotel/v3/list?minorRev=99&apiKey=ycdydfqdz4w5huxv4psfxs8h&cid=55505&locale=en_US&currencyCode=USD&supplierCacheTolerance=MED_ENHANCED&countryCode=US&city=Dallas&stateProvinceCode=TX&searchRadius=50&numberOfResults=20&arrivalDate=08/31/2014&departureDate=09/15/2014&minRate=100&maxRate=1000&room1=1&numberOfAdults=2';
$xml = simplexml_load_file($xml_file);
$response = $xml->HotelListResponse->HotelList->HotelSummary;
foreach($response as $val){
echo $val->name;
}
?>
This should be your new code:
<?php
$xml_file = 'http://dev.api.ean.com/ean-services/rs/hotel/v3/list?minorRev=99&apiKey=ycdydfqdz4w5huxv4psfxs8h&cid=55505&locale=en_US&currencyCode=USD&supplierCacheTolerance=MED_ENHANCED&countryCode=US&city=Dallas&stateProvinceCode=TX&searchRadius=50&numberOfResults=20&arrivalDate=08/31/2014&departureDate=09/15/2014&minRate=100&maxRate=1000&room1=1&numberOfAdults=2';
$content = file_get_contents($xml_file);
$xml = json_decode($content);
//$xml = simplexml_load_file($xml_file);
$response = $xml->HotelListResponse->HotelList->HotelSummary;
foreach($response as $val){
echo $val->name;
}
?>
Somehow the file request answers with a JSON file. Just parse it this way.

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

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!

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