page not refreshing after clicking delete button - php

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

Related

What's going on with my code?

I am using similar syntax in my blog. However, On my forum, nothing happens! This has been such an infuriating thing to tackle, as everything seems to be working exactly as my blog did. Here's my code I pass through and call the delete_post page
CHUNK FROM VIEWPOST.PHP
while($row = mysqli_fetch_array($result)){
echo '<tr>';
echo '<td class="postleft">';
echo date('F j, Y, g:i a', strtotime($row['forumpost_Date'])) . "<br>" .$row['user_Name']. "<br>" .$row['forumpost_ID'];
echo '</td>';
echo '<td class="postright">';
echo $row['forumpost_Text'];
echo '</td>';
if(isset ($_SESSION['loggedin']) && ($_SESSION['user_AuthLvl']) == 1){
echo '<td class="postright">';
echo '<a class= "btn btm-default" href="#">Edit</a>';
echo '<a class= "btn btm-default" href="delete_post.php?forumpost_ID='.$row['forumpost_ID'].'">Delete</a>';
echo '</td>';}
else if(isset ($_SESSION['loggedin']) && ($_SESSION['user_ID']) == $row['forumpost_Author']){
echo '<td class="postright">';
echo '<a class= "btn btm-default" href="#">Edit</a>';
echo '<a class= "btn btm-default" href="delete_post.php?forumpost_ID='.$row['forumpost_ID'].'">Delete</a>';
echo '</td>';}
echo '</tr>';
}echo '</table>';
DELETE POST FUNCTION
<?php
include ('header.php');
include ('dbconnect.php');
//A simple if statement page which takes the person back to the homepage
//via the header statement after a post is deleted. Kill the connection after.
if(!isset($_GET['forumpost_ID'])){
header('Location: index.php');
die();
}else{
delete('hw7_forumpost', $_GET['forumpost_ID']);
header('Location: index.php');
die();
}
/********************************************
delete function
**********************************************/
function delete($table, $forumpost_ID){
$table = mysqli_real_escape_string($connectDB, $table);
$forumpost_ID = (int)$forumpost_ID;
$sql_query = "DELETE FROM ".$table." WHERE id = ".$forumpost_ID;
$result = mysqli_query($connectDB, $sql_query);
}
?>
Now it is showing the ID's as intended, it just simply does not delete the post. It's such a simple Query, I don't know where my syntax is not matching up!
EDIT FOR DBCONNECT.PHP
<?php
/*---------------------------------------
DATABASE CONNECT PAGE
A simple connection to my database to utilize
for all of my pages!
----------------------------------------*/
$host = 'localhost';
$user = 'ad60';
$password = '4166346';
$dbname = 'ad60';
$connectDB = mysqli_connect($host, $user, $password, $dbname);
if (!$connectDB){
die('ERROR: CAN NOT CONNECT TO THE DATABASE!!!: '. mysqli_error($connectDB));
}
mysqli_select_db($connectDB,"ad60") or die("Unable to select database: ".mysqli_error($connectDB));
?>
Ok, I saw this and I would like to suggest the following:
In general
When you reuse code and copy paste it like you have done there is always the danger that you forget to edit parts that should be changed to make the code work within the new context. You should actually not use code like this.
Also you have hard coded configuration in your code. You should move up all the configuration to one central place. Never have hard coded values inside your functional code.
Learn more about this in general by reading up about code smell, programming patterns and mvc.
To find the problem
Now to fix your problem lets analyse your code starting with delete_post.php
First check if we actually end up inside delete_post.php. Just place an echo "hello world bladiebla" in top of the file and then exit. This looks stupid but since I can't see in your code if the paths match up check this please.
Now we have to make sure the required references are included properly. You start with the include functionality of php. This works of course, but when inside dbconnect.php something goes wrong while parsing your script it will continue to run. Using require would fix this. And to prevent files from loading twice you can use require_once. Check if you actually have included the dbconnect.php. You can do this by checking if the variables inside dbconnect.php exist.
Now we know we have access to the database confirm that delete_post.php received the forumpost_ID parameter. Just do print_r($_GET) and exit. Check if the field is set and if the value is set. Also check if the value is actually the correct value.
When above is all good we can go on. In your code you check if the forumpost_ID is set, but you do not check if the forumpost_ID has an actual value. In the above step we've validated this but still. Validate if your if
statement actually functions by echoing yes and no. Then test your url with different inputs.
Now we know if the code actually gets executed with all the resources that are required. You have a dedicated file that is meant to delete something. There is no need to use a function because this creates a new context and makes it necessary to make a call and check if the function context has access to all the variables you use in the upper context. In your case I would drop the function and just put the code directly within the else statement.
Then check the following:
Did you connect to the right database
Is the query correct (echo it)
Checkout the result of mysqli_query
Note! It was a while ago since I programmed with php so I assume noting from the codes behavior. This is always handy. You could check the php versions on your server for this could also be the problem. In the long run try to learn and use MVC. You can also use frameworks like codeigniter which already implemented the MVC design pattern.
You have to declare $connectDB as global in function.
function delete($table, $forumpost_ID){
global $connectDB;
$table = mysqli_real_escape_string($connectDB, $table);
$forumpost_ID = (int)$forumpost_ID;
$sql_query = "DELETE FROM ".$table." WHERE id = ".$forumpost_ID;
$result = mysqli_query($connectDB, $sql_query);
}
See the reference about variable scope here:
http://php.net/manual/en/language.variables.scope.php
please try to use below solution.
<?php
include ('header.php');
include ('dbconnect.php');
//A simple if statement page which takes the person back to the homepage
//via the header statement after a post is deleted. Kill the connection after.
if(!isset($_GET['forumpost_ID'])){
header('Location: index.php');
die();
}else{
delete('hw7_forumpost', $_GET['forumpost_ID'], $connectDB);
header('Location: index.php');
die();
}
/********************************************
delete function
**********************************************/
function delete($table, $forumpost_ID, $connectDB){
$table = mysqli_real_escape_string($connectDB, $table);
$forumpost_ID = (int)$forumpost_ID;
$sql_query = "DELETE FROM ".$table." WHERE id = ".$forumpost_ID;
$result = mysqli_query($connectDB, $sql_query);
}
?>
I wish this solution work for you best of luck!

delete value from database using link

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.

PHP not retrieving new data until page refresh

What is happening is I think my code is selecting the data first (basically old data) then updating it but what I want is for it to update then select the data (new data). How can I do this?
I am going to post where it goes wrong and if you need the full code just ask:
$select_links = $db->query("SELECT pid, added_by,link_title,lid,link_order FROM " . TABLE_PREFIX . "homepage_links WHERE pid='$pid'
ORDER BY link_order DESC LIMIT $start,$show");
$check_link_count_rows = $db->num_rows($select_links);
echo "<b> You Current Have " . $check_link_count_rows . " Links On Your Page: </b><br>";
echo "<form action='' method='POST'>
";
while($select_links_array = $db->fetch_array($select_links)) {
$link_title_display = $select_links_array['link_title'];
$link_id_display = $select_links_array['lid'];
if(!$mybb->input["order_edit_$link_id_display"]) {
$link_order_display = $select_links_array['link_order'];
} else {
$link_order_display = $mybb->input["order_edit_$link_id_display"];
}
$order_edit_value1 = $mybb->input["order_edit_$link_id_display"];
$order_edit_value = $db->escape_string($order_edit_value1);
echo "<br>" . $link_title_display . " <a href='?operation=edit_links&link=$link_id_display'> (edit) </a>
<input type='number' name='order_edit_$link_id_display' value='$link_order_display' style='width:40px;'>
<input type='hidden' name='get_link_id_display_value_$link_id_display' value='$link_id_display'><br>
";
$get_link_id_display_value1 = $mybb->input["get_link_id_display_value_$link_id_display"];
$get_link_id_display_value = $db->escape_string($get_link_id_display_value1);
$update_quick_edit_query = $db->query("UPDATE spud_homepage_links SET link_order='$order_edit_value'
WHERE lid='$get_link_id_display_value'");
}
I cannot find a solution as everything is in the right place for it to work besides this bug.
After a discussion in the comments, I determined that you were attempting to render a page after a post form submission that amends the database. It is perfectly possible to re-read your new database state and render it in a post operation, but it is inadvisable, since browsers cannot refresh the page without asking you if you wish to run the operation again. This does not make for a good user experience, especially in relation to using the back/forward buttons.
The reason for this behaviour is that post operations generally modify the database. They are used for example in credit card purchases or profile amendments where some change in the state of the server is expected. Thus, it is good practice to execute a new round-trip to the server, after the write operation, to change the page method from post to get.
The header() call I linked to will do this, and will resolve your rendering problem too.

Can you use one single product layout page to display products once clicked on?

I want to use one single page with pre-defined divs, layout etc. as basis so that when a product is clicked on from elsewhere it loads that product info onto the page?
They way im doing it ill be sitting here till about 2020 still typing out product info onto pages.
EDIT*************
function product ()
{
$get = mysql_query ("SELECT id, name, description, price, imgcover FROM products WHERE size ='11'");
if (mysql_num_rows($get) == FALSE)
{
echo " There are no products to be displayed!";
}
else
{
while ($get_row = mysql_fetch_assoc($get))
{
echo "<div id='productbox'><a href=product1.php>".$get_row['name'].'<br />
'.$get_row['price']. '<br />
' .$get_row['description']. '<br />
' .$get_row['imgcover']. "</a></div>" ;
}
}
}
In addition one problem I have with that code is that the <a href> tag only goes to product1.php. Any ideas how I can make that link to blank product layout page that would be filled with the product info that the user has just clicked on, basically linking to itself on a blank layout page.
Thanks any help would be great!
Thanks Maxyy
Since you dont have code this is a general way of doing this. What you want is a template for the product page
Query the database
load the data into a variable
make a script that will print out the data from the variable into a product page
somescript.php
<?php
$productid = $_REQUEST['productid']; //Of course do sanitation
//before using get,post variables
//though you should be using mysqli_* functions as mysql_* are depreciated
$result = mysql_query("select * from sometable where id='{$productid}");
$product = mysql_fetch_object($result);
include("productpage.php");
productpage.php
<div class="Product">
<div class="picture"><img src="<?php echo $product->imghref;?>" /></div>
<div class="price"><?php echo $product->price;?></div>
</div>
so on and so fourth. Included scripts use whatever variables are currently in the scope of the calling function
If you are meaning to load the products into the same page without doing another page load you will need to use ajax. Which is javascript code that use XHR requests to return data from a server. You can either do pure javascript or a library like jQuery to simplify the process of doing a xhr request by using $.ajax calls.
I know this question has been asked over 4 years ago, but since there's been no answer marked as right, I thought I might chip in.
First, let's upgrade from mysql and use mysqli - my personal favorite, you can also use PDO. Have you tried using $_GET to pull the id of whatever product you want to see and then displaying them all together or one at a time?
It could look something like this:
<?php // start by creating $mysqli connection
$host = "localhost";
$user = "username";
$pass = "password";
$db_name = "database";
$mysqli = new mysqli($host, $user, $pass, $db_name);
if($mysqli->connect_error)
{
die("Having some trouble pulling data");
exit();
}
Assuming the connection was made successfully we move on to checking for an ID being set. In this case I check it via an URL param assumed to be id. You can make it more complex, or take a different approach here.
if(isset($_GET['id']))
{
$id = htmlentities($_GET['id']);
$query = "SELECT * FROM table WHERE id = " . $id;
}
else
{
// if no ID is set, just bring all the results down
// then you can modify how, and which table the results
// are being used.
$query = "SELECT * FROM table ORDER BY id"; // the query can be changed to whatever you would be prefer
}
Once we have decided on a query we go on to start querying the database for information. I have three steps:
Check query >
Check table for records >
Loop through roles and create an object for each.
if($result = $mysqli->query($query))
{
if($result->num_rows > 0)
{
while ($row = $result->fetch_object())
{
// you can set up your element here
// you can set it up in whatever way you want
// to see your product being displayed, by simply
// using $row->column_name
// each column becomes an object here. So your id
// column would be pulled using $row->id
echo "<h1>" . $row->name . "</h1>";
echo "<p>" . $row->description . "</p>";
echo "<img src=" . $row->image_path . ">";
// etc ...
}
}
else
{
// if no records match the selected ID
echo "Nothing to see here...";
}
}
else
{
// if there's a problem with the query
echo "A slight problem with your query.";
}
$mysqli->close(); // close connection for safety
?>
I hope this answers your question and can help you if you are still stuck on this problem. This is the bare skeleton of what you can do with MySQLi and PHP, you could always use some Ajax to make the page more interactive, and user-friendly.
Adding content to a page on click needs to be done in either Javascript or in JQuery.
You can use ajax call to retrive the needed data from php page, Syntax is here.
Or you can also load a php page to a div content with .load() function in JQuery, Syntax is here.

Can you use $_POST in a WHERE clause

There are not really and direct answers on this, so I thought i'd give it a go.
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id = " .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
The above code is supposed to set the variable $myid as the posted content of id, the variable is then used in an SQL WHERE clause to fetch data from a database according to the submitted id. Forgetting the potential SQL injects (I will fix them later) why exactly does this not work?
Okay here is the full code from my test of it:
<?php
//This includes the variables, adjusted within the 'config.php file' and the functions from the 'functions.php' - the config variables are adjusted prior to anything else.
require('configs/config.php');
require('configs/functions.php');
//Check to see if the form has been submited, if it has we continue with the script.
if(isset($_POST['confirmation']) and $_POST['confirmation']=='true')
{
//Slashes are removed, depending on configuration.
if(get_magic_quotes_gpc())
{
$_POST['model'] = stripslashes($_POST['model']);
$_POST['problem'] = stripslashes($_POST['problem']);
$_POST['info'] = stripslashes($_POST['info']);
}
//Create the future ID of the post - obviously this will create and give the id of the post, it is generated in numerical order.
$maxid = mysql_fetch_array(mysql_query('select max(id) as id from repairs'));
$id = intval($maxid['id'])+1;
//Here the variables are protected using PHP and the input fields are also limited, where applicable.
$model = mysql_escape_string(substr($_POST['model'],0,9));
$problem = mysql_escape_string(substr($_POST['problem'],0,255));
$info = mysql_escape_string(substr($_POST['info'],0,6000));
//The post information is submitted into the database, the admin is then forwarded to the page for the new post. Else a warning is displayed and the admin is forwarded back to the new post page.
if(mysql_query("insert into repairs (id, model, problem, info) values ('$_POST[id]', '$_POST[model]', '$_POST[version]', '$_POST[info]')"))
{
?>
<?php
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id=" .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row = mysql_fetch_array($query))
{
$model = $row['model'];
$problem = $row['problem'];
}
//Select the post from the database according to the id.
$query2 = mysql_query('SELECT * FROM devices WHERE version = "'.$model.'" AND issue = "'.$problem.'";') or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query2) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row2 = mysql_fetch_array($query2))
{
$price = $row2['price'];
$device = $row2['device'];
$image = $row2['image'];
}
?>
<?php echo $id; ?>
<?php echo $model; ?>
<?php echo $problem; ?>
<?php echo $price; ?>
<?php echo $device; ?>
<?php echo $image; ?>
<?
}
else
{
echo '<meta http-equiv="refresh" content="2; URL=iphone.php"><div id="confirms" style="text-align:center;">Oops! An error occurred while submitting the post! Try again…</div></br>';
}
}
?>
What data type is id in your table? You maybe need to surround it in single quotes.
$query = msql_query("SELECT * FROM repairs WHERE id = '$myid' AND...")
Edit: Also you do not need to use concatenation with a double-quoted string.
Check the value of $myid and the entire dynamically created SQL string to make sure it contains what you think it contains.
It's likely that your problem arises from the use of empty-string comparisons for columns that probably contain NULL values. Try name IS NULL and so on for all the empty strings.
The only reason $myid would be empty, is if it's not being sent by the browser. Make sure your form action is set to POST. You can verify there are values in $_POST with the following:
print_r($_POST);
And, echo out your query to make sure it's what you expect it to be. Try running it manually via PHPMyAdmin or MySQL Workbench.
Using $something = mysql_real_escape_string($POST['something']);
Does not only prevent SQL-injection, it also prevents syntax errors due to people entering data like:
name = O'Reilly <<-- query will bomb with an error
memo = Chairman said: "welcome"
etc.
So in order to have a valid and working application it really is indispensible.
The argument of "I'll fix it later" has a few logical flaws:
It is slower to fix stuff later, you will spend more time overall because you need to revisit old code.
You will get unneeded bug reports in testing due to the functional errors mentioned above.
I'll do it later thingies tend to never happen.
Security is not optional, it is essential.
What happens if you get fulled off the project and someone else has to take over, (s)he will not know about your outstanding issues.
If you do something, finish it, don't leave al sorts of issues outstanding.
If I were your boss and did a code review on that code, you would be fired on the spot.

Categories