I have a page that shows comments, "comments.php", and I include the page on any other page that I want comments to show. I am trying to implement a way to delete comments if needed. Each comment has an auto-increment "commentID". Right now I'm using an action, and then just using a link to call the action.
When I hover over the link, the URL looks correct, but when I click it, the page refreshes and nothing happens. Any ideas?
Action:
if ($_POST['action'] == 'delete') {
$sql = "delete from " . $db_prefix . "comments where commentID = " . (int)$_GET['id'];
mysql_query($sql) or die('error deleting user: ' . $sql);
header('Location: ' . $_SERVER['HTTP_REFERER']);
}
Show comments and show link to delete: (unnecessary code has been left out)
echo 'delete
What am I doing wrong?
In your code you're mixing $_POST with $_GET.
Try this,
?php
if ($_GET['action'] == 'delete') {
if (!ctype_digit($_GET['id'])) {
exit("ID has to be an int.");
}
$id = intval($_GET['id']);
$sql = "DELETE FROM `" . $db_prefix . "comments` WHERE `commentID` = " . $id;
mysql_query($sql) or die('error deleting user: ' . $sql);
header('Location: ' . $_SERVER['HTTP_REFERER']);
}
?>
Your link also shows action=delete so you should be checking if $_GET action equals delete.
Edit 1
Your code is prone to SQL injection, you are still using MySQL even though it has been deprecated, you should use either MySQLi or PDO with prepared statements.
Not to mention your $_GET data is being passed on to the query without being sanitized, you should start using intval it would make it better and prevent XSS. Please read up on the function intval and ctype_digit to get a better understanding at what it does.
Edit 2
Scrap $_SERVER['HTTP_REFERER']
How reliable is HTTP_REFERER?
Edit 3
As noted in comments:
"If you're using the same file for everything, just omit the file name ?action=delete&id"
which would explain the 404 you mentioned in comments.
Related
The sql column avatar_link isn't updating:
A form submits data and directs to the script (partial) below. The SQL columns: name, comment, email and story_id all insert fine. The image saves to the server with no problem (I didn't include that part of the script to keep things brief). $templink is a newly created variable that should represent the URL of a image uploaded. I'm redefining the variable as $avatar_link and using POST.
$tempLink = "http://www.website.com/avatars/" . $_FILES["file"]["name"];
$page_path = $_POST['page_path'];
$name = $_POST['name'];
$comment = $_POST['comment'];
$email = $_POST['email'];
$storyid = $_POST['storyid'];
$avatar_link = $_POST['$tempLink'];
$con=mysqli_connect
("","","","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = 'INSERT INTO comments (name, comment, email, storyid, avatar_link, entry_date)';
$sql .= 'VALUES("'.$name.'", "'.$comment.'", "'.$email.'", "'.$storyid.'", "'.$avatar_link.'", now())';
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
I marked the title of this 'beginners PHP' because this question seems very basic (and I can't still figure it out)...if that is not appropriate let me know and I will remove.
$_POST variables come from a submitted form. If you are simply defining a variable and passing it into a statement for insertion into a database, you could eliminate a few steps here, and just do this:
$avatar_link = "http://www.website.com/avatars/" . $_FILES["file"]["name"];
Also, pay attention to #Marc B's comment here. You can learn about parameterizing mysqli statement all over the web, or here on Stack Overflow. What's really best, and what I'd recommend, is learning PDO.
I am working on a program that takes HTML code made by a WYSIWYG editor and inserting it into a database, then redirecting the user to the completed page, which reads the code off the database. I can manually enter code in phpmyadmin and it works but in PHP code it will not overwrite the entry in the code column for the ID specified. I have provided the PHP code to help you help me. The PHP is not giving me any parse errors. What is incorrect with the following code?
<?php
//POST VARIABLES------------------------------------------------------------------------
//$rawcode = $_POST[ 'editor1' ];
//$code = mysqli_real_escape_string($rawcode);
$code = 'GOOD';
$id = "1";
echo "$code";
//SQL VARIABLES-------------------------------------------------------------------------
$database = mysqli_connect("localhost" , "root" , "password" , "database");
//INSERT QUERY DATA HERE----------------------------------------------------------------
$queryw = "INSERT INTO users (code) VALUES('$code') WHERE ID = '" . $id . "'";
mysqli_query($queryw, $database);
//REDIRECT TO LOGIN PAGE----------------------------------------------------------------
echo "<script type='text/javascript'>\n";
echo "window.location = 'http://url.com/users/" . $id . "/default.htm';\n";
echo "</script>";
?>
Your problem is that mysql INSERT does not support WHERE. Change the query to:
INSERT INTO users (code) VALUES ('$code')
Then to update a record, use
UPDATE users SET code = '$code' WHERE id = $id
Of course, properly prepare the statements.
Additionally, mysqli_query requires the first parameter to be the connection and second to be the string. You have it reversed. See here:
http://php.net/manual/en/mysqli.query.php
It should also be noted that this kind of procedure should be run before the output to the browser. If so, you can just use PHP's header to relocate instead of this js workaround. However, this method will still work as you want. It is just likely to be considered cleaner if queries and relocation is done at the beginning of the script.
good day
need some help here, my Delete button works but page is not automatically refreshing after i clicked the delete button. i still need to manually retrieve the data from db and it would reflect that data is deleted already...
here is my code for delete php: how can i make this to refresh the page automatically?
<?php
require 'include/DB_Open.php';
$id = $_POST['id'];
$idtodelete = "'" . implode("','",$id) . "'";
$query = "DELETE FROM tbl WHERE ticket in (" . $idtodelete . ")";
$myData = mysql_query($query);
echo "DATA DELETED";
if($myData)
{
header("Location: delete.php");
}
include 'include/DB_Close.php';
?>
I suggest fetching the data after your delete logic. Then the delete logic will be executed before fetching the tickets.
Then a redirect to the same page isn't even necessary.
//
// DELETE
//
if (isset($_POST['delete'] && isset($_POST['id'])) {
// Do delete stuff,
// notice delete variable which would be the name of the delete form button e.g.
// If you like, you can still echo "Data deleted here" in e.g. a notification window
}
//
// FETCH data
//
$query = "Select * FROM tbl";
...
if you use post method better with this
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$id = $_POST['id'];
$idtodelete = "'" . implode("','",$id) . "'";
$query = "DELETE FROM tbl WHERE ticket in (" . $idtodelete . ")";
if (mysql_query($query))
{
header("Location: delete.php");
} else {
echo "Can not delete";
}
}
As suggested on one of the comments, and on the php documentation:
http://it2.php.net/manual/en/function.header.php :
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
Basically you have to take out the :
echo "DATA DELETED";
What's the point to try to echo that string if the page is going to be redirected anyway?
If you want to make it fancy you could use Ajax to delete it, and trigger a setTimeout() on JavaScript x seconds after showing the message.
Or if you really really really really, REALLY, want to do it this way, you could disable the errors report/display (using error_reporting(0) and ini_set('display_errors', 'Off'). By experience I know that it will work, but it's nasty and extremately ultra highly not recommended
Im using ThickBox 3.1 and regretting it since it is no longer supported and Im new to programming so I could use all the help I can get.
Im almost done setting up several Thickboxes on my site but my last one requires a variable to be passed from the parent page to ThickBox and I just can't seem to pick it up in my php script. I have a parent page that is getting the variable from a currently selected drop down menu. When I hover over the link that will open the ThickBox Modal I see:
http://localhost/forms/modal_product.html?strUser=100&TB_iframe=true&height=300&width=590
which is great because I need the strUser variable. So the ThickBox opens I enter some information into a short form just like my other ThickBoxes but nothing happens. When I look under firebug to see the AJAX response it informs me that:
<b>Notice</b>: Undefined index: strUser in <b>C:\xampp\htdocs\forms\item_add.php</b> on line <b>3</b
Ive tried seeing what $_SERVER['QUERY_STRING']; comes up with and it is NULL.
I think my question is generic in that I just don't know where my _GET variable is going? Can anyone with experience with ThickBox help me out? Ive read my butt off and I realize in older versions of ThickBox it was harder to pass variables and it required hacks but I should be able to do this the way I have it. What am I doing wrong? Is there an easier way to pass variables or am I just missing something obvious?
Also when I go to my form page directly and not as a link through the parent window, if I manually put a GET variable into the URL it still gives me the same errors which leads me to believe I'm just missing something basic. Here is my php code.
<?php
include '../dbc.php';
$getman = ($_GET['strUser']);
$manid1 = mysql_query("SELECT manufacturer_id FROM manufacturers WHERE man_name='$getman'");
$manid11 = mysql_fetch_array($manid1);
$manid21 = $manid11[0];
if ($_POST) {
// Collect POST data from form
$item_num = stripslashes($_POST['item_num']);
$descript = stripslashes($_POST['descript']);
$quanti = stripslashes($_POST['quanti']);
$fdaa = stripslashes($_POST['fdaa']);
}
$params = $_SERVER['QUERY_STRING'];
$domain = $_SERVER['SCRIPT_NAME'];
$queryString = $_SERVER['REQUEST_URI'];
$stmnt2 = mysql_query("INSERT INTO products (product_id, item_number, description, quantity_per_unit, fda_approved, manufacturer_id) VALUES ('NULL', '" . $item_num . "', '" . $descript . "' ,'" . $quanti . "', '" . $fdaa . "' , '" . $manid21 . "')");
$resp['status'] = 'success';
if ($stmnt2) {
$resp['errmessage'] = "Item submitted. Submit another item or click close.";
} else {
$resp['errmessage'] = $params;
}
echo json_encode($resp);
?>
I worked it out. I had to pull the variable in Jquery from the URL, put it into a hidden field and then run my php script.
Having trouble getting my form to UPDATE records in my database even after searching the web and viewing the other answers on stack-overflow.
Here is my current NON functioning code:
if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {
session_start();
$tablename = $_SESSION['MM_Username'];
$amount=$_POST['amount'];
$UpdateQuery = "UPDATE '" . $tablename . "' SET stock = '" . $amount . "' WHERE status = 1";
mysql_query($UpdateQuery);
}
The table i want to update has the same name as the SESSION variable MM_Username. I have a form with a textbox named amount and a Submit button that when clicked, should trigger the above code. If you need to know anything else let me know. Thanks in advance!
You're using the wrong quotes around your table name. Also, your query is open to SQL injection. Consider using PDO and bind parameters.
$UpdateQuery = sprintf('UPDATE `%s` SET `stock` = :amount WHERE `status` = 1',
$tablename);
$stmt = $pdo->prepare($UpdateQuery);
$stmt->bindParam('amount', $amount);
$stmt->execute();
Have MySQL tell you what the problem is. Change the last line of your code to this:
if (!mysql_query($UpdateQuery)) {
echo mysql_error();
}
Print out if you are having your tablename in your session variable.
print $_SESSION['MM_Username'];
Also print out the $UpdateQuery and see how the mysql query is formed. Copy that query & try running it manually in mysql to see if the query is ok.
ADVISE: I see that you have used $_POST. This is fine, but I advise you to use $_REQUEST. This var in PHP has all $_POST & $_GET content. Sometimes one forgets to change the $_POST to $_GET or vice versa & ends up wasting his time, debuggin.
if (!mysql_query($UpdateQuery)) {
echo mysql_error()
}