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.
Related
Hello I have a table in my database called files and I want to delete a row by its id but whenever I run the code I get the response "Successfully Deleted" but it does not delete the row.
This is my code.
I would appreciate any help.
<?php
require "conn.php";
$id = $_POST["id"];
if($conn){
$sql = "SELECT * FROM files WHERE id LIKE '$id'";
$query = mysqli_query($conn,$sql);
if (mysqli_num_rows($query)>0) {
$sqlDelete = "DELETE FROM files WHERE id LIKE '$id'";
echo "Successfully Deleted";
} else {
echo "Failed to delete";
}
} else {
echo "Connection Error";
}
?>
I guess the issue is because id in database is Int but I'm passing Strings to it so how should I solve this problem?
After you assign
$sqlDelete = "DELETE FROM files WHERE id LIKE '$id'";
you need to
if (mysqli_query($conn, $sqlDelete))
{
echo "Successfully Deleted";
}
in order to execute the delete query. BTW the select statement is redundant.
Please note that your code is very unsafe and SQLi prone. Use prepared statements instead of text substitution.
Try this
$sqlDelete = "DELETE FROM files WHERE id = ".$id;
mysqli_query($conn,$sqlDelete );
I can't update two table in one query. Is there any other way to do it? below is an example of my code.
$id = $_GET['idnum'];
$txtEditUsername=$_GET['txtEditUsername'];
$txtlname=$_GET['txtlname'];
$txtfname=$_GET['txtfname'];
$txtgender=$_GET['txtgender'];
$txtbdate=$_GET['txtbdate'];
$txtnationality=$_GET['txtnationality'];
$txtcnum=$_GET['txtcnum'];
$txtaddress=$_GET['txtaddress'];
$sql = "UPDATE users SET u_usernamee = '$txtEditUsername' WHERE u_uid = '$id'";
$sql = "UPDATE people SET ppl_lname = '$txtlname', ppl_fname = '$txtfname', ppl_gender = '$txtgender', ppl_bdate = '$txtbdate', ppl_nationality = '$txtnationality', ppl_cnum = '$txtcnum', ppl_address = '$txtaddress' WHERE ppl_id = '$id'";
if (mysqli_query($conn, $sql)) {
} else {
echo "Error ".mysqli_error($conn);
}
You can use mysqli_multi_query like this
$sql = "UPDATE users SET u_usernamee = '$txtEditUsername' WHERE u_uid = '$id'";
$sql .= "UPDATE people SET ppl_lname = '$txtlname', ppl_fname = '$txtfname',
ppl_gender = '$txtgender', ppl_bdate = '$txtbdate', ppl_nationality = '$txtnationality', ppl_cnum = '$txtcnum', ppl_address = '$txtaddress' WHERE ppl_id = '$id'";
if (mysqli_multi_query($conn, $query)) {
do {
/* sStockage du premier résultat */
if ($result = mysqli_store_result($conn)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);
}
mysqli_free_result($result);
}
/* Affichage d'une séparation */
if (mysqli_more_results($conn)) {
printf("-----------------\n");
}
} while (mysqli_next_result($conn));
}
And here you can know more about it https://www.php.net/manual/en/mysqli.multi-query.php
You should use different name for variables like $sql and $sql2, but you can even use one query, try this:
UPDATE users, people
SET users.u_username = '$txtEditUsername',
people.ppl_lname = '$txtlname',
people.ppl_fname = '$txtfname',
// AND SO ON
WHERE
users.u_uid = '$id'
AND people.ppl_id = '$id';
EDIT
However, like someone else said, you can be victim of sql injection.
Try to use prepared statement with PDO, give a look here
The problem is here:
$sql = "UPDATE users ...";
$sql = "UPDATE people ...";
You are using the same variable to execute two different queries. The second statement overrides the first one, erasing it. That's why the users table isn't updated.
$usersSQL = "UPDATE users SET u_usernamee = '$txtEditUsername' WHERE u_uid = '$id'";
if (!mysqli_query($conn, $usersSQL)) {
echo "Error while updating users table: ".mysqli_error($conn);
// Eventually, consider to exit the function..
}
$peopleSQL = "UPDATE people SET ppl_lname = '$txtlname', ppl_fname = '$txtfname', ppl_gender = '$txtgender', ppl_bdate = '$txtbdate', ppl_nationality = '$txtnationality', ppl_cnum = '$txtcnum', ppl_address = '$txtaddress' WHERE ppl_id = '$id'";
if (!mysqli_query($conn, $peopleSQL)) {
echo "Error while updating people table: ".mysqli_error($conn);
}
Last but not least
Never ever use unsanitized data. Always filter and validate user's data.
Adding validation, you'll avoid passing invalid values to the query (example: ppl_lname's length is maximum 50 chars, and user sends 51 chars).
And most important, NEVER use user's data directly to a SQL query, because you are exposing your database to a serious risk.
Give a read to this link, or this one, they will explain what's the problem when using unsanitized data.
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.
I am trying to make a deactivate account so ...When I click a link I want the account status to be updated in the database so it will turn 0. Every time I click the link here nothings happens it just re direct me to another page this my code for the deactivating
<?php
include "../includes/dbcon.php";
if(isset($_GET['user_id']))
{
$result = mysql_query("SELECT user_id FROM users WHERE user_id = $user_id");
while($row = mysql_fetch_array($result))
{
echo $result;
$status = $row($_GET['status']);
if($status == 1)
{
$status = 0;
$update = mysql_query("Update users set status = $status");
header("location: admin_manage_account.php");
}
else
{
echo "Already deactivated";
}
}
}
?>
I don't know what is your problem exactly, but why do you select the id based on the id?
Why don't you do something like "UPDATE users SET status = $status WHERE user_id = $user_id" in the first place?
In your example you don't even have a condition in the update statement...
If you want to "toggle/flip" a value you can just do something like:
UPDATE users SET status = NOT status WHERE user_id = $user_id
This way, true become false, false become true, etc.
You code is not ok on many reasons. But the most serious problem is SQL Injection attack!
If attacker put non-expected value to your user_id param, your sql like that "SELECT user_id FROM users WHERE user_id = $user_id" and that "Update users set status = $status WHEREuser_id= '$user_id'" can cause very serious problems.
For example: user_id can be: "0; DROP TABLE users"
Be careful with your code, rewrite it
Too many things needed to be improved. You should not use MySQL either. Consider MySQLi or PDO. BTW here is an updated version of your own code which should work:
<?php
include "../includes/dbcon.php";
if(isset($_GET['user_id']))
{
$user_id = $_GET['user_id']; // I assume you want to capture it from URL
$result = mysql_query("SELECT user_id FROM users WHERE user_id = $user_id");
while($row = mysql_fetch_array($result))
{
// echo $result; why do you echo it? No need
/* $status = $row($_GET['status']); should be: */
$status = $row['status'];
if($status == 1)
{
$status = 0;
$update = mysql_query("Update users set status = $status WHERE `user_id` = '$user_id'");
header("location: admin_manage_account.php");
}
else
{
echo "Already deactivated";
}
}
}
?>
Previously, you were not defining $user_id. Moreover, it wasn't correct the way you were getting the status ($status) of the user.
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";
}
?>