Load txt from SQL Database - javascript

I have a html code with javascript that loads the data from the same directory or a given folder, that's to say the url is just "folder/text.txt".
However, if I want to extract and read this file from a mySQL database named for example exampledb, how can I indicate the new url in my code in order to import the data with Javascript just as I did with a local file?
Thanks!

You will need to use a server side programming language to talk with your database, I would strongly recommend PHP or looking into some more advanced technology like Angular.js along side Node.js!
Here is a quick PHP/mysqli example on pulling data and displaying it in a table.
taken from w3
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["firstname"]." ".$row["lastname"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
There is several ways to tackle this, that is just a start.
http://www.w3schools.com/php/php_mysql_select.asp

Related

How to query a php file stored in localhost server from a javascript file stored in local machine?

I am trying to query a php file stored in a local host (MAMP) from javascript stored in local machine. I am using this method because my end application will be an android app that is made using cordova which stores html, JS and CSS files on mobile and I need a function in JS to query a server. Below is code:
Javascript:
function onclickagree()
{
var emailid = $('#emailad').val();
$.post('http://localhost/test/checkmail.php',{postemail:emailid},
function(data)
{
alert("checked");
});
}
php file:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "userinfo";
$emailidval = $_POST['postemail'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM userregistration WHERE email = '$emailidval'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "email exists";
}
else
{
echo "email doesn't exists";
}
$conn->close();
?>
Instead of writing http://localhost/ try to write http://127.0.0.1/

How can I store audio and video files with phpMyAdmin

So my original plan was to store images and audio in the directory with my html, css etc. but when I went to write my js, I found out I couldn't use require(fs)(I need to be able to search for these things) which threw a loop in my plan. My backup plan is to create a phpMyAdmin database to store my audio and images. I'm not sure how I could do this, or if it's even possible. Could someone point me in the right direction? Thanks so much.
Edit: I realized it might be possible to alter my Javascript so it does work so here it is.
const fs=require('fs')
var files = []
fs.readdir("Assets/Cards", (err, files) => {
files.forEach(f_name => {
files.push(f_name);
});
})
console.log(files)
Just save the media in the database in a column like media_content (it being varchar of course)
Just do something like
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
if this doesn't work try rebooting your server (this only works on linux and WINDOWS NT 5.1 or lower)

Using JS to run PHP script on server

I've been at this for quite a while now, and I have pretty much no experience with PHP and I've only begun with JavaScript.
I'm attempting to run a PHP script that I have on my server from the JavaScript on the webpage using AJAX. To be honest, I don't really have much of an idea of what I'm doing.
My current code:
JS:
function Write() {
$.ajax({
type: "POST",
url: "Write.php",
data: {
'GUID': "12345678987654321",
'IP': "127.0.0.2",
'USERNAME': "George",
'BAN_REASON': "Broke my pencil."
},
success: function(data) {
console.log(data);
}
});
}
PHP:
<?php
exec("java -jar Database.jar '.$_POST['GUID']' '.$_POST['IP']' '.$_POST['USERNAME']' '.$_POST['BAN_REASON']'");
?>
(I'm also not too entirely sure that I did that String correctly, so help on that would be appreciated)
Basically, that PHP code is using a Java program I made to write to a MySQL database using the arguments that are being sent by the PHP "exec()." It's not writing to the database at all, so I'm assuming it's something with the AJAX going to the PHP function.
When "Write()" is ran, all it does is print out the PHP code to the console...
NEW CODE
<?php
//Server
$servername = "localhost";
$dbusername = $_POST['DB_USERNAME'];
$password = $_POST['DB_PASSWORD'];
$dbname = "bansdb";
$username = $_POST['USERNAME'];
$guid = $_POST['GUID'];
$ip = $_POST['IP'];
$ban_reason = $_POST['BAN_REASON'];
$connection = new mysqli($servername, $dbusername, $password, $dbname);
if ($connection->connect_error) {
die("Connection Failed: " . $connection->connect_error);
}
$sql = "INSERT INTO bans (GUID, IP, USERNAME, BAN_REASON)
VALUES ('$guid', '$ip', '$username', '$ban_reason')";
if (mysqli_query($connection, $sql)) {
echo "Ban successfully added.";
} else {
echo "Error: " . $sql . mysqli_error($connection);
}
mysqli_close($connection);
?>
I would not pass your DB user/password over the network. Just make a simple application password and store the password statically in the PHP with the db user/password (in HTML modify form to have APP_PASSWORD input). With parameterized queries aside from closing SQL injection you also can have single quotes in your value and don't have to worry about the query breaking (the driver handles the quoting).
<?php
//Server
$servername = "localhost";
$dbusername = 'static_db_user';//$_POST['DB_USERNAME'];
$password = 'staticpassword';//$_POST['DB_PASSWORD'];
$dbname = "bansdb";
if($_POST['APP_PASSWORD'] != 'Some generic password') {
die('Invalid Credentials');
}
$username = $_POST['USERNAME'];
$guid = $_POST['GUID'];
$ip = $_POST['IP']; // I would store IP as an unsigned int, ip2long
$ban_reason = $_POST['BAN_REASON'];
$connection = new mysqli($servername, $dbusername, $password, $dbname);
if ($connection->connect_error) {
die("Connection Failed: " . $connection->connect_error);
}
$sql = "INSERT INTO bans (GUID, IP, USERNAME, BAN_REASON)
VALUES (?,?,?,?)";
if ($stmt = mysqli_prepare($connection, $sql)) {
mysqli_stmt_bind_param($stmt, , 'ssss', $guid, $ip, $username, $ban_reason;
if(mysqli_stmt_execute($stmt)) {
echo "Ban successfully added.";
} else {
echo "Execute Error: " . $sql . mysqli_error($connection);
}
} else {
echo "Prepare Error: " . $sql . mysqli_error($connection);
}
mysqli_close($connection);
?>
all it does is print out the PHP code to the console...
Do you have a web server that's configured to execute PHP code? You must realize that you cannot just run a plain php file in your browser opened from the filesystem on your "server".
Make a new file called info.php and save it to your web server. Inside it should only be this:
<?php
phpinfo();
If you see that code when you browse to it, then you do not have PHP enabled. Otherwise, you will see a lot of information about your configuration.
not too entirely sure that I did that String correctly
pretty close, but you should read up about some quotes
this might work for you:
<?php
exec("java -jar Database.jar $_POST[GUID] $_POST[IP] $_POST[USERNAME] $_POST[BAN_REASON]");

how to turn a php session into a usable variable

i have created a site were i have 2 tables on a database. the first page has 2 links which when clicked sends the name of the link to a php session. it then takes you to a page were its meant to view ether one of the databases based on the data that has been saved In the php session.
what i am trying to achieve is to have those links open up the table inside that file that will open up when the link is clicked. i don't want to make a new .php file for every table since i want to be able to simply add and access those tables on one document but not more then one.
that is my problem. on that document were it sends me to access the table from my database i want to access in variable (code below). the code below will explain what i need to know.
this is the code which i view the data in my table
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM tablenamehere ORDER BY id DESC LIMIT 500";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<p>". $row["firstname"]. " " . $row["lastname"] . "</p>";
}
} else {
echo "0 results";
}
$conn->close();
>
the code below is were i want to have the variable that has the name of the link i clicked on the page which gets redirected to this when the link is clicked. the variable that i gather from the php session i want to appear at the tablenamehere text.
$sql = "SELECT id, firstname, lastname FROM tablenamehere ORDER BY id DESC LIMIT 500";
$result = $conn->query($sql);
the code i have so far which creates the php session but is not connected to links yet are below.
<html>
<body>
Register Now!
</body>
</html>
<?php
session_start();
?>
<?php
if(isset($_GET['a'])){
$_SESSION['link']=$_GET['a'];
}
echo "the veriable is " . $_SESSION['link'] . "<br>";
i only want multiple tables to open up in this one php file. thank you for helping, any questions please message below.
If we can assume you are passing a table name as a parameter ( bit dangerous ) then you can do this
<?php
if(isset($_GET['a'])){
$_SESSION['link']=$_GET['a'];
}
$sql = "SELECT id, firstname, lastname
FROM {$_SESSION['link']}
ORDER BY id
DESC LIMIT 500";
But a better way might be to pass an indicator to the table you want to use. This way you are not passing a real table name around in the ether for people to see
if(isset($_GET['a'])){
$_SESSION['link']=$_GET['a'];
}
switch ($_SESSION['link']) {
case : 'a'
$tbl_name = 'table1';
break;
case : 'b'
$tbl_name = 'table2';
break;
default:
$tbl_name = 'default_table';
}
$sql = "SELECT id, firstname, lastname
FROM $tbl_name
ORDER BY id
DESC LIMIT 500";
My guess: the script that accesses the database is test1.php. The link adds already the call parameter a (=newtable):
Register Now!
The script test1.php could honor this $_GET parameter like you do when setting the $_SESSION parameter. The modification of your code would then look like this:
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Get and sanitize table name
$tablename = $conn->real_escape_string($_GET['a']);
$sql = "SELECT id, firstname, lastname FROM $tablename ORDER BY id DESC LIMIT 500";
$result = $conn->query($sql);
// ....
Notes:
In my example I assume that all tables are handled the same way. Of course, you could differentiate code based on the value of $tablename.
You most probably would not need a $_SESSION variable.
If, for any reason you must use a $_SESSION variable $_GET['a'] obviously should be overwritten by $_SESSION['link'] or vice-versa.
For security reasons, do not forget to sanitize the input parameter $_GET['a']!

JavaScript print and AJAX save/delete from database

I have created this page to get data from the database, with links to print the shown data and delete it afterwards.
One of the problems is that the JavaScript print function window.print(); wont work.
Another problem is that after printing the page, I would like to update the database, so people can see that it has been printed before.
Alternatively, the function could also print the page and then immediately deletes data, so people won't need to see if it has been printed before or not.
This is the code for getting the data from the database:
<html>
<header>
<script>
function print_table(id)
{
//print your document
window.print();
//send your data
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","http://localhost/Stage/printed_table.php" + id;
xmlhttp.send();
}
</script>
</header>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "depits";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Query the database
$resultSet = $conn->query("SELECT * FROM orders");
// Count the returned rows
if($resultSet->num_rows != 0){
// Turn the results into an Array
while($rows = $resultSet->fetch_assoc())
{
$id = $rows['id'];
$naam = $rows['naam'];
$achternaam = $rows['achternaam'];
$email = $rows['email'];
$telefoon = $rows['telefoon'];
$bestelling = $rows['bestelling'];
echo "<p>Name: $naam $achternaam<br />Email: $email<br />Telefoon: $telefoon<br /> Bestelling: $bestelling<br /> <a href='delete.php?del=$id'>Delete</a> <input type='button' onclick='print_table($id)' value='Print Table' /> </p>";
}
// Display the results
}else{
echo "Geen bestellingen";
}
?>
</body>
</html>
and these are the pages for the two server-side functions:
delete.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "depits";
// Get ID
$id = $_GET['del'];
$sql= "DELETE FROM orders WHERE id=" . $id . "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Query the database
$resultSet = $conn->query($sql) or die("Failed".mysql_error());
echo "<meta http-equiv='refresh' content='0;url=http://localhost/Stage%201/bestellingen.php'>";
?>
print_table.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "depits";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Query the database
$id = $_GET['id'];
$resultSet = $conn->query("UPDATE `orders` SET `printed` = 1 WHERE `id` = `$id`");
?>
You should really check your browser console (F12) to see if there are any JavaScript errors.
One really glaring error I could spot is this line, where the brackets aren't closed. These type of errors could be easily fixed just by checking the console first.
Another error is the variable in the string, it should be sent as a ?key=value pair.
xmlhttp.open("GET","http://localhost/Stage/printed_table.php" + id;
should be:
xmlhttp.open("GET","http://localhost/Stage/printed_table.php?id=" + id, true);
Another problem would be the URL the above line is calling. I notice you mentioned that your PHP file name is called print_table.php instead of printed_table.php.

Categories

Resources