how to display form content after php processing - javascript

Im creating a forum for a little project of mine.
So far I have been able to get the form contents and use php to process (YES I HAVE NOT ACCOUNTED FOR SQL INJECTION).
Anyway, the php code is as follows:
test.php
<?php
if (isset($_POST["add"])){
// "Save Changes" clicked
$title = $_POST['title'];
$message = $_POST['message'];
$username = 'root';
$password = '';
$db = 'main_database';
$conn = mysqli_connect('localhost', $username , $password,$db);
if (!$conn){
die("unable to connect");
}
$dt = date('Y-m-d h:i:s');
$sql = "INSERT INTO threads (title,author,date_posted,post) VALUES ('$title', 2, '$dt', '$message')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
header('Location: http://127.0.0.1:5500/RuneScape_website/RS.com/aff/runescape/forums/ForumThread/~tm10CE.html');
}
?>
Now what I really want to do, is after this data has been saved to the database, I want to display the newly created blog comment to the direct page on load up. For example, When you click submit, the comment should appear in the directed html page.
The only way I think about it, is that I need either javascript to create a new attribute and append it to the list of existing attributes (e.g. ), or in the php create the div and use javascript/JQuery to access the php file and collect the html.
So I want the $title and $message to be used in the html page where its directed to.
A real example is like stack overflow. After I write an answer the page appends my response. This is what I want to achieve.
I'm curious how to go about this. Thanks :)

Don't you need to know which forum page this submitted comment belongs to?
If you add a column to threads table and store the name of the forum page in it (in this case: ~tm10CE.html), then from your html page, you can make an ajax call to a php file and include the name of the page as a querystring value. Inside the php file, query the threads table for the name of the page and return all the entries related to that page.

Related

JS script that reacts to PHP script

I have such a request: I have to do JS script, that works with PHP script.
Right now i have such a PHP code:
~~~~~~ PHP ~~~~~~
<?php
$email = filter_input(INPUT_POST, 'email');
if (!empty($email)){
$host = "localhost";
$dbusername ="root";
$dbpassword ="";
$dbname = "email";
$conn = new mysqli ($host,$dbusername, $dbpassword , $dbname);
if (mysqli_connect_error()){
die('Connection problem('.mysqli_connect_errno().')'.mysqli_connect_error());
}
else{
$sql = "INSERT INTO `email` (`email_id`, `email`) VALUES (NULL, '$email');";
if ($conn->query($sql)){
echo "<script type='text/javascript'>alert(\"Email has been written to subscribe list!\");</script>";
echo '<script type="text/javascript">
window.location = "index.html"
</script>';
}
else{
echo "<script type='text/javascript'>alert(\"Your email is already in our subscribe list!\");</script>";
echo '<script type="text/javascript">
window.location = "index.html"
</script>';
}
$conn->close();
}}else{
echo "<script type='text/javascript'>alert(\"Don't forget to include your email address !\");</script>";
echo '<script type="text/javascript">
window.location = "index.html"
</script>';
}
?>
And here is a challenge. Instead of currently js scripts in php (that they activate on clean page without any content) JS script has to work on page, without reload - on the same page, when the request was sent from. I don't know how to do that ( i'm quite new to JS ) and i hope for your hints
Thanks for advices
If you don't want to reload the rendered page, you will have to work the other way around: not PHP is generating the whole page, but a JS script is pulling information from a PHP script and uses this information to display the according note.
There are multiple ways to fetch information from a server using JavaScript, the most prominent being AJAX to load HTML chunks or JSON responses. Please search for those topics as this is a relatively broad topic and your question is much too broad as it is.

PHP login algorithm not redirecting to next page (unsure on connection to database)

I am setting up a login page to take a users username and password then check that against a local database, however nothing is echoing form the database connection and there is no redirecting to the next page 'welcome.php' happening.
I have already tried many different ways of connecting to the local database and redirecting to different pages with different methods, none of which gave any error message or worked. using XAMPP Apache and mySQL modules to provide the local server.
<?php
if (isset($_POST['Login']))
{
$link = mysql_connect('localhost','root','password','budget');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
session_start();
$username= $_POST['username'];
$password= sha1($_POST['password']);
$_SESSION['login_user']=$username;
$query = mysql_query("SELECT accounts.username, passwords.password_hash
FROM accounts
INNER JOIN passwords ON accounts.account_id = passwords.account_id
WHERE accounts.username = '$username' AND password_hash = '$password';");
if (mysql_num_rows($query) != 0){
?>
<script type="text/javascript">window.location.replace(welcome.php);
</script>;
<?php
mysql_close($link);
}
}
?>
I expect it to redirect to 'welcome.php' but instead it just refreshes the same page and nothing is echoed or given as an error
What isn't working?
Your JavaScript location.replace method needs a string as an input, you're not giving it that (as the input value is not quoted). It would be window.location.replace('welcome.php'); instead.
How to solve it?
The better solution is to redirect in PHP instead of in JavaScript, using header().
Additional remarks
I took the liberty of converting your code to use mysqli_ instead of the old, outdated and deprecated mysqli_ library. With this, you can use a prepared statement, as I have shown below. Use this approach for all your queries, bind the parameters through placeholders.
session_start();
if (isset($_POST['Login'])) {
$link = mysqli_connect('localhost','root','password','budget');
if ($link->connection_errno) {
die('Could not connect: ' . $con->error);
}
$username = $_POST['username'];
$password = sha1($_POST['password']);
$stmt = $link->prepare("SELECT a.username, p.password_hash
FROM accounts a
INNER JOIN passwords p
ON a.account_id = a.account_id
WHERE a.username = ?
AND p.password_hash = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->bind_result($resultUsername, $resultPassword);
$stmt->execute();
if ($stmt->num_rows) {
$_SESSION['login_user'] = $username;
header("Location: welcome.php");
}
$stmt->close();
}
What's next?
Fix your passwords. Using sha1() is highly insecure for passwords, look into using passwords_hash()/password_verify() instead.
You need to add single quote around welcome.php
As welcome.php is neither a JavaScript keyword like this nor a number, single quote is mandatory also it is not a variable/object.
JS considers welcome as object and php as its method in welcome.php
Without it, a JavaScript error will be displayed:
ReferenceError: welcome is not defined
<script type="text/javascript">window.location.replace(welcome.php);
</script>
Also, there is no need of semi-colon ;.
JavaScript redirect without any condition.

posting data from website to MySQL using PHP does not work

I am new on PHP and trying to do get the user agent from the visitor of the website then send this information to the MySQL.
Home.html (this page has a button where the user should click on it to take him to another page where he will see his device information
<div id="TestMe_img">
<a href="Result.php">
<input type="submit" value="Test Your Device">
</a>
</div>
Result.php (the result page contain 2 things: 1- php code. 2- html code)
PHP
<?php
$server = "localhost";
$user = "root";
$pass = "";
$dbname = "user_data";
$userAgent = $_POST['userAgent'];
// Create connection
$conn = new mysqli($server,$user, $pass, $dbname);
// Check connection
if($conn -> connect_error) {
die("Conneciton Failed: " . $conn -> connect_error);
}
if (empty($userAgent)) {
echo "User Agent is blank";
die();
}
$sql = "INSERT INTO UserData (UserAgent) VALUES ('$userAgent')";
if ($conn -> query($sql) === TRUE) {
echo "Thank you! Hana is stupid";
}
else
echo "Unfortunately Hana is smart";
$conn -> close();
?>
HTML Part
<body onload="userAgent();">
<table>
<tr>
<td>user agent</td>
<td id="userAgent"></td>
</tr>
</table>
</body>
JavaScript
function userAgent(){
var userAgent = navigator.userAgent;
document.getElementById('userAgent').innerHTML = userAgent;
}
However, there is a mistake that I can not find because every time I click on the button it takes me to the result.php and show me the code on the browser with no result appear on the database!
OK, this is going to be slightly longer, but bear with me.
1st: You will be getting a "User Agent is blank" message, because the user agent is not actually submitted to the PHP page. You need to put an input (hidden or text) into a form, push the data inside and then submit that form. Change your HTML like this, then at least your date will be submitted:
<form method="post" action="Result.php">
<input type="hidden" id="userAgent">
<input type="submit" value="Test Your Device">
</form>
2nd: You don't even need to do that, because the userAgent is available to PHP already, even without submitting it manually. Just use this variable:
$_SERVER['HTTP_USER_AGENT']
3rd: You should NEVER put unsanitized input into an SQL string. This will lead to SQL injections and your server will be hacked.
Instead of:
$sql = "INSERT INTO UserData (UserAgent) VALUES ('$userAgent')";
$conn->query($sql);
You have to use a prepared statement (for pretty much any query that accepts variables), so that nobody can manipulate your query. Otherwise if your $userAgent variable contained a single quote, you could break out of your query and the attacker could inject any SQL code he wanted. So do this to fix your security issue:
$statement = $conn->prepare("INSERT INTO UserData (UserAgent) VALUES (?)");
$statement->bind_param('s', $userAgent);
$statement->execute();
The 's' parameter is actually one letter per each parameter you want to prepare in the statement. In this case it indicates you want to pass a string. "i" would be an integer, "d" a double, see here for more: http://php.net/manual/de/mysqli-stmt.bind-param.php
4th: Your question has absolutely nothing to do with phpMyAdmin, so you should probably change the title.
I hope this helps you get started.

How can i use selected link value on another php page

I'm new with questions and generally with "Stack Overflow", so forgive me if it is not formatted well.
So, I have problem with transferring some informations from one page to another. It is a value of <a> tag from an php while loop.
At the moment I have something like this:
$query = mysql_query("SELECT DISTINCT `a`.`id`,`o`.`first_name` , `o`.`last_name` , `a`.`name` FROM `owner` AS `o` , `animal` AS `a` WHERE `o`.`id` = `a`.`fk_current_owner` AND `o`.`fk_user` = '".$_SESSION['user_id']."'");
while($row = mysql_fetch_assoc($query)){
$pet_id = $row['id'];
$first_name = $row['first_name'];
$last_name = $row['last_name'];
$pet_name = $row['name'];
echo 'Owner: <strong>'.$first_name.' '.$last_name.'</strong> ';
echo 'Pet: <strong>'.$pet_name.'</strong><br>';
}
So you can assume that this will display names of pets that logged user got.
So I linked their names and I need to get ID of selected name on another page so I can display details of pet on page viewPet.php.
You can also send the pet id along as a GET parameter with the link.
echo ''.$pet_name.'';
On the viewPet.php page you'd access it by $_GET['id']
you can put the link in a cookie:
setcookie(name, value, expire, path, domain);
that is the code to set the cookie and then to receive the cookie you can do $_COOKIE['name'];
or you can do a session.
session_start();
$_SESSION['name']=value;

Pass hidden value from database when Using autocomplete feature

I am suing autocomplete to display values from database.
The file is as follows:
autocomplete.php
<?php
require_once "../includes/conf.php";
$q=$_GET['q'];
$my_data=mysql_real_escape_string($q);
//$mysqli=mysql_connect('localhost','root','','autofield') or die("Database Error");
$sql="SELECT vName,id FROM employee WHERE vName LIKE '%$my_data%' ORDER BY vName";
$result = mysql_query($sql) or die(mysql_error());
if($result)
{
while($row=mysql_fetch_array($result))
{
echo $row['vName']." </n>".$row['id'];
}
}
?>
The above file retuens the name that will be displayed in the text filed. Along with that I would like to pass id as hidden field so that I can process the data in php
How should I go about it?
You can make use of input type hidden for this purpose.
<input type="hidden" value=".$row['id']."/>
try this:
$array = array();
while($row=mysql_fetch_array($result))
{
array_push($array ,array("value"=>$row['id'],"label"=>$row['vName']));
}
and in jquery code:
terms.push( ui.item.label );
$( "#hidtextboxid" ).val( ui.item.value);
make sure you create one hidden field in your code.
check this:
how to pass hidden id using json in jquery ui autocomplete?
i dont want to answer your question with mysql_query for two reasons:
1. mysql_query official status is Deprecated: The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
2. it is vulnerable to SQL injection, see How can I prevent SQL injection in PHP?
use PDO (PHP Data Objects ) instead, it is secured and it is object-oriented
here are some tutorials to master this in 12 videos http://www.youtube.com/watch?v=XQjKkNiByCk
replace your MySQL instance with this
// instance of pdo
$config['db'] = array
(
'host' => '',
'username' => '',
'password' => '',
'dbname' => ''
);
$dbh = new PDO('mysql:host=' . $config['db']['host'] .
';dbname=' . $config['db']['dbname'],
$config['db']['username'],
$config['db']['password']);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
global $dbh;
//dbh is just a custom name for the object you can name it database
edit the credentials, next lets query your code, if the instance is not on the same file ie the connection script is being included then call upon global $dbh; before you start your sql so you bring the object to the current file otherwise
so your code will look like this
<?php
global $dbh;
//lets prepare the statement using : to input what ever variables we need to (securely)
$displayData= $dbh->prepare("SELECT vName,id FROM employee WHERE vName LIKE :my_data ORDER BY vName");
$displayData->bindValue(':my_data', $my_data , PDO::PARAM_STR);
//then we execute the code
$displayData->execute();
//store the result in array
$result = $displayData->fetchAll();
print_r($result); //take a look at the structured
//depending on the structure echoing could be like **echo $result[0][theIdYouTrynaGet];**
?>
And how would I retrieve it in the other page then?
<html>
<?php
include_once '/*the path of your file where the above is happening*/';
<input type="hidden" value="<?php echo $result['pass in your parameters'] ?>"/>
?>
<html>

Categories