When I submit my form to add a comment reply, the entire div that surrounds the form disappears. The comment still get added to the database but the div just disappears and I have to refresh my page. Any ideas ?
<div id="comment_reply" class="reply_div">
<form action="reply_comment.php?comment_id=<?php echo $comment_id; ?>"
method="POST">
<input type='hidden' name='comment_id' value="<?php echo $comment_id ?>">
<textarea name='reply_comment' id='reply_comment'
placeholder='Reply...'></textarea>
<button id="reply_button" name="reply_button">Add</button>
</form>
</div>
reply_comment.php:
<?php
require 'config/connect.php';
$con = new mysqli(...$dbCredentials);
include 'includes/classes/User.php';
include 'includes/classes/Post.php';
include 'includes/classes/Notification.php';
$userLoggedIn = $_SESSION['user_session'];
$comment_id = $_GET['comment_id'] ?? 0;
if (isset($_POST['reply_button'])) {
if (empty($_POST["reply_comment"])) {
echo "Reply can't be empty. Try Again";
exit();
}
$reply_body = trim(strip_tags(filter_var($_POST['reply_comment'],
FILTER_SANITIZE_STRING)));
$stmt = $con->prepare("INSERT INTO comment_replies (reply_body, username, comment_id)
VALUES (?, ?, ?)");
$stmt->bind_param("ssi", $reply_body, $userLoggedIn, $comment_id);
$stmt->execute();
header($_SERVER['HTTP_REFERER']);
exit();
}
?>
Related
I have a html form which includes a question involving three radio buttons. I want the word 'road', 'both' or gravel' to be saved to my database. This field is set up as a varchar in the database.
This is my html:
<div class="form-group">
<label>Do you prefer just road or gravel/trail cycling as well?</label>
<label for="road">Just road</label>
<input type="radio" name="bike_terrain" id="road" value="road" required/>
<span class="invalid-feedback"><?php echo $bike_terrain_err; ?></span>
<label for="both">Both</label>
<input type="radio" name="bike_terrain" id="both" value="both" />
<span class="invalid-feedback"><?php echo $bike_terrain_err; ?></span>
<label for="gravel">Just gravel/trail</label>
<input type="radio" name="bike_terrain" id="gravel" value="gravel" />
<span class="invalid-feedback"><?php echo $bike_terrain_err; ?></span>
</div>
I am then using php to validate the input is not empty:
if(empty($_POST["bike_terrain"])){
$bike_terrain_err = "Please select a bike terrain.";
} else {
$bike_terrain = isset($_POST["bike_terrain"]);
}
And php to send it to my localhost database:
if(empty($username_err) && empty($email_err) && empty($bike_terrain_err)) {
// Prepare an insert statement
$sql = "INSERT INTO users (username, email, terrain) VALUES (?, ?, ?)";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "sss", $param_username, $param_email, $param_terrain);
// Set parameters
$param_username = $username;
$param_email = $email;
$param_terrain = $bike_terrain;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Redirect to login page
header("location: login.php");
} else{
echo "Oops! Something went wrong. Please try again later.248";
}
}
}
(Note: I have cut out some of the other fields that I am inserting for simplicity)
$bike_terrain has previously been initialised as a string.
The problem is that nothing is being saved to the terrain field in my database and I don't know why!
Thank you very much! All suggestions, thoughts or ideas are very welcome.
Something like this (untested) should do the trick. you save the same radio with the same name so it would look like a selection somehow.
Had to quickly code from my mobile device XD
<?php
if(isset($_POST['submit'])){
$host = '127.0.0.1';
$user = 'root';
$pass = '';
$db = 'people_db'
$con = mysqli_connect($host, $user, $pass, $db) or die ('Cannot connect'.mysqli_error());
$fullname = mysqli_real_escape_string($con,$_POST['fullname']);
$gender = mysqli_real_escape_string($con,$_POST['gender']);
$q = "insert into employeedb (fullname, gender) values ('".$fullname."', '".$gender."')";
mysqli_result($con,$q);
echo 'Data Saved to Database!';
}
?>
<html>
<head>
<title>Save Radio to DB</title>
</head>
<body>
<form name="people" method="POST" action="index.php"
<input type="text" name="fullname" placeholder="Enter your name"/><br/>
<input type="radio" name="gender" value="Male"/>
<input type="radio" name="gender" value="Female"/><br/>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
I am having trouble creating this login system. When someone logs in I want it to create a table, if not already. Then bring them to the form page, then insert the data. I have everything working until the insert on the last page.
After Steam API Login
<?php
session_start();
require ('../../../mysql_connect/mysqli_connect_accounts.php');
require ('../steamauth/steamauth.php');
require ('../steamauth/userInfo.php');
$steamid=$_SESSION['steamid'];
$query = "SELECT * FROM `".$steamid."`";
$response = #mysqli_query($dbc, $query);
if($response){
header("Location: http://theskindealer.com/index.php");
} else {
$create = "CREATE TABLE `".$steamid."` (
steam64 VARCHAR(30),
fullname VARCHAR(60),
tradeurl VARCHAR(60),
email VARCHAR(50),
age INT(3),
tos INT(1),
access INT(1),
freeze INT(1),
balance DECIMAL(9,2),
newsletter INT(1),
emailVerified INT(1)
)";
if ($dbc->query($create) === TRUE) {
header("Location: http://theskindealer.com/scripts/createAccount.php");
} else {
header("Location: http://theskindealer.com/pages/errorlogin.php");
}
}
$stmt->close();
$dbc->close();
?>
Then it REDIRECTS to the form page:
<!DOCTYPE HTML>
<?php
session_start();
require ('../../../mysql_connect/mysqli_connect_accounts.php');
require ('../steamauth/steamauth.php');
require ('../steamauth/userInfo.php');
$steamid=$_SESSION['steamid'];
?>
<html>
<head>
<title>TheSkinDealer | Setup</title>
<link rel="stylesheet" type="text/css" href="../css/accept.css"></head><body>
<div id="content">
<div id="acceptbox">
<img src="../images/logo.png">
<form action="setup.php" method="post">
<div id="name1">Full Name:</br> <input type="text" name="fullname"> </br></div>
<div id="name1">TradeURL: <a target="_blank" href="http://steamcommunity.com/id/me/tradeoffers/privacy#trade_offer_access_url">(?)</a></div> <input type="text" name="tradeurl"> </br>
<div id="name1">EMAIL:</div> <input type="text" name="email"> </br>
<div id="checkboxes">
Terms Of Serice: <input type="checkbox" name="tos" value="1"> </br>
18 Or Older: <input type="checkbox" name="age" value="1"></br>
Newsletter: <input type="checkbox" name="newsletter" value="1"></br>
</div>
<div id="returnhome">
<div id="accept"><input type="submit" value="Create Account"></a></div>
</div>
</form>
</div>
<center><div id="par">Purchases Or Sales Cannot Be Made Without Accepting TOS.</div></center>
</div>
</body>
</html>
Lastly the insert page:
<?php
session_start();
require ('../../../mysql_connect/mysqli_connect_accounts.php');
require ('../steamauth/steamauth.php');
require ('../steamauth/userInfo.php');
$steamid=$_SESSION['steamid'];
$insert = "INSERT INTO `".$steamid."` (steam64, freeze, access,
tos, balance, age, email, tradeurl, fullname, newsletter, emailVerified)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $dbc->prepare($insert);
$stmt->bind_param('sssssssssss',
$steam64,
$freeze,
$access,
$tos,
$balance,
$age,
$email,
$tradeurl,
$fullname,
$newsletter,
$emailVerified
);
$steam64 = $steamid;
$freeze = 0;
$access = 0;
$tos = $_POST["tos"];
$balance = 0.00;
$age = $_POST["age"];
$email = $_POST["email"];
$tradeurl = $_POST["tradeurl"];
$fullname = $_POST["fullname"];
$newsletter = $_POST["newsletter"];
$emailVerified = 0;
$stmt->execute();
header("Location: http://theskindealer.com/");
$stmt->close();
$dbc->close();
?>
Do you get any errors when executing this script?
You could for instance add error_reporting(E_ALL); to the top of your script to get a better look at errors.
Looking at the script it seems like you are binding variables before they exist.
You should put the variable assigments before the bind_param exetution:
$steam64 = $steamid;
$freeze = 0;
$access = 0;
$tos = $_POST["tos"];
$balance = 0.00;
$age = $_POST["age"];
$email = $_POST["email"];
$tradeurl = $_POST["tradeurl"];
$fullname = $_POST["fullname"];
$newsletter = $_POST["newsletter"];
$emailVerified = 0;
$stmt->bind_param('sssssssssss',
$steam64,
$freeze,
$access,
$tos,
$balance,
$age,
$email,
$tradeurl,
$fullname,
$newsletter,
$emailVerified
);
$stmt->execute();
Also keep in mind that numeric values like 0 must be bind with 'i' instead of 's'
See http://php.net/manual/de/mysqli-stmt.bind-param.php for more info.
For instance.
$stmt->bind_param('iiisdissssi',
I'm trying to play around with databases and inserting data dynamically with php.
At the moment I have a form with 'post' method and everything seems logical to me but it isn't inserting the data into the table.
Code is attached below, would appreciate if someone could point me into the right direction.
index.php:
<form action="index.php" method="post">
<label for="name">Name</label>
<input type="text" name="name" required>
<label for="breed">Breed</label>
<input type="text" name="breed">
<label for="age">Age</label>
<input type="text" name="age">
<input type="submit" name="submit" value="Submit">
</form>
<?php
require "connect.php";
if('submit') {
$name = $_POST['name'];
$breed = $_POST['breed'];
$age = $_POST['age'];
$newdog = mysqli_query('INSERT INTO `dogs`(`name`, `breed`, `age`) VALUES ([$name],[$breed],[$age)');
if ($newdog) {
echo "$name has been added to the database";
} else {
echo "$name has not been added to database.";
};
};
?>
connect.php:
<?php
$connect = mysqli_connect('localhost', 'max', 'password', 'db_test');
?>
<?php
require "connect.php";
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$breed = $_POST['breed'];
$age = $_POST['age'];
$newdog = mysqli_query($connect, 'INSERT INTO dogs(name, breed, age) VALUES ("'.$name.'","'.$breed.'","'.$age.'")');
if ($newdog) {
echo "$name has been added to the database";
} else {
echo "$name has not been added to database.";
};
};
?>
Change if('submit') {
TO
if(isset($_POST['submit'])){//check if it is set
}
Also change this line:
$newdog = mysqli_query('INSERT INTOdogs(name,breed,age) VALUES ([$name],[$breed],[$age)');
TO
$newdog = mysqli_query($connect, 'INSERT INTOdogs(name,breed,age) VALUES ($name,$breed,$age)');//remove square bracktes and add connection variable
Your code is very well vulnerable to SQL injection
Using prepared statements,
$stmt = $connect->prepare("INSERT INTO dogs (`name`, `breed`, `age`) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $name, $breed, $age);
if($stmt->execute() == true){
echo 'Saved';
} else {
echo 'Error '. $stmt->error;
}
Own answer: Figured it out, I had to configure PHPStorm to use MAMP Apache server instead of the internal server since that one apparently doesn't like $_POST[] requests
So here I have a blog system.
My problem is that when I try to pull out data from the database, it is not displaying. Here is my current code, thanks!
index.php
<h1>News Blog</h1>
<form action="blog.php" method="POST">
username: <input type="name" name="name" placeholder="name"><br />
<textarea name="body" rows="10" cols="70"></textarea><br/>
<input type='submit' name='submit' value='Post' />
</form>
<?php
if(isset($_POST['name'], $_POST['body'])){
require'core/connect.php';
$query = dbConnect()->prepare("SELECT name, body FROM blog WHERE name =:name AND body = :body");
$query->bindParam(1, $_POST['name']);
$query->bindParam(2, $_POST['body']);
foreach($query-> fetchAll(PDO::FETCH_ASSOC) as $row){
echo $row['name'], '<br/><hr>';
echo $row['body'];
}
}
?>
Here is my blog.php if its necessary
<?php
if(isset($_POST['name'], $_POST['body'])){
require'core/connect.php';
$query = dbConnect()->prepare("INSERT INTO blog (name, body) VALUES (?,?)");
$query->bindParam(1, $_POST['name']);
$query->bindParam(2, $_POST['body']);
if($query->execute()){
echo 'Thank you for posting! Click here to go back.';
} else{
echo 'There has been an error';
}
}
?>
You need to fix your parameter binding first. You are using named placeholders in your query but using 1-indexed parameters in your bindParam calls. Then you also need to execute the query:
$query = dbConnect()->prepare("SELECT name, body FROM blog WHERE name =:name AND body = :body");
$query->bindParam(':name', $_POST['name']);
$query->bindParam(':body', $_POST['body']);
$query->execute();
foreach($query->fetchAll(PDO::FETCH_ASSOC) as $row){
echo $row['name'], '<br/><hr>';
echo $row['body'];
}
You have to execute your statement before fetch, and for a list page, you don't have to add the where part in your sql. There is no data post to the index.php.
Just change to below:
<?php
require'core/connect.php';
$query = dbConnect()->prepare("SELECT name, body FROM blog");
$query->execute();
foreach($query->fetchAll(PDO::FETCH_ASSOC) as $row){
echo $row['name'], '<br/><hr>';
echo $row['body'];
}
?>
I have this code:
Episode.php
<?$feedback = new feedback;
$articles = $feedback->fetch_all();
if (isset($_POST['name'], $_POST['post'])) {
$cast = $_GET['id'];
$name = $_POST['name'];
$email = $_POST['email'];
$post = nl2br ($_POST['post']);
$ipaddress = $_SERVER['REMOTE_ADDR'];
if (empty($name) or empty($post)) {
$error = 'All Fields Are Required!';
}else{
$query = $pdo->prepare('INSERT INTO comments (cast, name, email, post, ipaddress) VALUES(?, ?, ?, ?, ?)');
$query->bindValue(1, $cast);
$query->bindValue(2, $name);
$query->bindValue(3, $email);
$query->bindValue(4, $post);
$query->bindValue(5, $ipaddress);
$query->execute();
} }?>
<div align="center">
<strong>Give us your feedback?</strong><br /><br />
<?php if (isset($error)) { ?>
<small style="color:#aa0000;"><?php echo $error; ?></small><br /><br />
<?php } ?>
<form action="episode.php?id=<?php echo $data['cast_id']; ?>" method="post" autocomplete="off" enctype="multipart/form-data">
<input type="text" name="name" placeholder="Name" /> / <input type="text" name="email" placeholder="Email" /><small style="color:#aa0000;">*</small><br /><br />
<textarea rows="10" cols="50" name="post" placeholder="Comment"></textarea><br /><br />
<input type="submit" onclick="myFunction()" value="Add Comment" />
<br /><br />
<small style="color:#aa0000;">* <b>Email will not be displayed publicly</b></small><br />
</form>
</div>
Include.php
class feedback { public function fetch_all(){
global $pdo;
$query = $pdo->prepare("SELECT * FROM comments");
$query->bindValue(1, $cast);
$query->execute(); return $query->fetchAll();
} }
This code updates to the database as it is suppose to. But after submission it reloads the current page as mentioned in the form action.
But when I refresh the page to see the comment being added it asks to re submit. If I hit submit then the comment adds again.
How can I stop this from happening?
Maybe I could hide the comment box and display a thank you message but that would not stop a repeat entry.
Please help. Thank you.
Kev
You need to add a redirect in there. So at the bottom of your POST block add
if(isset($_POST['name'], $_POST['post'])) {
// Do POST stuff here
header('Location: your/url/here');
exit;
}
This sends a 302 redirect to the browser and it does a clean load of the page. Since this is a GET operation, there's no reload issues either.
After you have run
$query->execute();
you could unset your variables:
unset($name, $email, $post);