execute mysql DELETE query on click - php

i'm kind of a new player in php and sql field.
i'm trying to delete identity from my persons table when clicking on the remove link (or button)
can somebody tell me what am i doing wrong?
this is my php code:
<?php
$db = new DB();
$cg_id = $_SESSION['cg_id'];
$cg_address_id = $_SESSION['cg_address_id'];
$sql ="SELECT f_name, phone, c.id as idc
FROM contacts as c
WHERE c.cg_id = '$cg_id'";
$result = $db->mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<article class='contactArea'>";
echo "<a href='contacts2.php?del=".$row["idc"]."' class='deleteContact' name='remove' value='remove'>Remove</a></article>";
if(isset($_POST['idc'])){
$idco = $_POST['idc'];
$removeQuery = "DELETE FROM contacts as c WHERE id=".$idco." ";
$resultt = mysql_query($removeQuery);
if($resultt) {
header('Location: '.$_SERVER['REQUEST_URI']);
}
echo "<script>window.location.reload(true);</script>";
}
}
}else {
echo "Please edit senior profile for monitoring!";
}
?>

Try this (obviously replacing "localhost", "dbuser", "dbpassword" and "database_name" with the details for your mysql server and database):
<?php
$db = new mysqli("localhost","dbuser","dbpassword","database_name");
$cg_id = $_SESSION['cg_id'];
$cg_address_id = $_SESSION['cg_address_id'];
// I've moved the deletion code to BEFORE the select query, otherwise the
// query will be shown including the to-be-deleted data and it is then deleted after it is displayed
if(isset($_GET["del"])){ // <--- this was $_POST["del"] which would have been unset
$idc = $_GET["del"];
if($db->query("DELETE FROM contacts WHERE id=$idc")){
echo "deleted";
} else {
echo "fail";
}
}
$sql ="SELECT photo, f_name, phone, street, street_num, city, l_name, c.id as idc FROM contacts as c, address as a WHERE c.cg_id = '$cg_id' and a.id = c.address_id";
$result = $db->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<article class='contactArea'>";
echo "<article class='contact5 lior'>";
echo "<img class='CSImage' src='" .$row["photo"]."'>";
echo "<section class='generalFormTextW nameCPosition'> " .$row["f_name"]." ".$row["l_name"]."<br></section>";
echo "<section class='generalFormTextW phoneCPosition'> " .$row["phone"]."<br></section>";
echo "<section class='generalFormTextB addressCPosition'>".$row["city"].", <br> ".$row["street"]." ".$row["street_num"]. "<br></section>";
echo "<a href='contacts2.php?del=".$row["idc"]."' class='deleteContact' name='remove' value='remove'>Remove</a></article></article>";
}
}
?>
Notice that I'm changing the way you're using mysqli so that you are using it directly rather than as a member of the DB object which is the way I've seen it used elsewhere - It looks to me as if you don't actually open the database connection (although maybe you just didn't include it because it showed your password?)
**EDIT: I've changed $_POST["del"] to $_GET["del"] -- because you are setting del in a url ("contacts2.php?del=") this will be GET not POST.
**EDIT: I've moved the deletion code so that it fixes the problem where you have to refresh the page to see the data with the record deleted - previously the information was shown and THEN deleted, we want to delete THEN show.

Related

Delete a users data from SQL using PHP

Hi im trying to delete a users booking detials when the user clicks delete in my bookingbeforedeltion.php file but for some reason when I test my php file once I click delete it goes to my delete.php screen and says it failed to delete from database and has the error Undefined index: rn. Is my rn not defined? Sorry Im new to this. Here is my code below:
bookingbeforedeltion.php:
<!DOCTYPE HTML>
<html><head><title>BookingBeforeDeletion</title> </head>
<body>
<?php
include "config.php";
$DBC = mysqli_connect("127.0.0.1", DBUSER , DBPASSWORD, DBDATABASE);
if (!$DBC) {
echo "Error: Unable to connect to MySQL.\n".
mysqli_connect_errno()."=".mysqli_connect_error() ;
exit;
};
echo "<pre>";
$query = 'SELECT roomname, checkindate, checkoutdate FROM booking';
$result = mysqli_query($DBC,$query);
if (mysqli_num_rows($result) > 0) {
echo "Delete Bookings" ?><p><?php
while ($row = mysqli_fetch_assoc($result)) {
echo "Room name: ".$row['roomname'] . PHP_EOL;
echo "Check in date: ".$row['checkindate'] . PHP_EOL;
echo "Check out date: ".$row['checkoutdate'] . PHP_EOL;
?>
[Cancel]
<?php
echo "<hr />";
}
mysqli_free_result($result);
}
echo "</pre>";
echo "Connectted via ".mysqli_get_host_info($DBC);
mysqli_close($DBC);
?>
</body>
</html>
delete.php:
<!DOCTYPE HTML>
<html><head><title>BookingBeforeDeletion</title> </head>
body>
<?php
include "config.php";
$DBC = mysqli_connect("127.0.0.1", DBUSER , DBPASSWORD, DBDATABASE);
if (!$DBC) {
echo "Error: Unable to connect to MySQL.\n".
mysqli_connect_errno()."=".mysqli_connect_error() ;
exit;
};
echo "<pre>";
$roomname=$_GET['rn'];
$query = "DELETE bookingID, roomname, checkindate, checkoutdate, contactnumber,
bookingextras, roomreview, customerID, roomID FROM booking WHERE roomname =
'$roomname'";
$result = mysqli_query($DBC,$query);
if($result)
{
echo "<font color='green'> Booking deleted from database";
}
else {
echo "<font color='red'> Failed to delete booking from database";
}
?>
and I think this will help:
As mentioned above, you need to print it from the PHP
<a href= 'delete.php?rn=$result[roomname]'>
// To
<a href= 'delete.php?rn=<?= $row['roomname'] ?>'>
// Explanation:
// 1. <?= ... ?> is the short form of <?php echo ... ?>
// 2. The `roomname` came from $row, not $result ($result is the MySQLi Object)
// 3. You need to quote the `roomname` because without it `roomname` will be readed
// as Constant, and may Throw a Warning message
//
Your DELETE is incorrect, the correct one is DELETE FROM ... WHERE ...
$query = "DELETE bookingID, roomname, checkindate, checkoutdate, contactnumber,
bookingextras, roomreview, customerID, roomID FROM booking WHERE roomname =
'$roomname'";
// To
$query = "DELETE FROM booking WHERE roomname = '$roomname'";
EXTRA:
3. You can assign a default value to $roomname
$roomname=$_GET['rn'];
// To
$roomname=$_GET['rn'] ?? 'default if null';
// if the rn index doesnt exist, the $roomname value will be `default if null` instead of throwing a Warning
Try to use Prepared-Statement SQL instead of writing it. (I dont know the example, but it can prevent SQL Injection)

how to display all data on a webpage

I wrote this code to comment system on my webpage. But i want to keep showing all data on web page while another people do comment and see another people's comment
include 'connection.php';
$con1= new connection();
$db=$con1-> open();
$qry= "INSERT INTO post (content) VALUES ('".$_POST["commentEntered"]."')";
$db->exec($qry);
if(isset($_POST['Submit'])) {
if ($con1->query($qry) === TRUE) {
echo "Your Comment Successfull Submited";
} else {
echo "Error: " . $qry . "<br>" . $con1->error;
}
$sql = 'SELECT * FROM post';
$q = $db->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
$con1->close();
}
if ($_POST)
echo "<h2> Your Comment Successfully Submitted</h2> <br> ".$_POST['commentEntered']."<br>";
}
?>
after your select, inside your if($_POST) write this
while ($row = $q->fetch()) {
foreach($row as $key=>$val){
if (!is_numeric($key)) echo "<p>$key=>$val</p>";
}
}
EDIT i'm not 100% sure you can close the connection and still do a ->fetch, (I think you can but i've never tried it) so you may have to move your connection close after this (but I think you'll be alright), also I am not sure if setFetchMode will return duplicate numbered keys or not so as a precaution I have filtered for them you may not need to

PHP prevent URL input to delete row in database

I’m working on a blog website where the idea is that the current user that is logged in can edit and delete their own posts. I finally got it to work, but my question is how I can prevent that a user can write the following input in the URL and do the same actions as my delete.php action.
(Example) Manual URL input with topic_id:
/delete.php?del=133
Do anyone know how I can edit my existing code or know a better solution to the problem I will be much grateful!
This is how my code looks:
Profile.php:
if (#$_GET['id']) {
$check_d = mysql_query("SELECT * FROM users WHERE id ='".$_GET['id']."'");
while ($row_d = mysql_fetch_assoc($check_d)) {
echo "<div class='spacer'></div><h2 class='headertext'>Inlägg skapade av : ".$row_d['username']."</h2>";
$check_u = mysql_query("SELECT * FROM topics WHERE topic_creator='".$row_d['username']."' ORDER BY topic_id DESC");
while ($row_u = mysql_fetch_assoc($check_u)) {
$id = $row_u['topic_id'];
echo "<tr>";
echo "<td class='postmain'><a href='topic.php?id=$id' class='links'>".$row_u['topic_name']."<br /></a></td>";
echo "<td class='postmain'><p class='text'>".$row_u['topic_creator']."</p><br /></td>";
echo "<td class='postmain'><p class='text'>".$row_u['date']."</p><br /></td>";
if($_SESSION['username'] === $row_u['topic_creator']) {
echo "<td class='postmain'><a href='edit.php?edit=$id'><button>Redigera</button></a>";
echo "<a href='delete.php?del=$id'><button>Ta bort</button></a></td>";
}
echo "</tr>";
}
}
}
The highlighted code shows that only the current session (user) who made the post can edit and delete their own posts.
Delete.php:
if (isset($_GET['del'])) {
//getting id of the data from url
$id = $_GET['del'];
//deleting the row from table
$sql = "DELETE FROM topics WHERE topic_id='$id'";
$res = mysql_query( $sql );
//redirecting to the display page
header("Location:admin.php");
}
Using isset function is solution here . The isset function will check that whether user clicked the delete/modify link or not(i.e he pasted delete.php directly in link) . So your code will only execute when user clicks the link .
if (isset($_GET['del']))
{
// your profile.php code here
}
else
{
// error message
}
You can use the same $_SESSION logic to ensure anyone accessing the delete.php has the appropriate permissions.
if (isset($_GET['del'])) {
//getting id of the data from url
$id = $_GET['del'];
// Get the author for the specified post to ensure they are permitted to do so
// TODO
// Check that the author is the same as the $_SESSION user
if($_SESSION['username'] === $postAuthor) {
//deleting the row from table - FIX THIS (see below)
$sql = "DELETE FROM topics WHERE topic_id='$id'";
$res = mysql_query( $sql );
} else {
// User is not authorized, create error handling
// TODO
}
//redirecting to the display page
header("Location:admin.php");
}
Unrelated, beware of SQL injection. Bobby Tables is a good guide and you should not be using the mysql_ functions and should be using prepared statements.

Using PHP to submit a Vector onto MySQL to make a connection with 2 tables

i have a list of emails on a database, which are brought onto the screen, this is coming from a previous page where you choose the category to add emails into.
The idea is for the user to check in the emails he wants to add to a connecting table that will join those two.
But i seem to be having problems. I have tried editing the page where i think the problem is, which is the , but no clue as to how i should edit it.
<?php
mysql_connect("localhost","root","") or die("problema na conexao");
mysql_select_db("trabalho1");
$idcategoria = $_GET["id"];
$query = "SELECT nome,email,id FROM email";
$results = mysql_query($query) or die(mysql_error());
echo"<center>";
echo "<table border='2'>\n";
echo"<form id='formulario' name='formulario' method='post' onsubmit='return validar(this);' action='../inserir/inserirmailcat.php'>";
echo "<br>";
echo "<button type='submit'>Submeter</button>";
echo "<tr align='center'><td>Nome</td><td>Email</td><td>Adicionar a Categoria</td></tr>";
while ($row = mysql_fetch_assoc($results)) {
foreach ($row as $campo=>$valor) {
if($campo=="nome")
{
echo "<td><b></b>".$valor. "\n</td>";
}
if($campo=="email")
{
echo "<td><b></b>".$valor. "\n</td>";
}
if($campo=="id")
{
echo "<td><input name='nome[".$valor."]' type='checkbox' value='Adicionar'></td></tr>";
}
}
echo "<input type='hidden' name='categoria' value='".$idcategoria."'>";
echo "</form>\n";
}
echo "</table>\n";
echo"</center>";
?>
This first page receives the ID from the previous one, and it lists a series of emails, where i check out the ones i want to add to a new table. And i try to pass them through a vector.
<?php
mysql_connect("localhost","root","") or die("problema na conexao");
mysql_select_db("trabalho1");
$queryq = "SELECT id FROM email";
$resultsq = mysql_query($queryq) or die(mysql_error());
while ($rowq = mysql_fetch_assoc($resultsq)) {
foreach ($rowq as $campoq=>$valorq) {
$cat = $_POST["categoria"];
$username = $_POST['nome['.$valorq.']'];
if ($username != '')
{
$query = "INSERT INTO emailcategoria (email,categoria) VALUES ('".$username.",".$cat."')";
mysql_query($query) or die(mysql_error());
}
}
}
mysql_query($queryq) or die(mysql_error());
header("Location:../listar/listarcategoria.php");
?>
On this second page i try to add only the emails which have been selected onto a new table which will receive the email's ID and the category's ID, but it is giving me the following error "after a few different error's when i tried a diferent approach":
Notice: Undefined index: nome[8445] in C:\xampp\phpMyAdmin\trabalho\inserir\inserirmailcat.php on line 10
The error is given for all the email ID's.
UPDATED
Error is on this like
$username = $_POST['nome['".$valorq."']'];
Firstly, is it supposed to be 'nome' ?
Secondly change the syntax like this
$username = $_POST['nome['.$valorq.']'];
$username = $_POST['nome['".$valorq."']'];
Well that's wrong, as the syntax highlighting shows.
$username = $_POST['nome['.$valorq.']'];
Also, sanitise your input or (better) use prepared statements!
> xkcd

Display query in a div or custom location?

How could I have my database connection information at the top of my page but have the query separate from the code but still related so that I could have the print or echo displaying the retrieved images in a Div that I could place anywhere on my site?
<?php
$db = new PDO('mysql:host=host;dbname=dbname;charset=UTF-8', 'username', 'password');
$q = "SELECT badge1 FROM user_badges WHERE username='{$_SESSION['username']}' LIMIT 1";
$r = mysql_query($q);
$row = mysql_fetch_assoc($r);
$badge1 = $row['badge1'];
if($badge1 == "unlocked") {
print "image if user has unlocked the badge";
} else {
print "image if user hasn't unlocked the badge";
}
?>
I would like to have the above if and else statements placed in a div so I could position the images printed from the query anywhere on my site. Is this possible?
A couple of ways. Here is one example:
<?php
$db = new PDO('mysql:host=host;dbname=dbname;charset=UTF-8', 'username', 'password');
$q = "SELECT badge1 FROM user_badges WHERE username='{$_SESSION['username']}' LIMIT 1";
$r = mysql_query($q);
$row = mysql_fetch_assoc($r);
$badge1 = $row['badge1'];
?>
//Break out of PHP and add any HTML elements you want
<div id="whatever">
<?php
if($badge1 == "unlocked") {
print "image if user has unlocked the badge";
} else {
print "image if user hasn't unlocked the badge";
}
?>
</div>
p.s. Check your PDO. It's mixed with old MySQL_ stuff

Categories