this is probably very simple but im really new to php and js
i made a comment system for my site but i have an issue that i cant figure out
//comment section
$commentsArray = array();
$commentQuery_run = mysqli_query($con, "SELECT * FROM comments WHERE PostID='$userPostId'");
if (mysqli_num_rows($commentQuery_run) > 0) {
echo "<b id='commcount'>Comments:".mysqli_num_rows($commentQuery_run).
"</b>";
while ($commentRow = mysqli_fetch_assoc($commentQuery_run)) {
$commentID = $commentRow['id'];
$commentUsername = $commentRow['username'];
$commentUserPfpPath = $commentRow['path'];
$commentContent = $commentRow['text'];
$commentDate = $commentRow['date'];
$commentsArray[] = $commentContent;
echo "html for displaying the comments";
}
} else {
echo "<b id='commcount'>No comments! Be the first one to comment!</b>";
}
if ($isLoggedIn === true) {
echo "<form id='commForm' method='POST' action=''> <
input id = 'commTextInp'
type = 'text'
placeholder = 'Your comment...'
name = 'commentText' > < br >
<
input id = 'commSubmInp'
type = 'submit'
name = 'commentSubmit'
value = 'Post Comment' >
<
/form>";
} else {
echo "<b id='commcount'>Please Login In to comment!</b>";
}
//comment section
//coment process
if (isset($_POST['commentSubmit'])) {
if (isset($_POST['commentText']) && !empty($_POST['commentText'])) {
$postCommentUsername = $_SESSION['username'];
$postCommentPfpImg = $_SESSION['pfpimg'];
$postCommentContents = mysqli_real_escape_string($con, htmlentities($_POST['commentText'], ENT_QUOTES));
$postCommentDate = date("d/m/Y H:i");
if (!in_array($postCommentContents, $commentsArray)) {
$postCommentQuery_run = mysqli_query($con, "INSERT INTO comments VALUES('','$userPostId','$postCommentUsername','$postCommentPfpImg','$postCommentContents','$postCommentDate')");
if ($postCommentQuery_run === true) {
echo "<script> window.location.reload() </script>";
} else {
echo "<b style='color:red;'>Error while submitting comment!</b>";
}
} else {
echo "<b style='color:red;'>Please don't repeat yourself/other users!</b>";
}
} else {
echo "<b style='color:red;'>Please write something in your comment and try again</b>";
}
}
echo "</center>";
//comment process
every time i submit the form i get the "please dont repeat yourself/other users" error. why? does the window.location.reload() function also re-submit the form? or im I doing something completely wrong? and is there any better method for reloading the site? as it might be obvious i need to reload the page so that the new comment shows up. again, im really new to php/js/html so please explain why my code isnt working the way its supposed to. my guess is that the reload() method resubmits the form (excuse my bad english)
You better should place your POST-processing code in header of file, and you will be able to use header() redirect. To show error, you can use some flag; see:
// here we store all our comments
$commentsArray = [];
$commentQuery_run = mysqli_query($con,"SELECT * FROM comments WHERE PostID='$userPostId'");
while($commentRow = mysqli_fetch_assoc($commentQuery_run)){
$commentsArray[] = $commentRow;
}
//coment process
if(isset($_POST['commentSubmit'])){
if(isset($_POST['commentText']) && !empty($_POST['commentText'])){
$postCommentUsername = $_SESSION['username'];
$postCommentPfpImg = $_SESSION['pfpimg'];
$postCommentContents = mysqli_real_escape_string($con, htmlentities($_POST['commentText'], ENT_QUOTES));
$postCommentDate = date("d/m/Y H:i");
if(! array_search($postCommentContents, array_column($commentsArray, 'text')) ){
$postCommentQuery_run = mysqli_query($con,"INSERT INTO comments VALUES('','$userPostId','$postCommentUsername','$postCommentPfpImg','$postCommentContents','$postCommentDate')");
if($postCommentQuery_run === true){
header("Location: " . $_SERVER['PHP_SELF']);
}
else {
$is_error = 'ERROR';
}
}
else{
$is_error = 'DUPLICATE';
}
}
else{
$is_error = 'NO_DATA';
}
}
and next, in the old place (in the middle of page) you can show error:
if(isset($is_error)) {
switch($is_error) {
case 'DUPLICATE':
echo "<b style='color:red;'>Please don't repeat yourself/other users!</b>";
break;
case 'NO_DATA':
echo "<b style='color:red;'>Please write something in your comment and try again</b>";
break;
default:
echo "<b style='color:red;'>Error while submitting comment!</b>";
}
}
// ...........
// PRINT ALL COMMENTS HERE
if(count($commentsArray)>0){
echo "<b id='commcount'>Comments:" . count($commentsArray) . "</b>";
foreach($commentsArray as $comment){
// $comment contains all your db-fields
echo "html for displaying the comments";
}
}
else{
echo "<b id='commcount'>No comments! Be the first one to comment!</b>";
}
every time i submit the form i get the "please dont repeat yourself/other users" error. why?
if(! in_array($postCommentContents, $commentsArray))
for first comment is true because:
if(mysqli_num_rows($commentQuery_run) > 0)
for first comment is false and commentsArray is empty.
Related
My ajax code:
$('#name').keyup(function() {
var usercheck = $(this).val();
$('#nameAvailability').html('<img src="../SPR/assets/img/loading.gif" width="300" />'); //this part is working
$.post("../SPR/backend/username_availability_check.php", {user_name: usercheck} ,
function(data)
{
if (data.status == true)
{
$('#nameAvailability').parent('div').removeClass('has-error').addClass('has-success');
} else {
$('#nameAvailability').parent('div').removeClass('has-success').addClass('has-error');
}
$('#nameAvailability').html(data.msg); // not working
} ,'json');
});
My php code:
<?php
require("connection.php");
if(isset($_POST['user_name']) && $_POST['user_name'] != '')
{
$response = array();
$username = mysqli_real_escape_string($conn,$_POST['user_name']);
echo $username;
$sql = "select username from users where users.username='".$username."'";
$res = mysqli_query($conn, $sql);
$count = mysqli_num_rows($res);
if($count > 0)
{
$response['status'] = false;
$response['msg'] = 'Username already exists.';
}
else if(strlen($username) < 6 || strlen($username) > 15){
$response['status'] = false;
$response['msg'] = 'Username must be 6 to 15 characters';
}
else if (!preg_match("/^[a-zA-Z1-9]+$/", $username))
{
$response['status'] = false;
$response['msg'] = 'Use alphanumeric characters only.';
}
else
{
$response['status'] = true;
$response['msg'] = 'Username is available.';
}
echo json_encode($response);
echo $response;
}
?>
I have used session_start() in my index.php where user inputs his username in the input field with id 'name'
I have checked the given php code by running it individually by passing a custom username from the database and it works fine. So probably there's something wrong with the ajax code.
It is impossible to tell what your clientside code does based on what is posted here.
But in general, for debugging and to check if your serverside code works, do this:
Make a simple form, that POSTS to your PHP script.
<form action="whateveryourphpcodeisnamed.php" METHOD="POST">
<INPUT TYPE="TEXT" NAME="user_name">
<INPUT TYPE="SUBMIT" VALUE="TEST THE USERNAME">
</FORM>
And see what it says back to you.
Be sure to activate error_reporting during development.
I'm very new to PHP and JavaScript and I'm stuck. I spent a good 7 hours so far trying to figure this one out but I just do not know what or how to do it. So in my application, when you try to add a new row to my table, I have a html form to get the data. When you enter the data into the form, and press submit, it prompts for a password, and if the correct password is put in, it submits the form. It work just as I wanted it, here is what I have:
<button onclick="password()" type="button">Create New Hero</button>
<div>
<a id="discl">*-Required Fields</a>
</div>
<script>
function password(){
var password = prompt("Please Enter the Admin Password");
if(password != "shaun"){
alert("Wrong Password");
}
else{
if(validation()){
document.getElementById("form_id").submit();
}
else{
alert("One or more required fields were left empty, or tried to use <script>");
}
}
}
function validation(){
var f = document.getElementById("f_name").value;
var l = document.getElementById("l_name").value;
var d = document.getElementById("dob").value;
var a = document.getElementById("alias").value;
if(f == "" || l == "" || d == "" || f.includes("<script>") || l.includes("<script>") || a.includes("<script>")){
return false;
}
else{
return true;
}
}
</script>
Now I also have an edit and delete on my table. My problem is that with edit and delete, they are in tags with an href, and they are not buttons. This is how they originally looked when it worked without asking for a password:
echo "<a href='./edit.php?id={$row['id']}'>edit</a>";
So based on which row of the table it was, where you clicked edit or delete, based on the row's id from the database, it would edit or delete that table. Now my problem is I don't know how to properly set up the function so it asks for the password and redirect to the right url. This is what I have right now:
foreach($results as $row){
echo "<tr>";
echo "<td>{$row['first_name']}</td>";
echo "<td>{$row['last_name']}</td>";
echo "<td>{$row['date_of_birth']}</td>";
echo "<td>{$row['alias']}</td>";
echo "<td>{$row['active']}</td>";
echo "<td>{$row['hero']}</td>";
echo "<td>";
echo "<a href='./edit.php?id={$row['id']}'>edit</a>";
echo " | ";
echo "<a href='javascript: password()'>delete</a>";
echo "</td>";
echo "</tr>";
}
?>
<script type="text/javascript">
function password(){
var password = prompt("Please Enter the Admin Password");
if(password != "shaun"){
alert("Wrong Password");
}
else{
window.location.replace("./delete.php?id=<?php echo $row['id']; ?>");
}
}
</script>
The problem with this is that no matter which delete I click on on my table, it always deletes the last one, because the ID it's getting out after the url is the last available ID from my database. I'm not sure if I'm just missing something small, or I'm completely on the wrong path but any help would be appreciated because I'm very lost. Thank you
Will not comment on any security issues here, just the logic. You need to pass $row['id'] during PHP loop to your JS password() function that you want to use afterwards:
<?php
foreach ($results as $row) {
echo "<tr>";
echo "<td>{$row['first_name']}</td>";
echo "<td>{$row['last_name']}</td>";
echo "<td>{$row['date_of_birth']}</td>";
echo "<td>{$row['alias']}</td>";
echo "<td>{$row['active']}</td>";
echo "<td>{$row['hero']}</td>";
echo "<td>";
echo "<a href='./edit.php?id={$row['id']}'>edit</a>";
echo " | ";
echo "<a href='javascript: password(".$row['id'].")'>delete</a>";
echo "</td>";
echo "</tr>";
}
?>
<script type="text/javascript">
function password(delId) {
var password = prompt("Please Enter the Admin Password");
if (password != "shaun") {
alert("Wrong Password");
} else {
window.location.replace("./delete.php?id="+delId);
}
}
</script>
Ignoring the blatant security issue, I suggest this
<a href='#' class='edit' data-id='<?= $row['id'] ?>'>edit</a> |
<a href='#' class='delete' data-id='<?= $row['id'] ?>'>delete</a>
using
window.addEventListerner('load',function() {
document.querySelector('table').addEventListerner('click',function(e) {
e.preventdefault(); // stop the link
const tgt = e.target, id = tgt.getAttribute("id");
if (tgt.classList.contains("edit") {
location = '/edit.php?id='+encodeURIComponent(id);
}
else if (tgt.classList.contains("delete") {
let password = prompt("Please Enter the Admin Password");
if (password === "shaun") {
location.replace('/delete.php?id='+encodeURIComponent(id)=;
}
else {
alert("Wrong Password");
}
}
})
})
It is the target request, not the calling page which requires authentication, otherwise anybody could call the ./delete.php?... url and delete a row in the database.
This is usually done by maintaining a session, which remembers a login of the user. The delete.php request can then check whether the user is already logged in / has admin privileges, or demand the password when necessary.
When I run my ajax action the return text has a return character as the first char. However the echo text used to send is fixed with no spaces or returns. and if i alert the return text there is no carraige return.
I'm running the code from my Godaddy host, running MSQL with PHP5
innerHTML that crates the button - _("comment_"+sid).innerHTML += '<div id="reply_'+rid+'" class="reply_boxes"><div><b>Reply by you just now:</b><span id="srdb_'+rid+'">remove</span><br />'+data+'</div></div>';
_("replyBtn_"+sid).disabled = false;
_(ta).value = "";
js code -
function deleteComment(commentid,commentbox){
var conf = confirm("Press OK to confirm deletion of this status and its replies");
if(conf != true){
return false;
}
var ajax = ajaxObj("POST", "php_parsers/comments_system.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var deleteOk = ajax.responseText; //This is retuning a return carraige
if(deleteOk = "1"){
_(commentbox).style.display = 'none';
_("replytext_"+commentid).style.display = 'none';
_("replyBtn_"+commentid).style.display = 'none';
} else {
alert(ajax.responseText);
}
}
}
ajax.send("action=delete_comment&commentid="+commentid);
}
This is the PHP code
if (isset($_POST['action']) && $_POST['action'] == "delete_comment"){
if(!isset($_POST['commentid']) || $_POST['commentid'] == ""){
mysqli_close($db_conx);
echo "comment id is missing";
exit();
}
$commentid = preg_replace('#[^0-9]#', '', $_POST['commentid']);
// Check to make sure this logged in user actually owns that comment
$sql = "SELECT author_name FROM comments WHERE parent_id=$commentid LIMIT 1";
$query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$author_name = $row[author_name];
}
if ($author_name == $log_username) {
mysqli_query($db_conx, "DELETE FROM comments WHERE parent_id=$commentid");
mysqli_close($db_conx);
echo "1";
exit();
}else{
echo "$sql - $author_name";
}
}
So I have had to edit my code at the moment to use the int values as it would seem the IF statements still match the return value, but if i use a text return then it does not match. I have an almost identical bit of code to create the comment but this work as expected.
In a particular php file iam using a header and an alert box before it executes header, but its neglecting alert and executing header directly..!!please help me resolving this...!!pardon if i went wrong somewere.
.php
<?php
header('location: formprofile.php');
session_start();
require_once 'DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => false);
if (!empty($_POST['salutation']) && !empty($_POST['fname']) && !empty($_POST['lname']) && !empty($_POST['dob']) && !empty($_POST['mobile']) && !empty($_POST['country']) && !empty($_POST['state']) && !empty($_POST['city']) && !empty($_POST['pin'])){
/*
if required include seperate validation
for some fields which require validation
*/
// receiving the post params
$salutation = ($_POST['salutation']);
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$dob = trim($_POST['dob']);
$mobile = trim($_POST['mobile']);
$country = trim($_POST['country']);
$state = trim($_POST['state']);
$city = trim($_POST['city']);
$pin = trim($_POST['pin']);
/*
validation process
starts from here
*/
// validate your email address
if(strlen($mobile) == 10){
if($db->isMobileNumberExisted($mobile)) {
//user already existed
$response["error"] = true;
$response["error_msg"] = "user already existed with" . $mobile;
echo json_encode($response);
}else{
// create a new user
$user = $db->storeUser($salutation, $fname, $lname, $dob, $mobile, $country, $state, $city, $pin);
if ($user) {
// user stored successfully
$response["error"] = false;
$_SESSION['fullname'] = $user['fullname'];
$_SESSION['vault_no'] = $user['vault_no'];
$message = "Registration successful";
echo "<script type='text/javascript'>alert('$message');</script>";
} else {
// user failed to store
$response["error"] = true;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
}else{
//invalid mobile number
$response["error"] = true;
$response["error_msg"] = "PLEASE ENTER VALID MOBILE NUMBER!";
echo json_encode($response);
}
}else{
//missing the required fields
$response["error"] = true;
$response["error_msg"] = "Please fill all the required parameters!";
echo json_encode($response);
}
?>
header('location: formprofile.php');
This line is redirecting the page to formprofile.php and that causes to ignore everything below it. Just remove that line or if you want redirect after execution, then move it to the end of the file and do not echo or print anything before it.
But if you want to have some alert before redirecting to other page don't use header() for redirect. Add this JavaScript at the end of the file.
?>
<script>
alert("your message");
document.location = "formprofile.php";
</script>
i have a small doubt.. i posted my delete.php page coding here.
if(isset($_GET["id"]))
{
$meal_query = mysql_query("DELETE FROM ebmealplans WHERE MealPlanID = '$id'");
echo mysql_error();
$room_query = mysql_query("DELETE FROM ebroomtypes WHERE RoomTypeID = '$id'");
echo mysql_error();
$tariff_query = mysql_query("DELETE FROM ebvouchertariffs WHERE VoucherID_Fk = '$id'");
echo mysql_error();
$query = mysql_query("DELETE FROM ebvouchers WHERE VoucherID = '$id'");
echo mysql_error();
if($query)
{
echo "<script> alert('Voucher deleted successfully'); </script>";
}
else
{
echo "<script> alert('Failed to delete this voucher'); </script>";
}
mysql_close($link);
echo "<script> location.href='managevouchers.php'; </script>";
}
here i am delete some user datas using this php coding. it worked perfectly. i created four separate tables for store the records. if deletion function was successfully completed i want to show the alert message to users "Deleted Successfully". you can see in my coding i'm just show the alert message for only one $query. i tried another method..
if($query)
{
alert function
}
else
{
alert function
}
if($meal_query)
{
alert function
}
else
{
alert function
}
if($room_query)
{
alert function
}
else
{
alert function
}
if($tariff_query)
{
alert function
}
else
{
alert function
}
it show the alert message four times. i know multiple alert functions annoying the users. my question is how to show the single alert message for mysql multiple queries?
Just store the msg pieces in some variable, and alert them all finally.
$msgs = array ();
if ($query) {
$msgs [] = '.....';
} else {
$msgs [] = '...';
}
if ($meal_query) {
$msgs [] = '....';
} else {
$msgs [] = '...';
}
//....
if ($msgs) {
//join the msgs with line break
$alert = join ( "\n", $msgs );
//json encode will make sure it's like "..string..", no quotes problem
echo '<script> alert(', json_encode ( $alert ), '); </script>';
}