How to insert data in database using PDO? [duplicate] - php

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 3 years ago.
Is there any error in my code? I tried to insert articles but it's not being inserted.
It will be great if someone can check my code and tell me about my mistakes (I'm learning).
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in']))
{
//display add page
if (isset($_POST['title'], $_POST['content']))
{
$title = $_POST['title'];
$content = $_POST['content'];
if (empty($title) or empty($content))
{
$error = 'All fields are required';
}
else
{
$query = $pdo->prepare('INSERT INTO articles (article_title, article_content, article_timestamp) VALUES (?, ?, ?)');
$query->bindValue(1, $title);
$query->bindValue(2, $content);
$query->bindValue(3, time());
$query->execute();
header('Location: index.php');
exit();
}
}
?>
<html>
<head>
<title>CMS Tuterial</title>
<link rel="stylesheet" href="../assets/style.css" />
</head>
<body>
<div class="container">
CMS
<br />
<h4>Add Article</h4>
<?php
if(isset($error))
{
?>
<small style="color:#aa0000;"><?php echo $error; ?>
<br /> <br />
<?php
}
?>
</small>
<form action="add.php" method="post" autocomplete="off">
<input type="text" name="title" placeholder="Title" /><br /><br />
<textarea rows="15" cols="50" placeholder="Content" name="content"></textarea><br /><br />
<input type="submit" value="Add Article" />
</form>
</div>
</body>
</html>
<?php
}
else
{
header('Location: index.php');
}
?>

This doc explains the PDOStatement::bindValue that you might want to check. Then, you might want to change your codes to something similar to this, and it may work:
session_start();
include_once '../includes/connection.php';
if (isset($_SESSION['logged_in'])) {
//display add page
if (isset($_POST['title'], $_POST['content'])) {
$title = $_POST['title'];
$content = $_POST['content'];
if (empty($title) or empty($content)) {
$error = 'All fields are required';
} else {
$query = $pdo->prepare('INSERT INTO articles (article_title, article_content, article_timestamp) VALUES (?, ?, ?)');
$query->bindValue(1, $title, PDO::PARAM_STR);
$query->bindValue(2, $content, PDO::PARAM_STR);
$query->bindValue(3, time(), PDO::PARAM_INT);
$query->execute();
header('Location: index.php');
exit();
}
}
}
Edit:
If you only wish to see, queries are being executed, you might remove the ifs and test it, then you can add any if that is necessary. Maybe, similar to:
session_start();
include_once '../includes/connection.php';
$title = $_POST['title'];
$content = $_POST['content'];
var_dump($title);
var_dump($content);
$query = $pdo->prepare('INSERT INTO articles (article_title, article_content, article_timestamp) VALUES (?, ?, ?)');
var_dump($query);
$query->bindValue(1, $title, PDO::PARAM_STR);
$query->bindValue(2, $content, PDO::PARAM_STR);
$query->bindValue(3, time(), PDO::PARAM_INT);
$query->execute();

Related

Div disappears after form submission PHP

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();
}
?>

PHP, Inserting Form Data Into MYSQLi

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',

PDO foreach isn't displaying data being fetched

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'];
}
?>

Row won't update in database

I'm making a community site thing.
I'm currently making the option to change your password.
But, when I try to use it, it won't work..
Why is this? How do I fix it?
My code:
Settings.php (Where I change the pass)
PHP:
<?php
error_reporting(E_ALL);
include_once('includes/connection.php');
include_once('includes/user.php');
if(isset($_SESSION['logged_in'])){
if(isset($_POST['oldpass']) and isset($_POST['newpass'])){
$name = $_COOKIE['name'];
$oldpass = md5($_POST['oldpass']);
$newpass = md5($_POST['newpass']);
$query = $pdo->prepare("SELECT * FROM users WHERE username=? AND password=?");
$query->bindValue(1, $name);
$query->bindValue(2, $oldpass);
$query->execute();
$num = $query->rowCount();
if($num==1){
$query = $pdo->prepare("UPDATE users SET password=? WHERE username=?");
$query->bindValue(1, $newpass);
$query->bindValue(2, $name);
$result = $query->execute();
if($result==1){
header('Location: logout.php');
}else{
echo "Something went wrong.";
}
}
}
}
?>
HTML:
<html>
<head>
<title>MackNet</title>
<link rel="stylesheet" type="text/css" href="assets/style.css">
</head>
<body>
<div id="main">
<?php
$name = $_COOKIE['name'];
$pass = $_COOKIE['pass'];
$user = new User();
$row = $user->fetch_all($name, $pass);
?>
<div id="toolbar">
<?php
echo " <a href='main.php'>Home</a> ";
echo " <a href='logout.php'>Logout</a> ";
echo " <a href='settings.php'>Settings</a> ";
if($row['group'] == 2){
echo " <a href='users.php'>Manage Users</a> ";
}
?>
<hr>
</div>
<form action="settings.php" method="POST">
<input type="password" name="oldpass" placeholder="Old Password">
<input type="password" name="newpass" placeholder="New Password">
<input type="submit" value="Change password">
</form>
</div>
</body>
</html>
If you need any more code, tell me.
Thanks // Mackan90095
What error do you get? Or does it never get inside the if($num==1)?
Maybe its smart to retrieve the users id and use that to change the password. Imagine two users having the same username, that would change both their passwords.
I would also include a password confirmation field to make sure they enter the new password twice (just as a precaution).
Useful site: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
Why dont you try using try catch to see the error and replace if($result==1) with if($result)
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try{
$query = $pdo->prepare("SELECT * FROM users WHERE username=? AND password=?");
$query->bindValue(1, $name);
$query->bindValue(2, $oldpass);
$query->execute();
$num = $query->rowCount();
if($num==1){
$query = $pdo->prepare("UPDATE users SET password=? WHERE username=?");
$query->bindValue(1, $newpass);
$query->bindValue(2, $name);
$result = $query->execute();
if($result)
header('Location: logout.php');
}
}
catch (PDOException $e) {
echo "DataBase Error: ".$e->getMessage();
}
catch (Exception $e) {
echo "General Error: ".$e->getMessage();
}
You have a beautiful code, but I've seen only this:
change
<form action="settings.php" method="POST">
to
<form action="Settings.php" method="POST">
Settings.php is capitalized?

Adding to database. No repeat on refresh

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);

Categories