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

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>

Related

Including PHP files for json application

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.

PHP doesn't output error from mysql query for non-existent rows for autocomplete

I have a form that currently is able to auto complete base on user input, it queries the MySQL database and successfully lists all possible matches in the table and give suggestions. Now I want to handle rows that do not exist. I am having trouble to get my PHP file to echo the error. Here is what I have so far:
I'm guessing in my auto search function in my javascript in main.php I need to return the error message to the page?
search.php
<?php
//database configuration
$host = 'user';
$username = 'user';
$password = 'pwd';
$name = 'name';
//connect with the database
$dbConnection = new mysqli($host,$username,$password,$name);
if(isset($_GET['term'])){
//get search term
$searchTerm = '%'.$_GET['term'].'%';
//get matched data from skills table
if($query = $dbConnection->prepare("SELECT * FROM nametbl WHERE name LIKE ? ORDER BY name ASC")) {
$query->bind_param("s", $searchTerm);
$query->execute();
$result = $query->get_result();
//$row_cnt = $result->num_rows;
//echo $row_cnt;
if($result -> num_rows){
while ($row = $result->fetch_assoc()) {
$data[] = $row['name'];
}
//return json data
echo json_encode($data);
mysqli_close($dbConnection);
}
else { echo '<pre>' . "there are no rows." . '</pre>'; }
}
else {
echo '<pre>' . "something went wrong when trying to connect to the database." . '</pre>';
}
}
?>
main.php
<div id="gatewayInput">
<form method="post">
<input type="text" id="name" name="name" placeholder="Name..."><br><br>
<?php
include("search.php");
?>
</div>
...
...
...
<script src ="../../../jqueryDir/jquery-3.2.1.min.js"></script>
<script src ="../../../jqueryDir/jquery-ui.min.js"></script>
<script type="text/javascript">
//auto search function
$(function() {
$( "#name" ).autocomplete({
source: 'search.php'
});
});
1.your method type is post in the form
in main.php
and in the search.php, you have used "if(isset($_GET['term'])){"
this needs to be fixed I guess. either both needs to be POST or GET.
Again you are using include method which the whole code in search.php will be made in-line and treated as a one file main.php. so you need not use GET or Post method.
How does get and Post methods work is
3.1) you have a html or PHP which submits the data from browser(main.php), and this request is being served by an action class(search.php)
example :- in main.php
3.2) now in search.php you can use something like if(isset($_POST['term'])){
You can use num_rows (e.g. if ($result -> num_rows)) to see if the query returned anything.

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!

How can i call a php variable from a seperate file into a HTML file

Here is the actual file which i want to seperate the javascript from.
How do i tell the javascript where to look for the php file, at the moment i am only able to execute the javascript from within the php file..
<?php
date_default_timezone_set('Europe/London');
require_once("DbConnect.php");
$sql = "SELECT `artist`, `title`, `label`, `albumyear`, `date_played`, `duration`,
`picture` FROM historylist ORDER BY `date_played` DESC LIMIT 5 ";
$result = $db->query($sql);
$lastplayed = array();
$i = 1;
while ($row=$result->fetch_object()) {
$lastplayed[$i]['artist'] = $row->artist;
$lastplayed[$i]['title'] = $row->title;
$lastplayed[$i]['label'] = $row->label;
$lastplayed[$i]['albumyear'] = $row->albumyear;
$lastplayed[$i]['date_played'] = $row->date_played;
$lastplayed[$i]['duration'] = $row->duration;
$lastplayed[$i]['picture'] = $row->picture;
$i++;
}
$starttime = strtotime($lastplayed[1]['date_played']);
$curtime = time();
$timeleft = $starttime+round($lastplayed[1]['duration']/1000)-$curtime;
$secsremain = (round($lastplayed[1]['duration'] / 1000)-($curtime-$starttime));
$lastplayedjson = json_encode( $lastplayed );
?>
i want this part to be in a separate file
<script type="text/javascript">
var lastplayedjson = <?php echo $lastplayedjson ?>;
alert( lastplayedjson[1].title );
alert( lastplayedjson[2].title );
alert( lastplayedjson[3].title );
alert( lastplayedjson[4].title );
</script>
You could include the first php file (we'll call it fileA.php) which would allow fileB.php to access all of it's variables
File A
<?php
$cats = 'topkek';
File B
<?php
include('/path/to/fileA.php');
echo $cats;
Should output
topkek
You can see here for the differences on include, require, include_once and require_once
in your php:
include_once('templates/template-name.php');

Categories