No effect on PHP/SQL Delete on table - php

Basically my delete button is not functioning as intended. below is the screenshot of my for each table, displaying the contents of my table "product". I echoed the "productid" to show that the delete button has an int value.
products.php
<td>
<?php echo $rowProduct['productid']; ?>
<a href="clinics_buttons.vc.php<?php echo '?delete-coupon='.$rowProduct['productid']; ?>" onclick="return confirm('Delete this address?');">
<button class="btn btn-danger btn-sm full_width" data-toggle="modal">
<i class="fa fa-edit"></i><?php echo "DELETE"; ?>
</button>
</a>
</td>
I made the "delete-coupon" into a variable for use in the SQL. But even when '$productid' has a value, the table does not get deleted. Would like help on why this is happening and what could I add to fix it.
clinics_buttons.vc.php
<?php
session_start();
$routePath = "../";
require_once($routePath . "_config/db.php");
$dbConfig = new config_db();
$db = $dbConfig->init();
$delete_coupon = $_GET['delete-coupon'];
if (isset($_GET['delete-coupon'])) {
$stmt = $db->prepare("DELETE FROM `product` WHERE productid = $delete_coupon");
$stmt->execute();
header('Location: ' . $_SERVER['HTTP_REFERER']);
}
?>
Table Products

You probably have "form" tag surrounding that table so "button" will trigger form submission.

Related

php foreach button issue

What I exactly need:
inside the foreach for every element I create a button. Then connect to postgresql db, select data from the table by condition.
If there is a matching entry in the database then I display <span class="fa fa-heart"> </span>. If no entries then display <span class="far fa-heart"></span>. I need this output exactly inside <button> </button> tag.
<form method="POST">
<?php foreach ($rows as $data): ?>
<button class="btn btn-outline-danger mx-1" name=fav-click style="font-size: 11px;">
<?php
$linkk = pg_connect("host=localhost dbname=webportal user=postgres password=1234567");
$favor=(int)$data['obj_id'];
$id_usr=(int)$id;
$query = "select obj_id, usr_id from favorites where usr_id='$id_usr' and obj_id='$favor'";
$re = pg_query($linkk, $query);
$row1=pg_fetch_all($re);
if(pg_num_rows($re)==0)
{
echo '<span class="far fa-heart"></span>';
}
if(pg_num_rows($re)>0)
{
echo '<span class="fa fa-heart"> </span>';
}
?>
</button>
inside the form there also are
<input type=hidden name=obj_id value=<?= $data['obj_id'];?>>
<input type=hidden name=id_usr value=<?= $id; ?>>
in which I store the values ​​I need.
Outside the foreach I have:
<?php
if(isset($_POST['fav-click']) && isset($_POST['obj_id']) && isset($_POST['id_usr'])) {
$oo = $_POST['obj_id'];
$uu=$_POST['id_usr'];
if(pg_num_rows($re)==0)
{
$zapr="insert into favorites(obj_id, usr_id) values($oo, $uu)";
$done = pg_query($linkk, $zapr);
}
if(pg_num_rows($re)>0)
{
$zapr="delete from favorites where obj_id='$oo' and usr_id='$uu'";
$done = pg_query($linkk, $zapr);
}
}
?>
But it works not correctly because it always displays and does queries in the db for the last element of foreach. Doesn't matter if I click a button for another one.
How can I fix it?

"Issue with updating a record using a button”

When I click on the update button, the SQL query updates the last record not the wanted one
when displaying several courses, I would like to give the user the right to confirm one of the courses, when I click on the update button, it updates the last record
<?php
$cc = mysqli_query($mysqli, "SELECT * from course WHERE c_email ='$emailu' AND course_situation='pending'");
while($ccc = mysqli_fetch_array($cc)) {
$idcourse = $ccc['idcourse'];
$city = $ccc['idville'];
$pickup = $ccc['course_depart'];
?>
<tr>
<td><?= $idcourse ?></td>
<td><?= $pickup ?></td>
<td><?php echo $ccc['course_date'] ?>, <?php echo
$ccc['course_heure'] ?></td>
<td>
<?php
if($ccc['course_situation'] == "pending") { ?>
<span class="badge badge-danger">Pending</span>
<?php } else { ?>
<span class="badge badge-success">Confirmed</span>
<?php } ?>
</td>
<td><?php echo $ccc['c_phone'] ?></td>
<td><?php echo $ccc['c_phone'] ?></td>
<td><?php echo $ccc['idclient'] ?></td>
<td>
<button type="submit" name="cancelcourse" class="btn btn-danger btn-xs"><i class="icon md-check" aria-hidden="true"></i> Update</button>
</tr>
<?php }
if(isset($_POST["cancelcourse"])) {
$query = "UPDATE course SET id='$idu' AND course_situation='confirmed' WHERE idcourse='$idcourse' ";
if(mysqli_query($mysqli, $query)) {
echo "<div class=' alert alert-success' style='padding-left:150px'>
<strong>Success!</strong> Event page updated.</a>.
</div>";
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=index.php">';
} else {
echo "<div class='alert alert-danger'>
<strong>ERROR!</strong> We invite you to try Again Later.
</div> " . mysqli_error($mysqli);
}
}
You generate button for each course, but all your buttons are equal, they don't contains any information about which course you want to update. You use variable $idcourse, but it is assigned inside while-loop that generates table - for each row that is shown this variable is changed, so after showing whole table it will contains id for last row.
Please remember, that each time your page is reloaded (like after clicking button) whole script is executed from beginning and no variables are stored, unless you pass it yourself.
Simplest solution:
1.Add id to button
<button type="submit" name="cancelcourse" class="btn btn-danger btn-xs" value="<?=htmlspecialchars($idcourse)?>">
2.Change query
$idcourseToRemove = mysqli_real_escape_string($mysqli, $_POST["cancelcourse"]);
$query = "UPDATE course SET id='$idu' AND course_situation='confirmed' WHERE idcourse='$idcourseToRemove' ";
And last advice: learn about SQL Injection and how to avoid it (like for example by mysqli_real_escape_string function)
UPDATE course SET id='$idu',course_situation='confirmed' WHERE
idcourse='$idcourse'

Show row collapsed in Bootstrap

$i = 0;
while($row = $statement->fetch()) {
$current_id = 'id-' . $i;
$i++;
echo "
<tr>
<td>
<p>
<button class='btn btn-primary'
type='button'
data-toggle='collapse'
data-target='#<?=$current_id?>'
aria-expanded='false'
aria-controls='Collapse'>
Button with data-target
</button>
</p>
<div class='collapse' id='<?=$current_id?>'>
<div class='card card-block'>
Here is the content for block which will be shown when the button. This uses button with data-target attribute for collapsing.
</div>
</div>
</td>
";
}
Where is my error? It doesn't collapse but I need the unique ids for my rows.
now it work. What i have to do now:
$ccid = "#$current_id";
$ccid2 = "$current_id";
And then i have put the variables inside of ID and Href Like this:
href='".$ccid."'
id='".$ccid2."'
That fixxed this problem. Thanks to all!

Remove Current Row without ID (PHP, MYSQL, HTML)

I am working on a HTML website. I am using a MySQL Database and PHP.
The concept so far is fairly simple:
The user can add some text onto the site by clicking on an add button - the user gets directed to a page with a dialogue box
When he clicks submit, that text is in the data base.
The PHP code knows: while the data base has entries -> echo the text onto the HTML website (I added a while loop)
Now my next step is to let the user delete the text. I added a trash can glyphicon onto the HTML site. When the user clicks it, I would like for the current row in the table to be removed. Unfortunately nothing happens!
Here's the code:
<?php
$query = " SELECT * FROM Thesis";
$sql = mysqli_query($conn, $query);
$count = mysqli_num_rows($sql);
while ($row = mysqli_fetch_array($sql)){
?>
<div class="box green-box">
<p><div class="center-box-content">
<!--echo the title -->
<?php echo $row["title"]; ?>
<br>
<!--echo the description -->
<?php echo $row["description"]; ?>
</p>
<div class="lower-right-box-content">
<a href="adminview.php">
<span class="glyphicon glyphicon-trash glyphicon-trash" role="button">
<?php
$delquery = " DELETE * FROM Thesis";
mysqli_query($conn, $delquery);
?>
</span>
</a>
</div>
</div>
</div>
<?php };
?>
What am I doing wrong? I know that the main mistake must lie somewhere
in $delquery. But I am lost.
I also know that it would be better to have an ID for each row. But I would like to avoid it, because since we are in a while loop, there must be a way to just delete the current row that the while loop is in, right? That would be my preferred solution.
Lastly, I am very new to programming and not the most elegant programmer yet, please be kind :)
You are going to want a simple ID for your thesis table, something like this:
CREATE TABLE `Thesis` (
`thesis_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`description` varchar(255) NOT NULL,
PRIMARY KEY (`thesis_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I would separate out the PHP from the display code, putting the PHP code at the top of your file. For security and better code, I would use bind variables with PDO (instead of mysqli). But sticking with your original code, I would rewrite it like this:
<?php
// Establish the connection
$sql = mysqli_query($conn, $query);
// Delete a specific element
if (isset($_GET['delete_id']) && $_GET['delete_id'] > 0) {
$query = "DELETE FROM Thesis WHERE thesis_id = " . $_GET['delete_id'];
mysqli_query($conn, $query);
}
// Gather all the rows
$query = "SELECT * FROM Thesis";
$count = mysqli_num_rows($sql);
$rows = [];
while ($row = mysqli_fetch_array($sql)){
$rows[] = $row;
}
?>
<?php foreach ($rows as $row): ?>
<div class="box green-box">
<p><div class="center-box-content">
<!--echo the title -->
<?= $row["title"] ?>
<br>
<!--echo the description -->
<?= $row["description"] ?>
</p>
<div class="lower-right-box-content">
<a href="adminview.php?delete=<?= $row['thesis_id'] ?>">
<span class="glyphicon glyphicon-trash glyphicon-trash" role="button"></span>
</a>
</div>
</div>
</div>
<?php endforeach; ?>
The foreach call above is a common PHP shortcut, and the <?= tag will echo back something without having to call echo. The deletion of element using a GET call is not recommended, but for simplicity I'm keeping it in place.
WARNING: BE CAREFUL OF SQL INJECTIONS!!
Now, back to the problem.
First of all, your delete SQL code is run every time a row is inserted, so you will never have rows. First step is to delete
<?php
$delquery = " DELETE * FROM Thesis";
mysqli_query($conn, $delquery);
?>
Next, you want that certain row to be deleted if the user clicks the trash icon. To do this, you can pass the row ID to a PHP page via <a> or $.ajax, then delete it from that PHP page. However, BE CAREFUL OF SQL INJECTIONS
So you would need on your main page:
[delete icon]
And on your deleteRow.php:
$id=$_GET['id'];
//anti-injection code
mysqli_query($conn,"DELETE FROM Thesis WHERE id='$id'");
<a href="adminview.php">
<span class="glyphicon glyphicon-trash glyphicon-trash" role="button">
<?php
$delquery = " DELETE * FROM Thesis";
mysqli_query($conn, $delquery);
?>
</span>
</a>
In above code you deleting all the rows. which is wrong. what you should do is:
<a href="adminview.php?id=<?php echo $row["id"];?>">
<span class="glyphicon glyphicon-trash glyphicon-trash" role="button"></span>
</a>
in adminview.php
if(isset($_REQUEST['id'])) {
$delquery = " DELETE FROM Thesis WHERE id= '".$_REQUEST['id']."' ";
mysqli_query($conn, $delquery);
}

Change Enum With OOP PHP

I'm new to learning web development with PHP and I have a problem I'm trying to solve. I have an ENUM type in my database which is of 2 values: "Y" or "N". It is called userStatus inside my user table (tbl_users). I'm trying to use PHP to change that ENUM value for that particular user when a button is clicked. However when I click the button nothing happens and I'm unsure if its the button or my PHP or a combination of both being wrong which is causing this not to work?
PHP to change ENUM:
if(isset($_POST['btn-activate'])){
if(isset($_GET['id']))
{
$id = $_GET['id'];
extract($user_home->getID($userId));
$statusY = "Y";
$statusN = "N";
$stmt = $user->runQuery("SELECT userID,userStatus FROM tbl_users WHERE userID=:uID");
$stmt->execute(array(":userID"=>$userId));
$row=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0)
{
if($row['userStatus']==$statusN)
{
$stmt = $user->runQuery("UPDATE tbl_users SET userStatus=:status WHERE userId=:userID");
$stmt->bindparam(":status",$statusY);
$stmt->bindparam(":userID",$userId);
$stmt->execute();
$msg = "
<div class='alert alert-success'>
<button class='close' data-dismiss='alert'>×</button>
<strong>WoW !</strong> Your Account is Now Activated : <a href='manage_users.php'></a>
</div>
";
}
else
{
$msg = "
<div class='alert alert-error'>
<button class='close' data-dismiss='alert'>×</button>
<strong>sorry !</strong> Your Account is allready Activated : <a href='manage_users.php'></a>
</div>
";
}
}
else
{
$msg = "
<div class='alert alert-error'>
<button class='close' data-dismiss='alert'>×</button>
<strong>sorry !</strong> No Account Found : <a href='manage_users.php'></a>
</div>
";
}
}
}
Get user id function:
public function getID($userId)
{
$stmt = $this->db->prepare("SELECT * FROM tbl_users WHERE userId=:id");
$stmt->execute(array(":id"=>$userId));
$editRow=$stmt->fetch(PDO::FETCH_ASSOC);
return $editRow;
}
Table Which displays users:
$database = new Database();
$db = $database->dbConnection();
$conn = $db;
$query = "SELECT * FROM tbl_users";
$stmt = $conn->prepare($query);
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
?>
<tr>
<td><?php echo $row['userID']?></td>
<td><?php echo $row['userName']?></td>
<td><?php echo $row['userFirstName']." ".$row['userSurname']; ?></td>
<td><?php echo $row['userEmail']?></td>
<td><?php echo $row['userRole']?></td>
<td><?php echo $row['userStatus']?></td>
<td>
And My button at the end of the table which should, when clicked, run the PHP at the to:
<?php if($row['userStatus'] == ('N')){
echo ' <button type="submit" class="btn btn-info"><i class="glyphicon glyphicon-ok" name="btn-activate" ></i> Activate</button>';
}else{
echo ' <button class="btn btn-default"><i class="glyphicon glyphicon-eye-close"></i> Archive</button>';
} ?>
<button data-toggle="modal" data-target="#view-modal" data-id="<?php echo $row['userID']; ?>" id="getUser" class="btn btn-warning"><i class="glyphicon glyphicon-pencil"></i> Edit</button>
</td>
</tr>
Thanks in advance.
There is no code (nothing happens) if either of the first two if conditions don't evaluate to TRUE.
Consider adding some debugging output. At least add an else for each of those ifs and echo some debug output.
Very strange that the code is checking both $_POST and $_GET. I suspect that id is being passed in on the form submit, just like btn-activate, and not as a parameter in the uri. (i.e. Did you mean $_POST['id'] ? Just guessing here.
We see a reference to $userid in this line:
extract($user_home->getID($userId));
But we don't see what value is assigned to $userId. The preceding line attempts to set a variable named $id. But we don't see $id being used anywhere else.
Personally, I'd avoid using the extract function where it isn't specifically needed. (I don't want my code susceptible to malfunctioning, in this example, when someone adds a column to tbl_users.)
http://ericlippert.com/2014/03/05/how-to-debug-small-programs/
Put the name attribute to your button, not in the <i> element.
<?php
if($row['userStatus'] == ('N')){
echo ' <button type="submit" class="btn btn-info" name="btn-activate"><i class="glyphicon glyphicon-ok"></i> Activate</button>';
} else {
echo ' <button class="btn btn-default"><i class="glyphicon glyphicon-eye-close"></i> Archive</button>';
}
?>

Categories