Comment system reposting comment on page reload - php

I've been doing a very simple php comment system, where the user simply types a comment and it appears on the site.However, I realised that the most recent comment would keep being posted if the user refreshed the page.
I figured it had something to do with the while loop in the getComments function, but I've tried header("Location: index.php") and it had another error, so I'm really out of ideas.
index.php:
<?php
date_default_timezone_set('Europe/Bucharest');
include 'dbh.inc.php';
include 'comments.inc.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<?php
echo "<form method='POST' action='".setComments($conn)."'>
<input type='hidden' name='uid' value='Anonymous'>
<input type='hidden' name='date' value='".date('d-m-Y H:i:s')."'>
<textarea name='message'></textarea><br/>
<button type='submit' name='commentSubmit'>Comment</button>
</form>";
getComments($conn);
?>
</body>
</html>
Comments.inc.php:
<?php
function setComments($conn)
{
if (isset($_POST['commentSubmit']))
{
$uid = $_POST['uid'];
$date = $_POST['date'];
$message = $_POST['message'];
$sql = "INSERT INTO comments (uid, date, message) VALUES ('$uid','$date','$message')";
$result = mysqli_query($conn,$sql);
}
}
function getComments($conn)
{
$sql = "SELECT * FROM comments";
$result = mysqli_query($conn,$sql);
while($row =$result->fetch_assoc())
{
echo "<div class='comment-box'><p>";
echo $row['uid']." ";
echo $row['date']."<br>";
echo nl2br($row['message']);
echo "</p></div>";
}
}
dbh.inc.php
<?php
$conn = mysqli_connect('localhost', 'root', '' , 'commentsection');
Any feedback is greatly appreciated.

So I do not know if this is a good thing, but it seems very practical.What I've finally done is:
I set up a session variable.Then instead of
function getComments($conn)
{
$sql = "SELECT * FROM comments";
$result = mysqli_query($conn,$sql);
while($row =$result->fetch_assoc())
{
echo "<div class='comment-box'><p>";
echo $row['uid']." ";
echo $row['date']."<br>";
echo nl2br($row['message']);
echo "</p></div>";
}
}
I did
function getComments($conn)
{
$sql = "SELECT * FROM comments";
$result = mysqli_query($conn,$sql);
while($row =$result->fetch_assoc())
{
if($_SESSION["repeated"]!=$row['message'])
{
echo "<div class='comment-box'><p>";
echo $row['uid']." ";
echo $row['date']."<br>";
echo nl2br($row['message']);
}
$_SESSION["repeated"]=$row['message'];
echo "</p></div>";
}
}
And it seems to be absolutely working!It has a minor glitch though :
If I delete all the variables in the database after I already posted a comment in this session, at some point it will post it again.(Not a big deal).
But that's all.
I was going for the post/redirect/get, but I was a bit confused and tried this out of curiosity and it worked.(To me)It seems a simpler approach, or is it something I'm not seeing?

easy fix!!!
add recuired to the forms
<input type='text' name='emne' placeholder='Subject' required
<input type='text' name='emne' placeholder='Subject' required>

Related

MySQL/PHP <select> not displaying submitted value

I am working on a school assignment and I have run into some issues. I have PHP code for a form that, when selected, sends the selected result to a MySQL database and then loops through and displays the results. The only problem is that, instead of showing the selected <option>, it shows all four of the options.
Here is my code:
<?php
include_once (connection.php);
if (($_SERVER["REQUEST_METHOD"] == "POST") && (isset($_POST['card_catalog_form']))) {
$card_name = mysqli_real_escape_string($conn, $_POST['card_name']);
$card_label = mysqli_real_escape_string($conn, $_POST['card_label']);
$insert_card_genre_query = sprintf("INSERT into card_catalog (card_name, card_label) VALUES ('%s', '%s')",
$card_name,
$card_label);
$insert_card_genre = mysqli_query($conn, $insert_card_genre_query) or die (mysqli_error($conn));
$last_record = mysqli_insert_id($conn);
}
$card_genre_query = "SELECT card_genre.genre_id, card_label from `card_genre` order by card_label asc";
$card_genre = mysqli_query($conn, $card_genre_query) or die(mysqli_error($conn));
$get_card_genre_query = "SELECT card_catalog.id, card_catalog.card_name, card_catalog.card_label, card_genre.genre_id from card_catalog right join card_genre on card_catalog.card_label = card_genre.card_label";
$get_card_genre = mysqli_query($conn, $get_card_genre_query) or die(mysqli_error($conn));
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>The Marketplace By The Mana Club</title>
<link rel="stylesheet" type="text/css" href="stylesheets/tmp.css">
</head>
<body>
<?php include(templatestuff/top_of_tmp.php); ?>
<main>
<h1>Products:</h1>
<section>
<ul id="products_list">
<li><b>Product 1: "Jack-In-The-Mox"</b></li>
<li><b>Product Description: "Roll a six-sided die for Jack-in-the-Mox. On a 1, sacrifice Jack-in-the-Mox and lose 5 life. Otherwise, Jack-in-the-Mox has one of the following effects. Treat this ability as a mana source..."</b></li>
<img src="productimages/jackinthemox.jpeg" alt="Jack In The Mox"/>
</ul>
</section>
<div>
<h2>What Card Are You Looking For?</h2>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data">
<fieldset>
<p><b>What's The Card Name? <input type="text" name="card_name"></b></p>
<p>
<p><b>Card Type:</b></p>
<select name="card_genre">
<?php while ($row_card_genre = mysqli_fetch_assoc($card_genre)) { ?>
<option value="<?php echo $row_card_genre['genre_id'];?>"><?php echo $row_card_genre['card_label'];?></option>
<?php } ?>
</select>
</p>
<p><input type="submit"></p>
<input type="hidden" name="card_catalog_form">
</fieldset>
</form>
<?php
if ($last_record) {
echo "<p><b>You just created form query #" . $last_record ."</b><p>";
}
?>
<p>You are submitting your form at
<?php
date_default_timezone_set('America/New_York');
echo date('g:i a \o\n l, F j, Y');
?>
</p>
</div>
<?php
$query = "SELECT card_catalog.card_name, card_catalog.card_label, card_genre.genre_id FROM card_catalog, card_genre";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
while($row = mysqli_fetch_array($result)){
echo $row['card_name']. " - ". $row['genre_id'];
echo "<br />";
}
?>
</main>
<?php include('templatestuff/bottom_of_tmp.php'); ?>
</body>
</html>`
(If you want to see the website that contains the problem, you can go here)
Any help, or constructive criticism, would be greatly appreciated.
Thanks
This might point you in the right direction:
if (isset($_POST['card_genre'])) {
$query = "SELECT card_catalog.card_name, card_catalog.card_label, card_genre.genre_id FROM card_catalog, card_genre WHERE card_genre.genre_id = ?";
$stmt = mysqli_prepare($conn, $query);
$stmt->bind_param('s', $_POST['card_genre']);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $row['card_name']." - ".$row['genre_id'];
echo "<br />";
}
} else {
$query = "SELECT card_catalog.card_name, card_catalog.card_label, card_genre.genre_id FROM card_catalog, card_genre";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
while ($row = mysqli_fetch_array($result)) {
echo $row['card_name']." - ".$row['genre_id'];
echo "<br />";
}
}

PHP Search results error

I have written the below code as a test , but results are not comng in under the table I have created , the table appear along the top and all the results appear down the left hand side and even if I dont add anythig in the search all teh results show.?, cant see where I am going wrong. I am not worried about the actual HTML Look as it just a test. Appreciate the help. Error is
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel= "stylesheet" href="style5.css"/>
</head>
<boby>
<div class="third_bar">
<div class="second_image">
</div>
<div class="form"><form action= "search1.php" method="post">
<input type="text" name="search" id="search_bar" placeholder="" value="Search for your whisky here" max length="30" autocomplete="off" onMouseDown="active();" onBlur="inactive();"/><input type="submit" id="search_button" value="Go!"/>
</form>
</div>
</body>
</div>
</html>
search1.php
<?php
if (isset($_POST['search'])){
include ('connect.php');
$search = $_POST['search'];
$query = "SELECT * FROM whisky_results";
$result = mysqli_query($conn, $query) or die ('error getting data');
echo "<table>";
echo "<tr> <th>Whisky Name</th> <th>Whisky Desription</th> <th>Highest Price Recorded</th> <th>Lowest Price Recorded</th> </tr>";
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<tr><td>";
echo $row['name'];
echo "</td><td>";
echo "<tr><td>";
echo $row['description'];
echo "</td><td>";
echo "<tr><td>";
echo $row['highest_price'];
echo "</td><td>";
echo "<tr><td>";
echo $row['lowest_price'];
echo "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
?>

How do I get a "blob" image to post in a comment section

First off, I am VERY new to PHP coding. I've been more than a few days getting everything to work that is working and have been watching hours of video. Yet, for the life of me, I cannot get this to "completely" function.
When I click my upload button, the author, date_time group, and the comment work fine. They are posting to the database and posting to the "GET" section when I click upload. The thumbnail on the other hand just gives the broken path image. I'm sure it's something I'm not defining correctly, but I am completely lost. I have posted my comment box form source code, connection, and functions. My database is in commentsection/comments/image. The "image" column of the database type is set to BLOB.
Please help...
SOURCE CODE:
<?php
echo "<form method='POST' enctype='multipart/form-data 'action='".setComments($conn)."'>
<input type='hidden' name='uid' value='Anonymous'>
<input type='hidden' name='date' value='".date('Y-m-d H:i:s')."'>
<label>Upload Image</label><br>
<input type='file' name='image' id='image'><br>,<br>
<textarea name='message'></textarea><br><br>
<button type='submit' name='commentSubmit'>Upload</button>
</form>";
getComments($conn);
?>
CONNECTION:
$conn = mysqli_connect('localhost','root','', 'commentsection');
if (!$conn) {
die("Connection failed:".mysqli_connect_error());
}
FUNCTIONS:
<?php
function setComments($conn) {
if (isset($_POST['commentSubmit'])) {
$uid = $_POST['uid'];
$date = $_POST['date'];
$message = $_POST['message'];
$image = $_POST['image'];
$sql = "INSERT INTO comments (uid, date, image, message) values ('$uid', '$date','$image', '$message')";
$result = mysqli_query($conn, $sql);
}
}
function getComments($conn) {
$sql = "SELECT * FROM comments ORDER BY date DESC LIMIT 10";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)){
echo "<div class='commentbox'><p>";
echo $row['uid'];
echo $row['date']."<br>";
echo "<div class='thumbnail'>";
echo "<img src='".$row['image']."'>";
echo "</div>";
echo nl2br($row['message']);
echo "<p></div>"."<br>";
}
}

duplicate messages after clicking comment button

update
Can anyone explain to me why I am getting duplicate messages instead of one?
how can I change my code so that when I type a comment and press "Comment" button, it will only display one message instead of duplicates! When I have one comment boxes it doesn't show duplicate comments, but if I have more than one then it starts duplicating!
COMMENT.INC.PHP
include 'cdbh.inc.php';
function setComments($con)
{
if (isset($_POST['commentSubmit'])) {
$uid = mysqli_real_escape_string($con,$_POST['uid']);
$date = mysqli_real_escape_string($con,$_POST['date']);
$message = mysqli_real_escape_string($con,$_POST['message']);
$sql = "INSERT INTO comments (uid, date, message) VALUES ('$uid','$date','$message')";
$result = mysqli_query($con,$sql);
}
}
function getComments($con)
{
$sql = "SELECT * FROM comments";
$result = mysqli_query($con,$sql);
while ($row=mysqli_fetch_assoc($result)) {
echo $row['uid'];
echo ":";
echo $row['message']."<br><br>";
}
}
page code
<?php
date_default_timezone_set('America/Los_Angeles');
include 'comment.inc.php';
include("connection.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="comment.css" rel ="stylesheet">
</head>
<body>
<?php
$sql="Select * from tbl_images";
$result=mysqli_query($connection,$sql);
while ($row=mysqli_fetch_array($result)) {
?>
<img src="images/<?php echo $row['images_name'] ?>" width="200px" height="200px">
<?php
echo "<form method ='POST' action ='".setComments($con)."'>
<input type ='hidden' name ='uid' value='unknown'>
<input type ='hidden' name ='date' value='".date('Y-m-d H:i:s')."'>
<textarea name='message'></textarea>
<button type ='submit' name='commentSubmit'>Comment</button>
</form>";
}
getComments($con);
?>
</body>
</html>
Maybe you are submiting all your forms instead of one..
check your database in order to know from what img comes each message.
If you have other code like javascript, you should post it.

Creating a table on HTML with information from various MySQL tables

i have a website i am constructing for a school project, in which i already have various webpages where i get tabular data from my database through the use of While and Foreach.
But on this page in question, i am attempting to retrieve data from various tables, in order for a user to choose a category, and a text and submit.
But for some reason it isn't outputting any data. If i attempt with only one table and without using the table.field method, and only typing the fields, it works.
But from what i know, to retrieve from various tables i have to do so.
Can annione help me out on this?
<html>
<head>
<script type="text/javascript" >
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
mysql_connect("localhost","root","") or die("problema na conexao");
mysql_select_db("trabalho1");
$query = "SELECT texto.titulo,texto.ID,categoria.categoria,categoria.id FROM categoria,texto";
$results = mysql_query($query) or die(mysql_error());
echo"<center>";
echo "<table border='2'>\n";
echo "<form id='formulario' name='post' method='post' onsubmit='return validar(this) action='../inserir/inseretexto.php>'";
echo "<button type='submit'>Submeter</button>";
echo "<tr><td colspan ='2'>Historico de Newsletters</td><td colspan='2'>Enviar Newsletter</td></tr>";
echo "<tr><td colspan='2'>Texto </td><td colspan='2'>Categoria</td></tr>";
while ($row = mysql_fetch_assoc($results)) {
foreach ($row as $campo=>$valor) {
if ($campo == "texto.titulo") {
echo "<tr><td>'".$valor."'</td>";
}
if ($campo == "texto.ID") {
echo "<td><input type='radio' name='nome' value='".$valor."'></td></tr>";
}
if ($campo == "categoria.categoria") {
echo "<td>'".$valor."'</td>";
}
if ($campo=="categoria.id") {
echo "<td><input type='radio' name='nome' value='".$valor."'></td></tr>";
}
}
}
echo "</form>";
echo "</table>";
echo "</center>";
?>
</body>
</html>
Added: Since both tables have a field called id, it won't let me simply put the field names, i have to also put the table name like i did. And yes, i have verified and both tables are populated with data, they work fine on other pages.
This is what I suggest (I didn't consider much code optimization).
<?php
$data = array();
mysql_connect('localhost', 'root', '') or die('problema na conexao');
mysql_select_db('trabalho1');
// Use the same field-names/aliases: id, info
$query = 'SELECT ID AS id, titulo AS info FROM texto';
$results = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_assoc($results)) {
$data[] = $row;
}
// Use the same field-names/aliases: id, info
$query = 'SELECT id, categoria AS info FROM categoria';
$results = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_assoc($results)) {
$data[] = $row;
}
?>
<html>
<head>
<script type="text/javascript">
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<center>
<table border='2'>
<form id='formulario' name='post' method='post' onsubmit='return validar(this) action='../inserir/inseretexto.php>
<tr><td colspan ='2'><button type='submit'>Submeter</button></td></tr>
<tr><td colspan ='2'>Historico de Newsletters</td><td colspan='2'>Enviar Newsletter</td></tr>
<tr><td colspan='2'>Texto </td><td colspan='2'>Categoria</td></tr>
<?php
foreach ($data as $row) {
echo '<td><input type="radio" name="nome" value="' . $row['id'] . '></td></tr>' .
'<tr><td>' . $row['id'] . '</td>';
}
?>
</form>
</table>
</center>
</body>
</html>
PS: Read about my response about double quotations. Should I use curly brackets or concatenate variables within strings?

Categories