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.
Related
I'm trying to create a SQL query that takes the values of an entire table and dumps them into an array that I can call based the value of a URL parameter.
The parameter passed into the url will be ?username=User1.
I need the query to filter results in the database that are related to the that user (for example - their name, email address, interests etc).
I want to then be able to store them in an array that I can use to call and display the values, for example;
<?php echo htmlentities($row['profiles']['username'], ENT_QUOTES, 'UTF-8'); ?>
<?php echo htmlentities($row['profiles']['location_city'], ENT_QUOTES, 'UTF-8'); ?>
I use the following PHP to set the $u variable in PHP
My SQL query so far is as follows
$query = "
SELECT
user_id,
username,
displayname,
displayage,
location_city,
language
FROM profiles WHERE username='$u'
";
I then use the following PHP code to try and pass the data into an array;
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
My full code for profile.php;
<?php $_GET['u'] = 'u'; ?>
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
header("Location: index.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to index.php");
}
// Everything below this point in the file is secured by the login system
// We can retrieve a list of members from the database using a SELECT query.
// In this case we do not have a WHERE clause because we want to select all
// of the rows from the database table.
$query = "
SELECT
id,
username,
email
FROM profiles WHERE username='$u'
";
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
?>
<?php include('header.php') ?>
<div class="pages navbar-through toolbar-through">
<div class="page" data-page="profile">
<div class="page-content">
<div class="content-block">
<div class="content-block-inner">
<p>Profile content will go here</p>
Go Back<br />
</div>
</div>
</div>
</div>
</div>
<?php include('footer.php') ?>
Change profile.php file contents as shown below:
<?php $username = (isset($_GET['username']))? trim(strip_tags($_GET['username'])) : ""; ?>
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
header("Location: index.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to index.php");
}
// Everything below this point in the file is secured by the login system
// We can retrieve a list of members from the database using a SELECT query.
// In this case we do not have a WHERE clause because we want to select all
// of the rows from the database table.
$query = "
SELECT
user_id,
username,
displayname,
displayage,
location_city,
language
FROM profiles WHERE username = '$username'
";
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<?php include('header.php') ?>
<div class="pages navbar-through toolbar-through">
<div class="page" data-page="profile">
<div class="page-content">
<div class="content-block">
<div class="content-block-inner">
<p>Profile content will go here</p>
<?php foreach($rows as $row): ?>
<div>Username: <?php echo $row['username'] ?></div>
<div>Location: <?php echo $row['location_city'] ?></div>
<?php endforeach; ?>
Go Back<br />
</div>
</div>
</div>
</div>
</div>
<?php include('footer.php') ?>
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
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 am new to PHP and just wanting to make a basic page where i can see all the users in the database and delete them. I have come this far but it keeps on telling me that I have an i have and Undefined index: user_id and although it tells me that it has deleted the fields it has not deleted anything. Here is my code:
<?php include_once "includes/scripts.php"; ?>
<?php include_once "includes/connect.php";?>
<?php include_once "includes/cms_page_security.php";?>
<div id="cms_container"><br>
<br>
<h1>MANAGE USERS<img src="images/three_column_grid_line.png" alt="line"></h1>
<p class="logout_btn">Back</p>
<?php
$tbl="users"; // Table name
$sql = "SELECT * FROM $tbl";
$result = mysql_query($sql, $connect);
while($rows = mysql_fetch_array($result)){
?>
<?php
echo $rows['user_id'];
echo $rows['user_name'];
echo $rows['user_password'];
?>
delete
<?php
}
?>
<?php
mysql_close();
?>
</div><!--cms_container-->
</body>
</html>
The page that it should link to that deletes the query:
<?php include_once "includes/connect.php";?>
<?php
$tbl="users";
$user_id= $_GET ['user_id'];
$sql="DELETE FROM $tbl WHERE user_id = '$user_id'";
$result = mysql_query($sql, $connect);
if($result){
echo "Deleted Successfully";
echo "<BR>";
echo "<a href='delete.php'>Back to main page</a>";
}else {
echo "ERROR";
}
?>
<?php
mysql_close();
?>
In delete_user.php you must get user_id
$user_id= $_GET ['id'];
because in your delete link GET variable is "id", not "user_id"
You really should be using PDO instead.
The issue is in the information that you are passing.
The link : delete
is looking for an 'id' but you're later looking for 'user_id'
If you change it to delete, it should work.
I still strongly suggest you look into PDO instead though, it's much more secure and easier to work with.
Example of PDO Delete
public function deleteUser($username, $user_id){
if($this->isAdmin($username) == true){
$query = $this->db->prepare('DELETE FROM users WHERE user_id = ?');
$query->bindValue(1, $user_id);
try{
$query->execute();
}catch(PDOException $e){
die($e->getMessage());
}
}else{
return false;
}
}
I'm running an extra check to make sure the person who is requesting the deletion is an admin member but you should be able to see the structure
In addition to the other answers:
It looks like this line could be a fatal error, if php short tags aren't enabled:
delete
The php manual says:
*PHP also allows for short tags <? and ?>
(which are discouraged because they are only available if enabled with
short_open_tag php.ini configuration file directive, or if PHP was configured
with the--enable-short-tags option.*
http://php.net/manual/en/language.basic-syntax.phptags.php
The SQL query will be successful even if it alters zero rows. You are prefixing your user ids with a space when you are generating your HTML (id= <?), so you aren't matching any rows (since "1" won't be matched by " 1").
Where you are creating your 'Delete' link
delete
You're creating a variable of 'id', but later you look for 'user_id.
Change your link to
delete
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.