I have a link that's generated from a entry in a database, and I need to be able to delete that link. I have the DELETE query in my PHP, and a JavaScript confirm that works just fine, but confirming won't activate the PHP query. Here's the code:
JavaScript:
<script language="JavaScript" type="text/javascript">
function deldoc(docid, docname)
{
if (confirm("Are you sure you want to delete '" + docname + "'"))
{
window.location.href = '<?php echo DIREMPLOYEE;?>?deldoc=' + docid;
}
}
</script>
PHP:
if(isset($_GET['deldoc'])){
$deldoc = $_GET['deldoc'];
$deldoc = mysql_real_escape_string($deldoc);
$sql = mysql_query("DELETE FROM Documents WHERE docid = '$deldoc'") or die(mysql_error());
$_SESSION['success'] = "Document Deleted";
header('Location: ' .DIREMPLOYEE);
exit();
}
When I press the OK button on the Confirm popup, it takes me to the Index page, but it's not deleting the document, and it's not giving me an error. Instead, it just tacks the docid onto the end of the directory URL, so it looks like this:
http://domain.com/employee?deldoc=7
Any ideas on how I can fix this?
Your SQL query should be something like this:
mysql_query("DELETE FROM Documents WHERE docid = '$deldoc'")
Warning:
mysql_ functions are deprecated, use mysqli or PDO. Also your code is not safe. It's vulnerable to SQL injections.
Related
So i'm trying to make some text appear on my web page after a user clicks a button and runs a mysql function, but my AJAX function is only running the mysql function without doing anything else, i'm a little confused on what exactly i'm supposed to write to get it to update my page.
AJAX:
<script>$(document).ready(function(){
var game = 69;
var review = 21;
$('#fav').click(function(){
$(document).load('core/like.php', {
thegame: game,
thereview: review
});
});
});</script>"
PHP (core/like.php)
<?php
session_start();
if (isset($_SESSION['username'])) {
require 'connect.php';
$thegame = $_POST['thegame'];
$thereview = $_POST['thereview'];
$username = $_SESSION['username'];
$datentime = date("m/d/Y h:i:s a");
$stmt = $conn->prepare("UPDATE reviews SET likes=likes+1 WHERE r_id='$thereview'");
$stmt2 = $conn->prepare("INSERT INTO likes (l_id, username, r_id, date) VALUES (NULL, '$username', '$thereview', '$datentime')");
$stmt->execute();
$stmt2->execute();
$stmt->close();
$stmt2->close();
$conn->close();
echo "<div id="content"><h1>THIS IS A TEST</h1></div>";
exit();
} else {
echo "<h1>ERROR</h1>";
}
?>
Also, it only runs the mysql query when i use "document" as the jQuery selector. If i try and use a specific div like $(#abox).load('core/like.php'.. it does nothing. If i try to add a selector at the end to specify what content from the php file i want to return like $(document).load('core/like.php #content'.., it also does nothing.
It seems that there are two problems:
There are nested double quotes in the PHP:
echo "<div id="content"><h1>THIS IS A TEST</h1></div>";
Use single quotes for the outer ones:
echo '<div id="content"><h1>THIS IS A TEST</h1></div>';
Use quotes around the jQuery selector:
$(#abox).load('core/like.php'...
Like this:
$("#abox").load('core/like.php'...
Also, please take serious note of the comment about SQL injection.
I'm building PHP application for process employee leave records. In this application the main screen populate database records and action buttons. when user click the action button it take the database id from the table and go through another file to delete that record and then redirect back to the same page. This mechanism implemented using HTML _GET method. that means anyone can see the row ID in the URL feed and if anyone request this url with different row ID, PHP file delete the record since any other security measures not taken place in to prevent that. and also this application not using any kind of session.
this is my href code for the task I mentioned above.
echo "<a href='rejectone.php?id=$lvid' class='btn btn-danger btn-xs m-r-1em'>Cancal</a>";
and this is my rejectone.php code
<?php
$lid =$_GET['id'];
include 'database.php';
$accval = "Accept";
try {
$query = "UPDATE leavesrecords SET leavestatus = 'Reject' WHERE lvid = '$lid'";
$stmt = $con->prepare( $query );
$stmt->bindParam(1, $id);
$stmt->execute();
}
catch(PDOException $exception){
die('ERROR: ' . $exception->getMessage());
}
header( "refresh:0;url=bs.php" );
?>
I have two questions
1.) How can I run the rejectone task inside the same PHP file without redirecting to another PHP file
2.) How can I use HTML _POST method instead of get method to transfer data if I still use jejectone.php file
thanks!!
First of all change your line:
echo "<a href='rejectone.php?id=$lvid' class='btn btn-danger btn-xs m-r-1em'>Cancal</a>";
to
echo 'Cancal';
If you haven't included jQuery on your site, you can do it by adding this script to your page, just before closing
</head> tag
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
Add this JavaScript file to the bottom of your page, just before closing </body>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click', '.delete-item', function(e){
e.preventDefault();
if(!confirm('Are you sure you want to delete this item?')) return false;
$.post('bs.php', {'id': t.attr('primary-key'), 'delete_item': 1}, function(e){
window.location = 'bs.php';
})
})
})
</script>
Copy your rejectone.php to bs.php, but make these changes:
if(isset($_POST['delete_item']))
{
$lid = (int)$_POST['id'];
include 'database.php';
$accval = "Accept";
try {
$query = "UPDATE leavesrecords SET leavestatus = 'Reject' WHERE lvid = :lid ";
$stmt = $con->prepare( $query );
$stmt->bindParam(':lid', $lid );
$stmt->execute();
}
catch(PDOException $exception){
die('ERROR: ' . $exception->getMessage());
}
}
That is it.
Use ajax post method. See Full example of accepted solution with sample code for more details here : Delete MySQLi record without showing the id in the URL
Then using jquery remove that record from the page which will give more good UI experience.
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
I have this php code :
$kid = $_GET['document'];
$url = $_GET["url"];
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("repository", $con);
$url = mysql_real_escape_string($url);
$url = htmlspecialchars($url);
$exists = mysql_query("SELECT url FROM url WHERE url = '$url' LIMIT 1");
if (mysql_num_rows($exists) == 1) {
mysql_query("DELETE FROM url WHERE url = '$url'" );
mysql_query("DELETE FROM paragraphs WHERE url = '$url'" );
}
require("/htmlpurifier-4.3.0-standalone/HTMLPurifier.standalone.php");
require("/htmlpurifier-4.3.0-standalone/HTMLPurifier.autoload.php");
include("simple_html_dom.php");
$html = file_get_html($url);
$purifier = new HTMLPurifier();
$body = $html->find('body', 0);
echo $html->find('title', 0);
$cleanbody= $purifier->purify($body);
echo $cleanbody;
echo '<script src="jquery.js" type="text/javascript"></script>';
echo '<script src="extract.js" type="text/javascript"></script>';
$html->clear();
unset($html);
What happens here is that an html file is loaded, the body is found, purified, and is extracted by "extract.js" (which calls another php script to load it into a database). What I want to happen now is get the url_id (auto incrementing field) of the inserted url and then do a redirect after ALL of this is complete (executing a mysql_query and then a header location redirect, seems to be doing this before anything is loaded into the database). Perhaps running a mysql_query for the url_id where it matches the given url, after some condition satisfies the data has finished loading?
You don't seem to understand the server/client principle. You need to remember that the PHP just generates some HTML and sends it to the client. You can't know when the client will request the execution of the other PHP script.
Furthermore, you need to learn more SQL. It doesn't make sense to use a SELECT just to detect if a row exists, and then DELETE it if it does, not using the result at all. You might as well just run the DELETE statement no matter what. If you want to know whether it DELETE'ed anything, use mysql_affected_rows(). Also, consider using prepared statements, as it make it easier to protect against SQL injection.
If the extract.js is just extracting some tag from the HTML (without user input), you could do that on the server-side, and you wouldn't have to send it to the client at all.