PDO foreach isn't displaying data being fetched - php

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

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

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

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

POST method not inserting data into database table

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

I have an input form with a prepaired statement that should input into sql and print the input but all I get is NULL printed on the page

I have an input form with a prepaired statement that should input into sql and print the input but all I get is a blank page with the input php address. Have i missed something? I have changed the code to below but all that appears is NULL. The date field is sql type date and the string i entered into it to test is "2008-11-11", without the quotes of course.
<?php
function shutdown(){
var_dump(error_get_last());
}
register_shutdown_function('shutdown');
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include("dbconfig.php");
$errorvar = "";
if (isset($_POST['submit'])) {
if (empty($_POST['Title']) || empty($_POST["Date"]) || empty($_POST["Country"]) || empty($_POST["bloguser"]) || empty($_POST["Blogentry"])) {
$errorvar = "You dun gooffed";
echo $errorvar;
} else {
//defining and injection protecting data
$title = $_POST['Title'];
$date = $_POST['Date'];
$country = $_POST['Country'];
$bloguser = $_POST['bloguser'];
$blogentry = $_POST['Blogentry'];
$stmt = $mysqli->prepare("INSERT INTO blogs (BlogName,blogDate,country,bloguser,Blogdata) VALUES (?,?,?,?,?)");
$stmt->bind_param('sssss', $title, $date, $country, $bloguser, $blogentry);
if ($stmt->execute()) {
echo "New records created successfully";
printf("%d Row inserted.\n", $stmt->affected_rows);
header("location:index.php");
} else {
header("location:index.php");
echo $conn->error;
}
$stmt->close();
$conn->close();
header("location:index.php");
}
}
?>
The html form is below
<fieldset style="width:45%"><legend>Blog data entry</legend>
<form name="Blogentry" action="Inputform.php" method="POST">
<label for="Title">Title: </label>
<input type="text" name="Title" value="" size="40"/><br>
<label for="Date">Date: </label>
<input type="text" name="Date" value="" size="40"/><br>
<label for="Country">Country: </label>
<input type="text" name="Country" value="" size="40"/><br>
<label for="bloguser">User: </label>
<input type="text" name="bloguser" value="" size="40"/><br>
<label for="Blogentry">Blog: </label>
<textarea name="Blogentry" rows="4" cols="20">
</textarea><br>
<input id="button" type="submit" name="submitblog" value="submit-blog">
</form>
</fieldset>
</body>
</html>
enable error reporting :
add on top of your script
error_reporting(E_ALL);
ini_set('display_errors', 1);
and then use prepared statements proper. As far as your script there no parameters that you are binding,
<?php
session_start();
include("dbconfig.php");
$errorvar = "";
if (isset($_POST['submit'])) {
if (empty($_POST['Title']) || empty($_POST["Date"]) || empty($_POST["Country"]) || empty($_POST["bloguser"]) || empty($_POST["Blogentry"])) {
$errorvar = "You dun gooffed";
echo $errorvar;
} else {
//defining and injection protecting data
$title = $_POST['Title'];
$date = $_POST['Date'];
$country = $_POST['Country'];
$bloguser = $_POST['bloguser'];
$blogentry = $_POST['Blogentry'];
$stmt = $conn->prepare("INSERT INTO blogs (BlogName,blogDate,country,bloguser,Blogdata) VALUES (?,?,?,?,?)");
$stmt->bind_param("sssss", $title, $date, $country, $bloguser, $blogentry);
if ($stmt->execute()) {
echo "New records created successfully";
printf("%d Row inserted.\n", $stmt->affected_rows);
header("location:index.php");
} else {
echo $conn->error;
}
$stmt->close();
$conn->close();
}
}
?>
you don't need to escape anything since you are using bind
so drop the mysqli_real_escape
you have errors in your query as I point out in the code below
$stmt = $mysqli->prepare("INSERT INTO blogs (BlogName,blogDate,country,bloguser,Blogdata) VALUES (?,?,?,?,?)");
// question marks will be replaced with data - use question marks!
$stmt->bind_param('sssss', $title, $date, $country, $bloguser, $blogentry);
// number of bound parameters should match number and order of question marks
$stmt->execute();

PHP & MySQL no inserting data into table (PDO)

I am having trouble getting a record to insert into my database, I have checked the code and all the variables and names match between PHP and the database.
There are no error messages and I am getting the text saying booking was created but, no record is entered into the database.
Here is the php code for inserting the record;
<div class="containter">
<?php
if (isset($_POST['submit'])) {
try {
include ('include\PDO.php');
$sql = "INSERT INTO customers(Customer_Name, Customer_Email, Customer_Contact) VALUES (:Customer_Name, :Customer_Email, :Customer_Contact)";
//Named Parameters
$stmt = $dbh->prepare($sql);
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
$Customer_Name = filter_input(INPUT_POST, 'Customer_Name');
$stmt->bindValue(':Customer_Name', $Customer_Name, PDO::PARAM_STR);
$Customer_Email = filter_input(INPUT_POST, 'Customer_Email');
$stmt->bindValue(':Customer_Email', $Customer_Email, PDO::PARAM_STR);
$Customer_Contact = filter_input(INPUT_POST, 'Customer_Contact');
$stmt->bindValue(':Customer_Contact', $Customer_Contact, PDO::PARAM_STR);
print $Customer_Contact;
print $Customer_Name;
print $Customer_Email;
$stmt->execute();
$dbh = null;
} catch (PDOException $e) {
//Error Messages
print "We have had an error: " . $e->getMessage() . "<br/>";
die();
}
?>
<p> Booking Created.</p>
<?php } else { ?>
<form action ="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<label>Name:</label> <input type="text" name ="Cusomer_Name">
<label>Email:</label> <input type="email" name ="Cusomer_Email">
<label>Contact:</label> <input type="tel" name ="Cusomer_Contact">
<input type="submit" name ="submit">
</form>
<?php } ?>
</div>
</body>
</html>
I have checked everything I can think of but I just cannot seem to get the records to add to the database.
Any ideas of what I'm doing wrong?
In the html form you have:
<label>Name:</label> <input type="text" name ="Cusomer_Name">
In the php code you filter Customer_Name:
$Customer_Name = filter_input(INPUT_POST, 'Customer_Name');
There is a missing 't' in the html form.
Put Customer_Name instead of Cusomer_Name in the html form and do the same thing for Cusomer_Email and Cusomer_Contact
$stmt->execute(); returns boolean with answer. Try following snippet to figure out where exactly problem is:
$success = $stmt->execute();
if (!$success){
print $stmt->errorInfo()[2]; //PDO driver error message
}

Categories