PHP Delete Function not working - php

Have had a look around but still struggling like no tomorrow. Just trying to get a delete button working. But its made complicated because the delete function is not completed on the one file.
Users are currently on the crud/view.php file
<?php
session_start();
if(isset($_SESSION['u_uid']))
$uid = $_SESSION['u_id'];
require_once('connect.php');
$ReadSql = "SELECT * FROM `contact` WHERE users_id=$uid ORDER BY Name";
$res = mysqli_query($connection, $ReadSql);
?>
I have a few functions but my delete button is:
<td> <input type="button" onClick="deleteme(<?php echo $r['u_uid']; ?>)" name="Delete" value="Delete"></td>
Followed by:
function deleteme(delid) {
if(confirm("Are you sure you want to Delete?")){
window.location.href='delete.php?del_id='+delid;
}
}
Leading to a crud/delete.php
<?php
session_start();
if(isset($_SESSION['u_uid'])){
require_once('connect.php');
$select = "DELETE from contact where id='".$_GET['del_id']."'";
$query = mysqli_query($connection, $select) or die($select);
}else {
print_r($_GET['del_id'])
?>
I think you can have the delete function on just the view.php and get rid of the delete.php. But I'm not sure what to do.
Many thanks!

Make sure that the variables really contain something that you expect it to have, does the u_uid was really set, try printing out your delete query to make sure that it builds a valid SQL statement.
Or you can try enclosing your table fields with back-ticks, like you did on your select statement.
It is very advisable also to use prepared statements to make your script more secured.

Related

Can't delete record from table in PHP by pressing submit button

I am trying to delete a record from my database when I press the submit button (input with type of submit) but this code is not working and I can't figure out why.
Here is the button code:
<input type="submit" value="Delete Selected Weapon" class="mybutton" name="Submit">
Here is the PHP code:
<?php
if(isset($_POST['Submit']))
{
require_once('../connect.php');
$selected = $_POST['deleteweaponname'];
$sql = "DELETE FROM weapon WHERE weaponname = $selected";
$result = $connect -> query($sql);
if(!$result)
{
echo "Could not delete record";
}
$connect -> close();
}
?>
The $selected variable is supposed to get the value of a select
I don't receive my error message either, when I press the button it just refreshes the site as if there were no PHP code attached to the button.
I also know that my connect.php is working because in another file it works.
I also tried isset($_POST['submit']) but that didn't work either.
I tried putting the code at the end of the file, and now it's in the front of it but neither seems to work.
The simple solution is quote string value:
$sql = "DELETE FROM weapon WHERE weaponname = '$selected'";
But this solution is open to SQL injection. So best way is using prepared statements:
-- set placeholder for variable
$sql = "DELETE FROM weapon WHERE weaponname = ?";
-- prepare statement
$stmt = $connect->prepare($query);
-- execute statement using variable
$stmt->execute([$selected]);

Deleting from mysql php

I just uploaded imaged to a users account and know I'm trying to delete one of them, however when I click the delete button it just refreshes the page
this is the code in profile.php that links it to the delete.php
echo '<li>Delete Edit Download </li>';
and this is my delete.php:
<?php
include("db/connect.php");
include("profile.php");
$sql = "SELECT * FROM users DELETE upload WHERE user_id = file_id";
mysqli_query($con, $sql);
mysqli_close($con);
?>
Burn your code with fire. Burn it! It is ALL wrong!
1: Echoing a variable
If you're in the middle of echoing some text and you want a variable, don't try opening a second PHP block, that's not going to work. Instead:
echo 'something ' . $variable . ' more text';
2: Destructive actions with GET
Never, EVER use <a href="..."> to perform destructive actions, especially not deletion. EVER. You should use a form instead, like this:
<form action="delete.php" method="post">
<input type="hidden" name="file_id" value="<?php echo $file_id; ?>" />
<input type="submit" value="Delete file" />
</form>
Bonus points if you add something like onSubmit="return confirm('Are you SURE you want to delete this?');" or similar.
3: Your delete query
Not sure how you can mess this up, but apparently...
$sql = "DELETE FROM `upload` WHERE `file_id` = ".intval($_POST['file_id']);
You may want to (read: ABSOLUTELY SHOULD!) add some code to check if the current user actually has permission to delete the given file, unless you want people deleting everything.
You cannot perform two queries like this -
$sql = "SELECT * FROM users DELETE upload WHERE file_id = file_id";
Change it to this -
$sql = "DELETE FROM upload WHERE file_id = file_id";
I'm unsure how you're passing variables around and I am assuming that you're binding file_id properly.

Query result into variable

I'm making a website. I want it so that I can put records into the database via my website. So first I need to select the id from which record I want to change. Then I want to put the values of the selected id into a variable. The I want to put the variable into a form value.
I'm trying to make something similar to phpmyadmin. If you click on the pencil you go to a form were everything is complete and you can just change the things you want to change and save it into the database.
wijzigen.php:
<form id="form1" name="form1" method="post" action="set_wijziging.php">
<h1>Selecteer het vuurwerkid van het product dat u wilt wijzigen</h1>
<p>Vuurwerkid <br>
<input type="text" name="vuurwerkid" id="vuurwerkid" />
<input type="submit" name="wijzigen" id="wijzigen" value="wijzigen"/>
</form>
and here is the part were I put what I typed in in the form into a variable.
<?php
$vuurwerkid=$_POST["vuurwerkid"];
?>
Then I'm trying to make a query wich only selects the things were vuurwerkid='$vuurwerkid'
So here I try to put the results of the query into a variable. But this doesn't seem to work.
set_wijziging.php:
<?php
include("connect.php");
$vuurwerkid=$_POST["vuurwerkid"];
$query = "SELECT * FROM vuurwerk_info WERE vuurwerkid='$vuurwerkid'";
$resultaat = MySQL_query($query);
while ($row = MySQL_fetch_array($resultaat))
{
$vuurwerkid="$row["vuurwerkid"]";
$naam=$row["naam"];
$prijs=$row["prijs"];
$soort=$row["soort"];
$cat_vuurwerk=$row["cat_vuurwerk"];
$aantal=$row["aantal"];
}
?>
I'm just started learning PHP
Your where spelling is wrong in your query
Try this
$query = "SELECT * FROM vuurwerk_info WHERE vuurwerkid='$vuurwerkid'";
I miss that last time Change this line as well
$vuurwerkid="$row["vuurwerkid"]";
To this
`$vuurwerkid=$row["vuurwerkid"];
//Remove the Double queite. As its variable not string`
although function name are case-incensitive. But change theese lines as well
chnage this
$resultaat = MySQL_query($query);
while ($row = MySQL_fetch_array($resultaat))
To this
$resultaat = mysql_query($query);
while ($row = mysql_fetch_array($resultaat))
Note I change nothing in the below line. I just used the small letter to right those function
Please learn MYSQLI_ OR PDO
As mysql function are depriciated.
You should change your $query to
$query = "SELECT * FROM vuurwerk_info WHERE vuurwerkid='$vuurwerkid'";
Also try to echo your query to see if it's correct.
Finally as others pointed out you should stop using mysql_* and switch to msqli or PDO.

PHP form search for MySQL DB

I need some help getting a search function to work. I have previously coded something to work similar to this, where if I click on a hyperlink, I'm able to carry a variable forward and then assign this into an SQL script so it pulls only this one thing back from the DB. (Predefined variable, and not user input). I've tried modifying the script I've been using to allow for a form based text box to have user input which is then searched through a single database field, with a LIKE statement.
This is what I have, and it's not returning anything.
Input Form
<form class="formFormat" method="post" action="SearchResult.php">
<label class="lableInput2">Key Words</label>
<input type="text" class="textInput" name="JobDetails" />
<input type="image" src="img/blue/buttonsearch.jpg" value="search" class="buttonInput" alt="Submit Form" border="0" />
</form>
Returning Page
<?php
include('conn_mysql.inc');
include('corefuncs.php');
// create database connection
$conn = dbConnect('query');
// initialize flag
$deleted = false;
// get details of selected record
if ($_GET && !$_POST) {
// check that primary key is numeric
if (isset($_GET['JobDetails']) && is_numeric($_GET['JobDetails'])) {
$JobDetails = $_POST['JobDetails'];
}
else {
$JobDetails = NULL;
}
if ($JobDetails) {
$sql = "SELECT * FROM jobs WHERE JobDetails LIKE '%JobDetails%'";
$result = mysql_query($sql) or die (mysql_error());
$row = mysql_fetch_assoc($result);
}
}
?>
<p><h1><?php echo ($row['JobTitle'].'<span class="jobid"> #'.$row['IDJobs'].'</span>');?></h1></p>
<p><strong><?php echo ($row['Location']); ?></strong></p>
<p><strong>£<?php echo ($row['JobValue']); ?>.00</strong></p>
<p><strong>www.companyurl.com - BAD IDEA?</strong></p>
<p><strong>Open for Bidding</strong></p>
<br />
<p><span class="jobid">Job Posted: <?php echo ($row['JobPostDate']); ?></span></p>
<p><?php print ($row['JobDetails']); ?></p>
<p><span class="jobid">Job Deadline: <?php echo ($row['JobDeadline']); ?></span></p>
I know that I need to loop the output, so it displays more than one, but at the moment it simply returns the following error for every field (obv the line changes depending on what's trying to extract.
"( ! ) Notice: Undefined variable: row in
C:\wamp\www\ReEmployWork\SearchResult.php on line 54"
Can anyone assist? I'm a bit lost with this, and I believe I'm either going in the wrong direction or just missing something.
You missed $ before the variable name. Instead of:
$sql = "SELECT * FROM jobs WHERE JobDetails LIKE '%JobDetails%'";
write:
$sql = "SELECT * FROM jobs WHERE JobDetails LIKE '%$JobDetails%'";
You left your $ before JobDetails in you query.
Also remeber to use http://php.net/manual/en/function.mysql-real-escape-string.php
A suggestion:
$escaped_value = mysql_real_escape_string($JobDetails)
$sql = "SELECT * FROM jobs WHERE JobDetails LIKE '%$escaped_value%'";
For future readers. I scrapped the code I tried to modify and I took it from the beginning. There's enough information above for anyone to do this. Have a go, and you may end up with a result similar to what I coded.
$JobDetails = $_POST['JobDetails'];
$JobDetails = mysql_real_escape_string($JobDetails);
$sql = "SELECT * FROM `jobs` WHERE `JobDetails` LIKE '%{$JobDetails}%'";
$result = mysql_query($sql) or die (mysql_error());
?>
The above is what I coded and it runs like a dream. You make a lot more mistakes modifying code than you do, if you just code from scratch, so if you're learning dabble and play with code already wrote, but if you need something yourself which is unique then you're best starting from scratch.

How to Remove a Database Entry when a Link is Clicked

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.

Categories