0
Hello...
Well, supposing a user wants to comment on any post. The system should:
Check if the user is logged in, otherwise he will receive a script "you must be logged in to comment".
If the user is logged in, then you must take that user’s id and pass to
autor_coment
(which is aFK
table of comments)
That’s it. As I’m starting out and I couldn’t find any examples of codes like this, I decided to ask for help here. However, when I register the comment I can not leave autor_coment
null, since it is a FK
. So, I wanted to get the id of the logged-in user and pass to autor_coment
.
In short... when I register a comment I can’t leave this to FK
autor_coment
null. So, I want to pass the value of the logged in user id to this FK
.
Until then, I have this code to register comments:
<?php
if(isset($_POST['comentar'])){
$autor_coment = trim(strip_tags($_POST['autor_coment']));
$comentario = trim(strip_tags($_POST['comentario']));
if(empty($autor_coment)){
echo "<script>alert('Preencha todos os campos para comentar.'); history.back();</script>";
}elseif(empty($comentario)){
echo "<script>alert('Preencha todos os campos para comentar.'); history.back();</script>";
}else{
$insert = "INSERT into comentarios (autor_coment, comentario) VALUES (:autor_coment, :comentario)";
try{
$result = $conexao->prepare($insert);
$result->bindParam(':autor_coment', $autor_coment, PDO::PARAM_STR);
$result->bindParam(':comentario', $comentario, PDO::PARAM_STR);
$result->execute();
$contar = $result->rowCount();
if($contar>0){
echo "<script>alert('Seu comentário foi enviado com sucesso!')</script>";
header("Location: ../index.php");
}else{
echo "<script>alert('Erro! Não foi possível comentar')</script>";
}
}catch(PDOException $e){
echo $e;
}
}
}
?>
<br>
<form action="" method="post" enctype="multipart/form-data">
<p>
<input
style="width: 400px;"
type=""
name="id"
required
placeholder="ID">
<br><br>
<input
style="width: 400px; height: 150px;"
type="text"
id="comentario"
name="comentario"
value=""
required
placeholder="Digite seu comentário"
/>
<br>
<a style="padding-left: 280px;">
<input
style="width:120px; height:40px; background:#333; color:white; border:none;"
type="submit"
name="comentar"
class="w3-button w3-black w3-section"
value="Comentar"
/>
</p></a>
</form>
I’m getting the user ID in the comment and I’m not checking whether the user is logged in or not. So these are two problems that I have no idea how to solve.
You already authenticate the user?
– Giovanni Nunes
Yes, user authentication has been done.
– Giovana
Then, you must have the user ID registered in the session and it is this value that you will use in the variable
$autor_coment
. At the same time display the comments part if the user is authenticated, otherwise type the "you need to be logged in to comment".– Giovanni Nunes
Okay, I’ll try that. Thank you!
– Giovana