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]");
Related
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/
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)
this is my code. i've done this before in other computer and it's okay, but now when try it in my laptop,it can't be done. idk what is the problem, it will show blank in phpmyadmin. i'm using xampp v3.2.2, is that will be the problem?
<html><head><title>Your Data</title></head>
<body>
<?php
$n = $_POST["n"];
$c = $_POST["contact"];
$e = $_POST["email"];
$cm = $_POST["campus"];
$m1 = $_POST["member1"];
$m2 = $_POST["member2"];
$m3 = $_POST["member3"];
$connect = mysqli_connect("localhost","root","") or die("Unable to connect MySQL".mysqli_error());
$db = mysqli_select_db($connect,"multimedia_db") or die("Unable to select database");
$query1 = "INSERT INTO teams(advisor_name,advisor_contact,advisor_email,advisor_campus,member1,member2,member3) VALUES ('$n','$c','$e','$cm','$m1','$m2','$m3')";
$data1 = mysqli_query($connect,$query1) or die("SQL statement failed"); //records are assigned to variable data
echo "You've succesfully register";
?>
</body>
</html>
I don't use MySQLi very often. So I'll explain how to use PDO. Just so you know PDO means PHP Data Objects. The reason I'm explaining, PDO is because, if done properly, it makes SQL injection almost impossible.
Connection
connecting to your database is generally done in a separate file. Here is an example:
con.php
<?php
$hostname = '';
$username = '';
$password = '';
$dbname = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
This is just connecting to the database, so we don't have to keep connecting to other pages, we just refer to this page with an include, like this:
<?php include 'con.php'; ?>
We can put this on any page and it'll include the connection to the database. For example, if you want to select from a database:
<?php
include 'con.php';
$load_data = $dbh->prepare("SELECT * FROM user_table");
if ($load_data->execute()) {
$load_data->setFetchMode(PDO::FETCH_ASSOC);
}
while ($row = $load_data->fetch()) {
$name = $row['name'];
echo $name;
}
?>
This would simply SELECT everything from the user_table from the column name and would display all the matching records.
If you're trying to do an INSERT instead:
<?php
include 'con.php';
$post_name = $_POST['post_name'];
$stmt = $dbh->prepare("INSERT INTO user_table (name) VALUES (:user_name)");
$stmt->bindParam(':user_name', $post_name, PDO::PARAM_STR);
if ($stmt->execute()) {
echo "Success";
} else {
echo "Failed";
}
?>
So the $post_name would be the name you give your input on a form in this case name="post_name" that would be inserted into the user_table.
Hope this helps and FYI here is a very good tutorial on how to do INSERT, UPDATE and DELETE using PDO.
i've found the solution for my question. It's just that i forgot to put localhost in front of the 'url'. no wonder it showed blank.
like 'localhost/sem5/saveRegistration.php'.
i'm sorry for the inconvenience. still a beginner using this hehe
So I'm building a mobile (cordova) app using a mySQL server, PHP, javascript (jQuery) but I have encountered a rather annoying problem.
When sending a test string with AJAX the recieving end, a PHP script does not receive all the data:
function testJson() {
$.ajax({
type: 'POST',
data: {
text: "hello, this is a test to see if the string is send."
},
url: 'http://a.working.url/save.php',
success: function(data) {
alert('succes');
},
error: function(data) {
alert('There was an error adding your comment');
}
});
return false;
}
then at the serverside I have a small PHP script:
<?php
$server = "localhost:3307";
//changed port to 3307
$username = "user";
$password = "pass";
$database = "test";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$comment = $_POST['text'];
echo $comment;
$sql = "INSERT INTO data (comment) ";
$sql .= "VALUES ('$comment')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
echo "Comment added";
}
mysql_close($con);
?>
but this PHP script did not recieve the full string, when I check using:
echo $_POST['text']
It only got: "hello, this is a test to see if the" (without quotes).
If anybody can help me it would be great cause I cannot continue working on the app unless the data transfer works.
Thanks in advance.
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