Using PHP to delete comments from the database - php

My site is an admin login site, therefore users cannot register. However they can post comments to the site. I have delete buttons on the comments but didn't realise that anybody can then delete anybodies comments. How can I change this so when the admin is logged in they are able to delete inappropriate comments (if any) and get rid of the delete button from the general public.
This is my Comment.php code with the delete button function in there:
<?php
session_start();
require_once 'templates/open.php';
require_once 'connect.php';
require_once 'functions/cleanstring.php';
require_once 'functions/encrypt.php';
?>
Another code file:
<?php
$db_hostname = 'localhost';
$db_database = 'cs12e2g_MyFirstDB'; //'Your database name'
$db_username = 'cs12e2g_DBuser'; //'your username';
$db_password = 'vtjppqs7'; //'Your password';
$db_status = 'not initialised';
$db_server = mysqli_connect($db_hostname, $db_username, $db_password);
$db_status = "connected";
if (!$db_server){
die("Unable to connect to MySQL: " . mysqli_connect_error());
$db_status = "not connected";
}
// Includes and variables always required
require_once 'recaptcha/recaptchalib.php';
require_once 'functions/cleanstring.php';
$privatekey = "6Lem4-gSAAAAADsaa9KXlzSAhLs8Ztp83Lt-x1kn";
$publickey = "6Lem4-gSAAAAAMHLAVbieIknMtUZo71ZKzzCkoFN";
mysqli_select_db($db_server, $db_database);
$str_message = "";
if (!$db_server){
die("Unable to connect to MySQL: " . mysqli_connect_error());
}else{
if(isset($_GET['delete'])){
$deleteq="DELETE FROM comments WHERE ID={$_GET['delete']} LIMIT 1";
$deleter=mysqli_query($db_server, $deleteq);
IF($deleter){
echo"<p>That message was deleted!</p>";}}
//Test whether form has been submitted
if(trim($_POST['submit']) == "Submit"){
//Handle submission
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
$str_message = "The reCAPTCHA wasn't entered correctly. Go back and try it
again.
(reCAPTCHA said: " . $resp->error . ")";
} else {
// Your code here to handle a successful verification
$comment = $_POST['comment'];
if($comment != ""){
$query = "INSERT INTO comments (comment) VALUES ('$comment')";
mysqli_query($db_server, $query) or die("Comment insert failed: " .
mysqli_error($db_server) );
$str_message = "Thanks for your comment!";
}else{
$str_message = "Invalid form submission";
}
}
}
//Create page with or without submission
$query = "SELECT * FROM comments";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server) );
while($row = mysqli_fetch_array($result)){
$ID= $row['ID'];
$str_result .= "<p><em>Comment $j (" . $row['commDate'] .
")</em><br /> " .$row['comment'] . "</p>
<a href ='commentnow.php?delete=$ID
'>Delete</a><hr />";
}
mysqli_free_result($result);
}
?>
<h1>What do you think?</h1>
<p><h5>Did you find everything you wanted? Please comment below:<h5></p>
<form action="commentnow.php" method="post">
<textarea rows="10" cols="50" name="comment"></textarea><br />
<?php echo recaptcha_get_html($publickey); ?>
<input type="submit" name="submit" value="Submit" />
</form>
<span style="color:#FF0000;">
<?php echo $str_message; ?></span>
<hr />
<h2>Comments:</h2>
<?php echo $str_result; ?>
</div>
<?php
require_once 'templates/close.php';
?>
I have a members.php page which corresponds to when the admin logs in (they are the only ones that can access this page) would the delete button code have to go in here? so they are the only ones that can use the function? If so where would it go, and how?

Restrict the delete button to show only for the admin. Also this would mean that you somehow identify if the logged in user is an admin.
if ($is_admin) {
// Code to display button
}
Also in the backend check if the logged in user is admin
if ($is_admin) {
// Code to delete comment
delete_comment();
}

and you welcome to php.
You have that identify the users that enter in your application.
Using database or arrays or files or variables etc etc.
If permission is equal to admin or editor (For example) allow delete.
For example
if( $login == 'admin' ){
// Allow action
}
My you understand?
(My English is bad, sorry)

Related

Submitting HTML form to database using PHP and it brings back php page instead of submitting

I'm trying to connect HTML form to SQL database using PHP but when I hit submit, it is giving me PHP page.
This is HTML code
<form method="post" action="connect.php">
Username : <input type="text" name="username"><br><br>
Password : <input type="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
Here is PHP code
$username = filter_input(INPUT_POST, 'username');
$password = filter_input(INPUT_POST, 'password');
if (!empty($username)){
if (!empty($password)){
$host = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "youtube";
// Create connection
$conn = new mysqli ($host, $dbusername, $dbpassword, $dbname);
if (mysqli_connect_error()){
die('Connect Error ('. mysqli_connect_errno() .') '
. mysqli_connect_error());
}
else{
$sql = "INSERT INTO account (username, password)
values ('$username','$password')";
if ($conn->query($sql)){
echo "New record is inserted sucessfully";
}
else{
echo "Error: ". $sql ."
". $conn->error;
}
$conn->close();
}
}
else{
echo "Password should not be empty";
die();
}
}
else{
echo "Username should not be empty";
die();
}
I expect to get 'New record is inserted successfully' or 'error'
In php, once you done with the various processes in a page, you need to write a redirect otherwise it will just die waiting for the next action. At the moment, after its done executing, you it will just echo if successful and die() is failed as per your conditions.
Add:
if ($conn->query($sql)){
header("Location: /path_of_page.html");
}
The same can be applied in the }else (){} statements.
Edit: I forgot to mention, avoid using die and echo in intermediate (processing) pages since they will output on the raw php during executions. Rather, put them in an array and pass them to the UI as parameter.

Isset function not working

I'm working on PHP at the moment.
I have a form seen below with a submit button.
I then created a function below also.
As you can see the first thing the function does is checked the submit button is pressed, but it goes into this if upon loading the page(i don't need to press the button), and it out puts the "Entry Submitted" p tag autmoatically, where it shouldn't even be entering the first if statement.
Any help appreciated,
<p>
<input type="submit" name="Submit" id="Submit" value="Submit" tabindex="100"/>
<br />`enter code here`
</p>
</form>
<?php
if (isset($_POST['Submit'])){
$conn_error = 'Could not connect.';
$mysql_host = 'localhost';
$mysql_user = 'auser';
$mysql_pass = 'auser';
$mysql_db = 'ourwebdb';
// Connect to database
if (!#mysql_connect($mysql_host, $mysql_user, $mysql_pass) || !#mysql_select_db($mysql_db)) {
die ($conn_error);
}else {
//echo 'Connected';
// Perform database insert
$name = $_POST["Name"];
$email = $_POST["email"];
$teamSupported = $_POST["radioGroup"];
$comment = $_POST["comment"];
$query = "INSERT INTO visitors (Name, Email,[Supported Team], Comment)
VALUES ('{$name}', '{$email}', '{$teamSupported}', '{$comment}')";
$result = mysql_query($query);
if ($result) {
// Success
$id = mysql_insert_id();
echo '<p> Entry Submitted</p>';
// Do something
} else {
die ("Database query failed. ". mysql_error());
}
}
}
mysql_close();
Change your 1st PHP line
if (isset($_POST['Submit'])){
to
if (isset($_POST['Submit']) && $_POST['Submit']=='Submit' ){
there is nothing wrong in your code (except cut out portion of form). so there is two possible scenario 1. you are refreshing browser url with re-submit 2. there are some onload javascript/jquery function which submit the page (form.submit()..)
Solution for 1. is easy just open the url in new tab. for scenario 2. you need to check Or submit your full code here

update an existing file in mysql database with new file

<form action="insertresubmittedpaper.php" autocomplete="on" enctype="multipart/form-data" method="post">
<h1>Re-Submit Paper</h1>
<p>
<input type="file" name="uploaded_file"><br>
</p>
<br>
<br>
<center>
<p class="submit button">
<input type="submit" value="Submit">
</p>
</center>
</form>
Hello I'm working on a project where I need to insert a file into database, and after that I have an option where the user can update the existing file in database using a form and when once updated it will be redirected to another page.
I'm using PHP , mysql.
The Problem is a new file is not being updated into the database, but it is redirecting to another page.
Here i'm posting my code. Please suggest me necessary changes.
<?php
session_start();
if(isset($_SESSION['username']))
{
echo "<div id='User'>Welcome: " . $_SESSION['username'] . "</div>";
}
else
{
echo "<div id='Guest'>Welcome: Guest </div>";
}
/*
Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password)
*/
if(isset($_FILES['uploaded_file'])) {
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
$link = mysqli_connect("localhost", "kuda", "secret", "researchcloud");
// Check connection
if($link === false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$UserName=$_SESSION['username'];
$Subject = mysqli_real_escape_string($link, $_POST['subject']);
$Category = mysqli_real_escape_string($link, $_POST['category']);
$Journal = mysqli_real_escape_string($link, $_POST['journal']);
$mime = mysqli_real_escape_string($link, $_FILES['uploaded_file']['type']);
$data = mysqli_real_escape_string($link, file_get_contents($_FILES ['uploaded_file'] ['tmp_name'] ));
// attempt insert query execution
$sql = "UPDATE rc_ijai set FullPaper='$data', mime='$mime' where A1Email='$UserName' and Journal='$Journal'";
if(mysqli_query($link, $sql))
{
header('Location:authorprofile.php');
}
else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
}
}
else {
echo 'An error occurred while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
?>
Don't use mysqli_query() to check that query has been executed or not. specially for insert and update queries. Because for update query some times a query will get executed and non of the row will get updated. So for insert and update check the number of rows affected after the query execution. After checking this You can easily solve it.

Could not update data: Access denied for user 'xxxx'#'localhost' (using password: NO)

Okay so I have been trying to fix this issue for a few hours now and have had no luck. Hopefully one/some of you brilliant programmers can aid in getting this code working properly. Currently, I have two databases set up: Users and AvatarDB. In Users, I have a table called userinfo and in AvatarDB I have a table called Avatars. What I am trying to do is have Users upload an avatar which will be stored in the AvatarDB and will have the same ID as the user ID. (For simplicity and troubleshooting purposes, I am currently just asking the user to enter their ID into the form, however once I get this code working will then have the code retrieve their user ID from my Users database) Unfortunately, when I try to upload an avatar I get the error in the title. Here is my code for connecting to the database:
$servername = "localhost";
$username = "xxxx"; (I put the username here)
$password = "xxxx"; (I put the password here)
// Create connection
$db = mysql_connect($servername, $username, $password);
// Check connection
if (!$db) { die("Connection failed: " . mysql_connect_error()); }
Then, my upload.php file is as follows:
<?PHP include(connect.php) ?>
<form id="avatar" name="avatar" method="post" action="submitAvatar.php" enctype="multipart/form-data">
ID:
<input type="text" id="memberId" name="memberId">
Upload Avatar:
<input type="file" onchange="load_image(this.id,this.value);" id="userAvatar" name="userAvatar">
<br><br>
<input type="submit" value="Update Avatar" id="updateAvatar" name="updateAvatar">
</form>
My submitAvatar.php is as follows:
<?PHP include(connect.php);
if($_SERVER['REQUEST_METHOD'] == "POST" && $_POST['updateAvatar'] == 'Update Avatar') {
if($_POST['memberId']=="") {
echo "Member id is required";
} else {
$memberId = $_POST['memberId'];
$updtDate = date("Y-m-d : H:i:s", time());
$allowedExts = array("gif", "jpeg", "jpg", "png", "bmp");
$temp = explode(".", $_FILES["userAvatar"]["name"]);
if($_FILES['userAvatar']['size']>0) {
if (in_array(strtolower($temp[1]), $allowedExts)) {
$picNm = uniqid().".jpg";
$path="memberAvatars/".$picNm;
if(move_uploaded_file($_FILES['userAvatar']['tmp_name'],$path)) {
$sql = "UPDATE Avatars ". "SET name = $picNm ". "WHERE memberId = $memberId" ;
mysql_select_db('AvatarDB');
$retval = mysql_query( $sql, $db );
if(! $retval ) { die('Could not update data: ' . mysql_error()); }
echo "Updated data successfully\n";
mysql_close($db);
} else {
echo "Error1.";
}
} else {
echo "Invalid type.";
}
}
}
}
?>
Anyone have any idea why I'm getting the following error?
Could not update data: Access denied for user 'xxxx'#'localhost' (using password: NO)
Thank you in advance!
Here are my ideas on this issue. No need to put <?PHP include(connect.php) ?> in upload.php unless your actually doing a query there which it doesn't look like. It's already included in submitAvatar.php.
I believe the issue is in the syntax of your query or the way you have included your connection script. You may need to use quotes inside your include.
<?PHP include('connect.php') ?>
Also, try changing
$sql = "UPDATE Avatars ". "SET name = $picNm ". "WHERE memberId = $memberId" ;
to
$sql = "UPDATE Avatars SET name = $picNm WHERE memberId = $memberId";
Alternatively, if you want it quoted, the correct format would be.
$sql = "UPDATE Avatars SET name = '".$picNm."' WHERE memberId = '".$memberId"'";
EDIT:
After looking more closely at your code, I believe the problem lies here:
mysql_select_db('AvatarDB');
$retval = mysql_query( $sql, $db );
Looks like you've got them switched, try
mysql_select_db('AvatarDB', $db);
$retval = mysql_query($sql);

PHP error - mysqli_query() expects parameter 1 to be mysqli, null given

I can't seem to correct my php error having looked at their answers and corrections. This is the error I get when the page is refreshed on the internet:
mysqli_query() expects parameter 1 to be mysqli, null given…
<?php
session_start();
if (!isset($_SESSION['logged'])){
$_SESSION = array();
header('location: home_start.php'); //your login form
require_once("functions.php");
include_once("home_start.php");
$db_hostname = 'xxxx';
$db_database = 'xxx'; //'Your database name'
$db_username = 'xxx'; //'your username';
$db_password = 'xxx'; //'Your password';
$db_status = 'not initialised';
$str_result = ' ';
$str_options = ' ';
$db_server = mysqli_connect($db_hostname, $db_username, $db_password);
$db_status = "connected";
$db_select = mysqli_select_db($db_server, $db_database);
}
//EXISTING DATABASE CONNECTION CODE
//if (!$db_server){
//die("Unable to connect to MySQL: " . mysqli_connect_error($db_server)); }else{ $db_status = "not connected";
//NEW SUBMISSION HANDLING CODE HERE
//if(trim($_POST['submit']) == "Submit"){
//}//EXISTING CODE (to create the options list) HERE...
//}
//require_once('recaptcha/recaptchalib.php');
//$privatekey = " 6Lem4-gSAAAAADsaa9KXlzSAhLs8Ztp83Lt-x1kn";
//$resp = recaptcha_check_answer ($privatekey,
//$_SERVER["REMOTE_ADDR"],
//$_POST["recaptcha_challenge_field"],
//$_POST["recaptcha_response_field"]);
//$message = "";
//if (!$resp->is_valid) {
//$message = "The reCAPTCHA wasn't entered correctly. Go back and try it again. (reCAPTCHA said: " . $resp->error . ")";
//} else {
// ADD YOUR CODE HERE to handle a successful ReCAPTCHA submission // e.g. Validate the data
//$unsafe_name = $_POST['fullname'];
//}
//$message .= "Thanks for your input $unsafe_name !";
//echo $message;
if (isset($comment) && $comment == '') {
$bedrooms = $_POST['bedrooms'];
$bedrooms = clean_string($db_server, $year);
$comment = clean_string($db_server, $_POST['comment']);
}
else {
$query1 = "INSERT INTO comments (comment) VALUES ('$comment')";
$result = mysqli_query($db_server, $query1); if(!result){ die("Insert failed: " . mysqli_error($db_server));
}
$message = "Thanks for your comment";
}
function getPosts(mysqli $db_select){
$query1 = "SELECT * FROM comments";
$result1 = mysqli_query($db_server, $query1);
while($array = mysqli_fetch_array($result1)){
$comments = date('d/m/Y', strtotime($array['commDate'])) . "<p>" . $array['comment'] . "</p><br/>";
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="home.css" rel="stylesheet" type="text/css"/>
<title>Home</title>
</head>
<body>
<div id="middle">
<h2><strong>HELLO!</strong></h2>
<h2>Welcome to <strong>Cosy Cribs</strong> website!</h2>
<p>This website combines all the possible lettings available to YOU from the most prefered letting companies in the great city of Leeds!</p>
<p>It was recognised that when students attempt to let a house for the next year, there were far too many different websites and companies visit; making the whole ordeal of finding a house more stressful then needs be!</p>
<p>We, at <strong>Cosy Cribs</strong>, decided that your lives needed to be made easier, and so we announce a website that provides you with all of the lettings from these different companies - all on one website - and links to the house you like.</p>
<h2>ENJOY!</h2>
</div>
<form id="comments" action="home.php" method="post">
<select name="comments">
</select>
<h1>Do you have a comment on preferred company or number of bedrooms?</h1>
Comment: <textarea rows="2" cols="30" name="comment"></textarea>
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
</body>
</html>
Seems like you are overwriting your $db_server on the line that reads:
$db_server = mysqli_query($db_server, $query1) or
die("Insert failed: " . mysqli_error($db_server));
So you should change that to be another variable like $result1:
$result1 = mysqli_query($db_server, $query1) or
die("Insert failed: " . mysqli_error($db_server));
That said, are you actually connecting via $db_server anywhere else in your code? Look out for errors similar to what I just pointed out.
your $db_server is null which should a valid mysqli instance. this indicates either database connection failed or you didn't initialize $db_server or you overwritten it and looks like last option is true.
$db_server = mysqli_query($db_server, $query1)
this overwrites $db_server.
Insted of $db_server use $db_select. This may work as your $db_server variable does not have a connection to database. Its just a connection to server.

Categories