deleting records from mysql table - php

Continuing with my simple CRUD, I'm stuck again...
So I have a table created called "usuaris" and a column called "id" which is my auto-increment and then another column called "usuari_nom". Now, I want to add "delete function", so when I am displaying the records of my table I've added a to delete it:
<div id="main">
<?php
global $conn;
$query = "SELECT * FROM usuaris";
if($grup_usuaris = mysqli_query($conn, $query)) {
echo "<table>";
echo "<tr><th>Usuaris</th><th>Accions</th></tr>";
while($row = mysqli_fetch_assoc($grup_usuaris)) {
echo "<tr><td>" . $row['usuari_nom'] . "</td><td>Eliminar usuari</td></tr>";
}
echo "</table>";
echo "+ Afegeix Usuari";
mysqli_free_result($grup_usuaris);
} else {
echo "query failed";
echo("Error description: " . mysqli_error($conn));
}
?>
</div>
So now, If I click on "eliminar usuari" it goes to the file where I am adding the query to delete, plus the id of that user; for example: "http://localhost/calendario/elimina_usuari.php?subject=6". But then, in the file elimina_usuari.php, how do I select the id to know what record to delete?
I've thought with $_GET but it doesn't seems to work, either with $_POST:
elimina_usuari.php
<?php
global $conn;
$usuari_id = $_GET['id'];
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
$result = mysqli_query($conn, $query);
if ($result && mysqli_affected_rows($conn) == 1) {
redirect_to("calendari.php");
} else {
echo "no eliminat";
}
?>
Any clue how can I get its id? Should I take it from the url somehow?
Thanks

you're doing fine.
just need to change this
$usuari_id = $_GET['id'];
to
$usuari_id = $_GET['subject'];
as you're setting subject instead of id in your url
http://localhost/calendario/elimina_usuari.php?subject=6
^
and if you want to process id, like $_GET['id'], you need to change URL.
"http://localhost/calendario/elimina_usuari.php?id=6"
^ change here
EDIT
as per your comment,
you can use any $variable to $_POST or $_GET, it has nothing to do with the database column name.
Like you can use following.
"http://localhost/calendario/elimina_usuari.php?eve_mf=6"
and on elimina_usuari.php page,
$id = $_GET['eve_mf'];
and second part, why can I do that and I don't need to call it id as it is called in my db table?
Again, it's not the issue what you call variables in you local environment, all you to do(and should take care of) is to put right parameters in your sql query.
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
Here id is the name of your column name in your database. You can't change it here if you even want it to.
however, $usuari_id is your local variable, and you can change it whatever you want.
Hope I've explained what you're looking for :)

You can get the id with $_GET['subject'].
Please be aware about SQL injection as you are wrongly get the id of the user to be deleted:
$usuari_id = mysqli_real_escape_string($conn, $_GET['subject']);

<?php
global $conn;
$usuari_id = $_GET['subject'];
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
$result = mysqli_query($conn, $query);
if ($result && mysqli_affected_rows($conn) == 1) {
redirect_to("calendari.php");
} else {
echo "no eliminat";
}
?>

You just need to Get the exact variable name or parameter name which you have sent with your url
I mean see your url contains subject=6
that means you have to get subject instead of id;
please replace this code
$usuari_id = $_GET['id'];
to
$usuari_id = $_GET['subject'];

try this in elimina_usurai.php
<?php
global $conn;
$usuari_id = $_GET['subject'];
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
$result = mysqli_query($conn, $query);
if ($result && mysqli_affected_rows($conn) == 1) {
redirect_to("calendari.php");
} else {
echo "no eliminat";
}
?>

Related

Reusable Delete PHP Statement?

I was wondering how to make my code less cluttered and more re-usable. I have seperate delete.php files for deleting specific data from pages. For example I have Genre,Platform and Customers.
Genre Delete
//get value of ?id= from the url
$DeleteID = $_GET['id'];
echo $DeleteID;
require("connect.php");
//Linking
$link = connectToDB();
//SQL Query
$sql = "DELETE
FROM Genre
WHERE GenreID = ".$DeleteID;
//Execute
$result = $link->query($sql);
//Check
if ($link->affected_rows == 1) {
header( "Location: genre.php" );
}
else {
echo "Didn't Work";
}
Platform Delete
<?php
session_start();
//get value of ?id= from the url
$DeleteID = $_GET['id'];
echo $DeleteID;
require("connect.php");
//Linking
$link = connectToDB();
//SQL Query
$sql = "DELETE
FROM Platform
WHERE PlatformID = ".$DeleteID;
//Execute
$result = $link->query($sql);
//Check
if ($link->affected_rows == 1) {
header( "Location: platform.php" );
}
else {
echo "Didn't Work";
}
I wanted to know if it was possible for these to be made into 1 delete file that I can alter, or statement. The user is redirected to these pages through a button in a table, and it redirects to the delete page with the PK ID of the record.
You could pass another variable into the URL to indicate what you want to be deleted (Genre, Platform, Customers, etc.).
Granted, it becomes very easy to create a mess of if/else statements, but it would keep all the functionality limited to one file.
you could write a small helper function:
function deleteMe($link, $table, $id){
//SQL Query
$id = intval($id);
$sql = "DELETE
FROM `$table`
WHERE `{$table}ID` = ".$id;
//Execute
$result = $link->query($sql);
return $link->affected_rows;
}
You could then include this on a single delete page and use it as needed, passing your table and id in with GET params.

Getting data from POST [id] form in PHP

On a table that displays data from a database, I have a form that has a text area on which a user can type a receipt number and submit to save in a database for a specif row. The PHP code below is what updates the database after the form is submitted.
I want to pick the rest of the details for the specific row so I used the $_POST['id'] on which the receipt has been submitted. The id is the primary key. I'm however having a challenge since I can't fetch data from the database using $id = $_POST['id'];I created before outside the function The update statement works perfectly but the SELECT STATEMENTdoesn't . How do I go about it? Any one?
if(isset($_POST['submit'])) {
$rec = $_POST['receipt'];
$id = $_POST['id'];
//reate connection
$sql = "UPDATE customer SET `receipt` = '".$_POST['receipt']."', `date_entered` = NOW(), `receipt_lock` = 1 WHERE `id` = '".$_POST['tid']."' AND receipt_lock = 0";
if ($conn->query($sql) === TRUE) {
// echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
exit();
$conn->close();
}
function wall(){
global $recp;
global $id;
// Create con
$sql = "SELECT * FROM customer WHERE id ='$id'";
$result1 = mysqli_query($conn, $sql);
$resultarr = mysqli_fetch_assoc($result1); // fetch data
$name = $resultarr['name'];
echo "$name"; //Does not display
$amount = $resultarr['amount'];
$transaction_id = $resultarr['trans_id'];
$date = $resultarr['time_paid'];
}
else {
echo "this is not right!;
}
wall();
Ignoring all the (valid) questions about SQL security and just addressing your problem - how about passing the $id variable as a parameter to your wall function.?
wall($id);
function wall($id){
$sql = "SELECT * FROM customer WHERE id ='$id'";
// ... use prepared statements for security...
...
}
Looks like you are using $_POST['tid'] instead of $_POST['id'] or $id in your SQL-query.
What you are doing there is a big nono, in terms of security. Make sure you escape your POST parameters before adding them inside your query.
$id = $_POST['id'];
$id = mysqli_real_escape_string($conn, $id);
http://php.net/manual/ro/mysqli.real-escape-string.php
Think about sending data as parameters of a function function wall($id) instead of a global parameter.

whats wrong with this part of php code?

first I have a login form in c# that asks the user to input his email and password then these are data are sent to the domain then I retrieve it in php so I wrote a sql query to get the logged in user id and this works fine till the
if(isset($_POST['y']))
inside of it there is an insert query this query works but doesn't insert the user id ! I tried to figure it out but I dont know whats the problem .
here's the code :
<?php
session_start();
$con = mysqli_connect("mysql7.000webhost.com","a1945567_host","12345678ab","a1945567_db");
$sql = "SELECT ID FROM user WHERE Email = '".$_GET["txt_UserName"]."'AND Password = '".sha1($_GET["txt_Password"])."'";
$result = $con->query($sql);
$
$row = mysqli_fetch_array($result,MYSQLI_NUM);
$_SESSION['ID'] = $row[0] ;
echo "SUCCESS";
echo $usrID = $row[0];
if(isset($_POST['y'])){
$sql = "INSERT INTO `question13_interaction` (uid,no_0,no_1) VALUES ('".$usrID."','".$_POST['y']."',0)";
$con->query($sql);
// mysqli_query($con,$sql);
}
else if(isset($_POST["z"])){
//$sumcount = "INSERT INTO question13_interaction (sumcount)";
//$result = mysqli_query($con,$sumcount);
$sql1 = "INSERT INTO question13_interaction(uid,no_1,no_0) VALUES('".$row[0]."','".$_POST["z"]."',0)";
mysqli_query($con,$sql1);
}
//}
/*else
{
echo "FAILED";
}*/
?>
you have an extra"$" in the code:
$result = $con->query($sql);
$
probably should just be :
$result = $con->query($sql);
also I don;t think you want the echo in this statement - it will probably not set it to the correct value for your query:
echo $usrID = $row[0];
should be
$usrID = $row[0];
Except for the redundant "$", there is another question. There should be a white space between single quote and "AND", or mysql cann't parse the query correctly

How do i make delete button work?

I am trying to make a delete button but it doesn't work.
$interogare = "SELECT * FROM comments JOIN users ON users.user_id = comments.user_id WHERE movie_id='$movie_id' ORDER BY date_posted DESC";
$result = mysqli_query($dbc, $interogare) or die(mysqli_error($dbc));
while($rand = mysqli_fetch_assoc($result))
{
echo 'Delete';
if(isset($_GET['com'])) {
$haidi = mysqli_real_escape_string($dbc,$_GET['com']);
$sql_del = "DELETE FROM comments WHERE comment_id = '$haidi'";
mysqli_query($dbc,$sql_del);
header('location: film.php?id='.$_GET['id'].'');
exit();
}
}
When i click the delete link it takes me to
film.php?com='.$rand['comment_id'].'
page but nothing happens,it should delete my comment and take me back to the page where the comment was.Can someone please help me figure this out ?
does this work?
<?php
$query = "
SELECT *
FROM comments
JOIN users ON users.user_id = comments.user_id
WHERE movie_id=" . $movie_id . "
ORDER BY date_posted DESC";
$result = mysqli_query($dbc, $query) or die(mysqli_error($dbc));
if (isset($_GET)) {
$getData = $_GET;
}
while ($rand = mysqli_fetch_assoc($result))
{
echo 'Delete';
if (isset($getData) && $getData['com']) {
$id = mysqli_real_escape_string($dbc, $getData['com']);
$query = "
DELETE FROM comments
WHERE comment_id=" . $id;
$result = mysqli_query($dbc, $query);
if($result)
{
header('location: film.php?id=' . $id . '');
}
exit();
}
}
i would rather grab the post once, and then make sure we are passing the same object around, so i set GET to a var. then, i didnt like the way the ids were being set in the query, because it wasnt as easy to see. then i got down to the way you were creating the header, and it looked like you were passing the id from some GET data, instead of the id you just extracted and set to a varibale, see above..., or was that your intention to use $_GET['id'] for that actually instead?
also, you might need to pass your data link in the mysqli_real_escape_string() method

While loop not printing all answers

This might be really simple, but i cannot figure out the problem with this code:
$sql = mysql_query("select * from Temporary_Stock_Transfer where Emp_ID = '$emp_id' and Company_ID = '$company_id'");
if(mysql_num_rows($sql) == 0) {
echo "<tr><td colspan='3'><i>You currenty have no items</i></td></tr>";
}else {
while($row = mysql_fetch_array($sql)) {
echo mysql_num_rows($sql);
echo 'reached';
$book_id = $row[1];
$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
echo "<tr><td>".$sql[0]."</td><td>".$row[2]."</td><td><span class='label label-important'>Remove</span></td></tr>";
}
}
Now based on my database the query is returning 2 results, the echo mysql_num_rows($sql) also gives out 2. However the reached is echoed only once. Does anyone see a potential problem with the code?
P.S: My bad, $sql is being repeated, that was a silly mistake
It will only echo once because of this line :
$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
your overwriting the $sql variable.
Why not just run a single query and join the data you require ?
try ($sql2 instead of $sql and $sql[0] to $sql2[0]):
$sql = mysql_query("select * from Temporary_Stock_Transfer where Emp_ID = '$emp_id' and Company_ID = '$company_id'");
if(mysql_num_rows($sql) == 0) {
echo "<tr><td colspan='3'><i>You currenty have no items</i></td></tr>";
}else {
while($row = mysql_fetch_array($sql)) {
echo mysql_num_rows($sql);
echo 'reached';
$book_id = $row[1];
$sql2 = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
echo "<tr><td>".$sql2[0]."</td><td>".$row[2]."</td><td><span class='label label-important'>Remove</span></td></tr>";
}
}
I think it'll be because you are ressetting the sql variable
$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
when you are still using it in the while loop. :P
It's probably this line:
$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
Try using a different variable name.
You are changing the $sql variable inside the loop, therefore the next time you run $row = mysql_fetch_array($sql), the value will be different (probably won't be any based on your code).
Inside the while loop you are re-using the same variable: $sql. This is used to control the terminating condition of the loop.
Using a different variable name, e.g. $sql2 should leave the original variable intact and the loop should proceed as expected.

Categories