I am working on a comment system & I created a page that admins can be able to delete comments. I have coded everything & it seems to be right but I don't know why it's not working at all...
Here's the code to the admins page:
<html>
<head>
<title>Admins Page</title>
</head>
<body>
<?php
function getCM(){
global $con;
$get_comment = "select * from product_comments where type='0'";
$run_comment = mysqli_query($con, $get_comment);
while($row_comment = mysqli_fetch_array($run_comment)){
$cmid = $row_comment["id"];
$cmcode = $row_comment["productcode"];
$cmemail = $row_comment["email"];
$cmname= $row_comment["name"];
$cmcomment = $row_comment["comment"];
$cmdate = $row_comment["modified_date"];
$cmtime = $row_comment["modified_time"];
$cmtype = $row_comment["type"];
echo "
<div class='container'>
<div id='table' class='table-editable'>
<span class='table-add glyphicon glyphicon-plus'></span>
<table class='table'>
<tr>
<th>Comment ID #$cmid</th>
</tr>
<tr>
<td contenteditable='true'>$cmcomment</td>
<td>
<span class='table-remove glyphicon glyphicon-remove'></span>
</td>
<td>
<a href='delete.php?id=$cmid'>Delete</a>
</td>
</tr>
</div>
";
}
}
?>
</body>
</html>
And here's the code to delete.php page:
<?php
session_start();
if (!isset($_SESSION["manager"])) {
header("location: admin_login.php");
exit();
}
require '../php_includes/init/db_conx.php';
require '../functions/func.php';
if (isset($_GET['cmid'])){
$comment_id = $_GET['cmid'];
mysqli_query("DELETE FROM product_comments WHERE id='$comment_id'") or die(mysql_error());
echo "<script>alert('Comment has been deleted!')</script>";
header("Location: product_comments.php");
}
?>
Please if you know what's my problem please let me know that...
There are a few things wrong here.
You didn't connect to your query mysqli_query("DELETE...
That function requires a database connection parameter be passed.
Consult: http://php.net/manual/en/mysqli.query.php
Then mysql_error() that mysql_ function does not mix with anything other than its own API, use mysqli_error($con), assuming a successful connection with mysqli_ and $con as its variable.
Consult: http://php.net/manual/en/function.mysqli-connect.php
Your present code is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements.
On the PHP side:
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
should there be errors elsewhere in your code.
which there is, in this part of your code:
echo "<script>alert('Comment has been deleted!')</script>";
header("Location: product_comments.php");
You are outputting before header, and need to remove the echo and adding exit; for the header.
Consult: How to fix "Headers already sent" error in PHP
Then this:
<a href='delete.php?id=$cmid'>Delete</a>
You are using ?id and referencing the $_GET['cmid'] array.
That bit ^ about the "id" is called "Teach a person HOW to fish".
Footnotes:
I have no idea where and how you are calling the getCM() function.
the error you have is
$comment_id = $_GET['cmid'];
change it to this
$comment_id = $_GET['id'];
toexplain whz
<a href='delete.php?id=$cmid'>Delete</a>
U called the cmid not id. hence u need to get id
Related
I am having a problem trying to display the username on the profile page from the $_GET, the session is created but unable to display the username on the profile page.
<?php include("template/header.php");
include("requires/connection.php"); ?>
<?php
if(isset($_GET['u'])) {
$username = mysqli_real_escape_string($_GET['u']);
if(ctype_alnum($username)) {
// Check user exists
$check = mysqli_query("SELECT username FROM users WHERE username='$username'");
if(mysqli_num_rows($check)===1) {
$get = mysqli_fetch_assoc($check);
$username = $get['username'];
}
else {
echo "<h2>User doesn't exist</h2>";
exit();
}
}
}
?>
<div class="profile-content-container">
<h1>Profile <?php echo "$username"; ?></h1>
<p>Welcome</p>
</div><!-- end of profile-content-container -->
<div class="profileMenu">
<div id="leftsideMenu">
<ul>
<li>Home</li>
<li>My Profile</li>
<li></li>
<li></li>
<li>Logout</li>
</ul><!-- end of menu -->
</div><!-- end of leftsideMenu -->
</div><!-- end of profileMenu -->
<?php include("template/footer.php"); ?>
Both mysqli_real_escape_string() and mysqli_query() functions require that the DB connection be passed as the first parameter; yours doesn't have that.
mysqli_real_escape_string($con, $_GET['u'])
^^^^^ see that?
so...
$username = mysqli_real_escape_string($con, $_GET['u']);
^^^^^ add the db connection variable
and for the query
mysqli_query($con, "SELECT ...
^^^^^ see that?
I used $con here, because there is no indication as to which variable you are using to assign the connection to.
References:
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/mysqli.real-escape-string.php
Sidenote: You may want to change this
if(mysqli_num_rows($check)===1)
to
if(mysqli_num_rows($check) >0 )
where I seen in some case that ===1 failed.
Another thing, changing this block of code
$get = mysqli_fetch_assoc($check);
$username = $get['username'];
to, and using a while loop
while($get = mysqli_fetch_assoc($check)){
// or mysqli_fetch_array
$username = $get['username'];
}
Plus, your DB connection should be mysqli_ based and not mysql_ or PDO, which is also unknownst to us.
Those different MySQL APIs do not intermix.
References:
http://php.net/manual/en/function.mysqli-connect.php
http://php.net/manual/en/mysqlinfo.api.choosing.php
Add or die(mysqli_error($con)) to mysqli_query() to check for errors.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Your code shows a GET array; without knowing where that is populated from, make sure it's set and not empty.
If using a form, then make sure that a POST method isn't implied.
If your form is using a POST method, then you should be using POST and not GET. Make sure the element has a "name" attribute, IF you're using form.
Also unknownst to us.
Again, if you're using a form with a POST method, or whatever, make sure there is a name attribute for it.
I.e.:
<input type="text" name="u">
Edit:
This part will throw an undefined variable notice:
<h1>Profile <?php echo "$username"; ?></h1>
So, use a conditional statement for it:
<h1>Profile
<?php
if(isset($username) && !empty($username)) {
echo $username;
}
else{
echo "Username is empty or not set somewhere.";
}
?>
</h1>
or use a ternary operator
<h1>Profile <?php echo $username ? $username : ""; ?></h1>
or
<h1>Profile <?php echo $username ? $username : "It is empty"; ?></h1>
or
<h1>Profile <?php echo !empty($_GET['u']) ? $_GET['u'] : ""; ?></h1>
or
<h1>Profile <?php echo !empty($_GET['u']) ? $_GET['u'] : "It is empty."; ?></h1>
As you stated in comments, you are using ?u="username" which should read without quotes ?u=username or as an example ?u=john no quotes and may be case sensitive. So john may not be the same as John with an uppercase "J".
So here is my dilemna that I've been reviewing and trying to break through for the last few days. I've created a basic login/register PHP system, which works fine. I've implemented a blog system that displays posts. I've written an add post function which does not post to the database, and it doesn't throw back an error function either.
I don't really understand because my register system works and adds new users, but the 'add blog post' does nothing. I can add from the database and it displays fine, but nothing here.
<?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();
if (isset($_SESSION['id'])) {
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
} else {
header('Location: login.php');
die();
}
if ($_POST['submit']) {
$title = strip_tags($_POST['title']);
$subtitle = strip_tags($_POST['subtitle']);
$content = strip_tags($_POST['content']);
mysqli_query($dbCon, $userREQ3);
$userREQ3 = " INSERT INTO `logindb`.`blog`
(`title`, `subtitle`, `content`) VALUES ('$title','$subtitle','$content')";
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Welcome, <?php echo $username; ?>, You are logged in. Your user id is <?php echo $userId; ?>.
Index
<form action="logout.php">
<input type="submit" value="Log me out!">
</form>
<form method="post" action="admin.php">
Title: <input type="text" name="title"/><br>
Subtitle: <input type="text" name="subtitle"/><br>
<br>
<br>
Content: <textarea name="content"></textarea>
<input type="submit" value="Write Post"/>
</form>
</body>
</html>
Your code is failing for two reasons.
Your conditional statement is looking for a named element called "submit"
You're trying to execute before the statement. Place your query (mysqli_query())"below" the values and do mysqli_query($dbCon, $userREQ3) or die(mysqli_error($dbCon));
Sidenote: Change if ($_POST['submit']) { to if (isset($_POST['submit'])) { it's better.
and <input type="submit" value="Write Post"/>
to <input type="submit" name="submit" value="Write Post"/>
SQL injection:
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
Also, you have variables in the body of your code, which may throw undefined variable x on initial page load.
Use a ternary operator for this
http://php.net/manual/en/language.operators.comparison.php
Use this for all your inputs/variables
As stated (in comments below): Make sure that you have connected to your database and using a mysqli method and not another API.
https://secure.php.net/mysqlinfo.api.choosing
Different MySQL APIs do not intermix with each other. Use the same MySQL API from connection to query.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Successful query or not:
To see if the query was indeed successful, or failed, check for errors and use affected_rows.
References:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/mysqli.affected-rows.php
PHP Not Inserting Content in mySQL Database: Text, Images, Anything
If you were trying to use images, then a valid enctype is required to be included in the form tags.
Depending on how/what you wanted to insert for the images, than that could be a factor.
If you're wanting to insert the image as a path is one thing, but using it "as an image", say a BLOB then that has limitations in size; use LONGBLOB and you must escape that data before going in the database.
Consult:
https://dev.mysql.com/doc/refman/5.0/en/blob.html
http://php.net/manual/en/features.file-upload.post-method.php
Try to generate the query first, then execute it...
$userREQ3 = " INSERT INTO `logindb`.`blog`
(`title`, `subtitle`, `content`) VALUES ('$title', '$subtitle','$content')";
mysqli_query($dbCon, $userREQ3);
Sorry if my Title is crappy but I've looked everywhere and i just don't know how to do this.
OK. what i want to do is display information from a specific id from a table row.
first page
employees.php
<?php
require 'header.php';
require 'connect.php';
$sql1 = mysql_query("SELECT * FROM employees ORDER BY id ASC");
while($runrows = mysql_fetch_array($sql1)){
$employename = $runrows["employename"];
$minidescription = $runrows["minidescription"];
$bigdescription = $runrows["bigdescription"];
echo "
<!-- Employe Profile Start -->
<div class='ProfileWrap'>
<section class='Profile'>
<div class='HeadShot'>
<div class='Separator'></div>
<img width='90' height='136' alt='Employe Headshot' class='EmployeImage' src=img/headshots/".$runrows['images'] ." />
<div class='EmployeInfo'>
<legend class='EmployeName'>
<b>
Employe Name: $employename
</b>
</legend>
<div class='EmployeDes'>
<p>
Employe Descript $minidescription...
</p>
</div>
<a href='readmore.php?id=" .$id = $runrows["id"]. "' id='demo' alt='Read More'>
<div class='ReadMore'>
<b>
Read More
</b>
</div>
</a>
</div>
</div>
</section>
</div>
<!-- employe Profile End -->
";
} // close while loop
?>
<?php require 'footer.php'; ?>
second page
employe.php
<?php
require 'header.php';
require 'connect.php';
echo "<a href='index.php'>Back</a>";
$sql2 = mysql_query("SELECT * FROM employees WHERE id=$id");
while($runrows = mysql_fetch_array($sql2)){
$id = $runrows["id"];
$employename = $runrows["employename"];
$minidescription = $runrows["minidescription"];
$bigdescription = $runrows["bigdescription"];
echo "
<legend class='EmployeName'>
<b>
Employe Name: $employename
</b>
</legend>
<div class='EmployeDes'>
<p>
Employe Description: $bigdescription...
</p>
</div>
";
};
require 'footer.php';
?>
and you would click
[Read More]
then it would go to another page called readmore.php
"Click" [Read More] -> readmore.php?id=14 -> display specific info from that id from the database.
username
minidescription
->
click [Read More]
then it would show up like readmore.php?id=14 in the small address bar at the
bottom left
->
new page
->
largedescription
i want to be able to click on an item in a site that has a read more button and have it take me to another page where it displays the description info for that specific id
yes i realize I'm a complete newbie but I'm still learning and that was a crappy example of what i want to accomplish but i hope you understand what I'm trying to do none the less.
sorry if this already exists but I've looked everywhere and couldn't find what i was looking for. If someone has a link to share that can do what I've asked this question can just be deleted.
Thanks in Advance! hope someone can help me figure this out.
First, note #Matthew Johnson's answer about using Mysqli or PDO. Here are a few code specifics, though. When you generate the link to the page, you need this:
<a href='readmore.php?id=" . $runrows["id"] . "' id='demo' alt='Read More'>
Using $id = $runrows["id"] doesn't place the value into the url, it simply declares the value of the $id variable.
Then in your readmore.php file, the id can be capture from the URL using the $_GET array:
if (isset($_GET['id'])) {
$id = $_GET['id'];
}
The mysql_* functions are deprecated, and should no longer be used. Mysqli or PDO should be used, along with prepared statements. The code as you have it is susceptible to sql injection attacks. A simplified version of what you're trying to do would look something like this:
To Link:
//this gets all the name and mini, loops through and displays....
$stmt = $mysqli->prepare("SELECT id, employename, minidescription FROM employees");
$stmt->execute();
$stmt->bind_result($id, $employeename, $minidescription);
while($stmt->fetch()) {
echo "<p><a href='readmore.php?id=$id'>$employeename</a>: $minidescription</p>";
}
The Read More:
//make sure it's set, if so assign it...
$id = (isset($_GET['id']) ? $_GET['id'] : "";
//this gets the info using the id variable from the URL...
$stmt = $mysqli->prepare("SELECT employename, minidescription, bigdescription FROM employees WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($employeename, $minidescription, $bigdescription);
$stmt->fetch();
echo "$employeename: $bigdescription";
Using mysqli and prepared statements, as shown here, protects you against bobby tables and sql injection attacks. You can learn more about mysqli from the manual. Here's a tutorial with a quick run through of how prepared statements work.
Edit:
The code above still needs a database connection. The warning of an undefined variable is saying that the $mysqli variable hasn't been defined. The fatal error is due to the fact that the prepare statement failed. To create a connection, it would look similar to this:
define("HOST", "Host URL");
define("USER", "dbUser");
define("PASSWORD", "password");
define("DATABASE", "databaseName");
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
This would replace the code in your connect.php.
i have a list of user reviews that a user can choose to approve or delete.
I have the reviews.php file which lists the pending reviews, a approve_review.php file and a delete_review.php file.
Once the user approves the review i need the mysql column 'approve' to be changed from '0' to '1'. Same applies for the delete but instead of updating 'approve' it will update 'delete'.
Everything i've tried isn't working. please can someone tell me where i'm going wrong. Thanks.
reviews.php:
<?php
$pending_set = get_pending_reviews();
while ($reviews = mysql_fetch_array($pending_set)) {
?>
<div class="prof-content-pend-reviews" id="reviews">
<div class="pend-review-content">
<?php echo "{$reviews['content']}"; ?>
</div>
<div class="approve"></div>
<div class="delete"></div>
</div>
<? } ?>
approve_review.php:
<?php
require_once("session.php");
require_once("functions.php");
require('_config/connection.php');
approve_review ($_GET['review'], $_SESSION['user']);
header('Location: http://localhost/ptb1/reviews.php');
?>
Function:
function approve_review($review_id, $user) {
global $connection;
global $_SESSION;
$query = "UPDATE ptb_reviews
SET approved='1'
WHERE id=$review_id
AND to_user_id=$user";
mysql_query($query, $connection);
}
A parameter is missing to approve_review.php ... its has to be something like this:
<div class="approve"></div>
You have to replace TheID with your php variable.
Greatings!
There are some things wrong here:
You are not actually sending any parameters to your script;
Your script is wide open to sql injection, you should switch to prepared statements in PDO / mysqli.
I wanted to expand my PHP skills so I read through a tutorial on tutorialzine. I understand the instructions presented in the tutorial. But when it comes to expanding on it I seem to be lacking a connection. My main goal was to simply delete a selected note when an a tag is clicked. However I don't know how to select the id assigned to the note to be able to pass it to my delete function.
Source: http://tutorialzine.com/2010/01/sticky-notes-ajax-php-jquery/
Thanks for the help.
<?php
error_reporting(E_ALL^E_NOTICE);
require 'connect.php';
mysql_query("DELETE FROM notes WHERE id>3 AND dt<SUBTIME(NOW(),'0 1:0:0')");
$query = mysql_query("SELECT * FROM notes ORDER BY id DESC");
$notes = '';
$left='';
$top='';
$zindex='';
while($row=mysql_fetch_assoc($query)){
list($left,$top,$zindex) = explode('x',$row['xyz']);
$notes.= '
<div class="note '.$row['color'].'" style="left:'.$left.'px;top:'.$top.'px;z-index:'.$zindex.'">
'.htmlspecialchars($row['text']).'
<div class="author">'.htmlspecialchars($row['name']).'</div>
<span class="data">'.$row['id'].'</span>
<a id="remove_note" href="javascript:;" onclick="deleteNote('<? echo $row['id']; ?>');"> </a>
</div>';
}
function deleteNote(id){
$sql="DELETE FROM notes WHERE id='$rows['id']'";
$result=mysql_query($sql) or die("Error when tryin to delete note.");
}
?>
Update:
I've been playing around with this and the answers that both Andrew and sachleen have provided. And ill plan to work on an AJAX alternative since you've mentioned the whole SQL Injection issue. But I am still having issues with passing the id to the remove.php file. I believe is has to do with how $notes is creating the information from the DB.
I say this because I get: Parse error: syntax error, unexpected T_STRING in /home/avonamyd/public_html/projects_php/sticky_notes/demo.php on line 24
And that is only when I include the code as is from sachleen. But when I update it to account for the single quotes I have the following code. The id is present and is passed to the remove.php file but I am still getting an error. This is when I use my code or what you've provided.
$notes.= '
<div class="note '.$row['color'].'" style="left:'.$left.'px;top:'.$top.'px;z-index:'.$zindex.'">
'.htmlspecialchars($row['text']).'
<div class="author">'.htmlspecialchars($row['name']).'</div>
<span class="data">'.$row['id'].'</span>
<a id="remove_note" target="_blank" href="remove.php?id='.$row['id'].'"> </a>
</div>';
Below is what I currently have in my remove.php file:
<?php
include 'connect.php';
$_GET['id'];
function deleteNote($id){
$sql="DELETE FROM notes WHERE id='$id'";
}
$result=mysql_query($sql) or die("Error when tryin to delete note.");
?>
Update
I've added in additional echo lines throughout the remove.php and this is what I am coming up with.
<?php
include 'connect.php';
$_GET['id'];
echo $id; --doesnt show
function deleteNote($id){
echo "hello"; --doesnt show
$sql="SELECT FROM notes WHERE id='$id'";
}
echo 'hello2'; --shows
$result=mysql_query($sql) or die("Error when tryin to delete note.");
?>
Update:
Thank you for everyone's help with this project I've finally gotten the concepts to click in my head after some tinkering around. I will post the functional code below for anyone else that stumbles upon this code. =D
Thx Everyone!
demo.php
error_reporting(E_ALL^E_NOTICE);
require 'connect.php';
mysql_query("DELETE FROM notes WHERE id>3 AND dt<SUBTIME(NOW(),'0 1:0:0')");
$query = mysql_query("SELECT * FROM notes ORDER BY id DESC");
$notes = '';
$left='';
$top='';
$zindex='';
while($row=mysql_fetch_assoc($query)){
list($left,$top,$zindex) = explode('x',$row['xyz']);
$id = $row['id'];
$notes.= '
<div class="note '.$row['color'].'" style="left:'.$left.'px;top:'.$top.'px;z-index:'.$zindex.'">
'.htmlspecialchars($row['text']).'
<div class="author">'.htmlspecialchars($row['name']).'</div>
<span class="data">'.$row['id'].'</span>
<a id="remove_note" target="_blank" href="remove.php?id='.$row['id'].'"> </a>
</div>';
}
remove.php
<?php
include 'connect.php';
$id = intval($_GET['id']);
$sql="DELETE FROM notes WHERE id=$id";
$result = mysql_query($sql) or die("Unable to delete database entry.");
?>
It looks like you are trying to mix JavaScript and PHP. You cannot call the deleteNote() function when your link is clicked because it is a PHP function. There are a couple of ways to go about calling the PHP script to delete the note:
Use something like the following:
<?php
// ...
$id_to_delete = $_GET['id'];
if( isset($id_to_delete) ) {
$sql="DELETE FROM notes WHERE id='$id_to_delete'";
$result=mysql_query($sql) or die("Error when tryin to delete note.");
}
$query = mysql_query("SELECT * FROM notes ORDER BY id DESC");
//...
while($row=mysql_fetch_assoc($query)){
//...
echo '<a id="remove_note" href="CURRENT_SCRIPT_URL?id=' . $id_to_delete . '">X</a>';
//...
}
?>
Or you could create a second script that deletes a row from the database based on the data that you pass to it and use ajax (I would recommend using jQuery for ajax functionality) to call that script with the id of the item to delete.
Remember that anyone could call your script with a GET parameter and delete a record from the database (or worse, perform an SQL injection attack), so make sure that you have some sort of safeguard in place unless you want all of your records wiped out!
You can't onclick a PHP function. You're mixing JavaScript with PHP. I would do this:
<a id="remove_note" href="remove.php?id=<?php echo $row['id']; ?>">Remove</a>
And then on remove.php get the ID using $_GET['id'] and pass that into the DELETE query.
you have 2 options.
1) make an <a href="another_php_script.php?delete=true"> (or similar), then run the delete script. (then header back to the same page you were on).
This is because you cannot run an onClick php function, you have to redirect to the other page.
2) You can use the onclick function to call an AJAX script, and execute the deleting PHP script from the page you're on - without redirecting.
Option 1 is the easy option, Option 2 is the better option to learn from.