This question already exists:
How to send MySQL multiple rows with PHP for delete purpose? [duplicate]
Closed 3 years ago.
How can I delete multiple rows with checkbox and PDO prepared statements?
With given code, I can delete only last one row from checkded rows, but not all them. I think I have mistake in Main.php, concretly in prepared statements.
How can I solve this problem?
Main.php
// DELETE DATA with PDO
public function delete($id){
$sql = "DELETE FROM $this->table WHERE id IN (:id)";
$stmt = DB::prepare($sql);
$stmt->bindParam(':id', $id);
return $stmt->execute();
}
index.php
// DELETE DATA
if(isset($_POST['delete'])) {
$id = $_POST['id'];
if ($user->delete($id)){
echo "Data Deleted Successfully.. </br>";
}
}
form in index.php
<form method="POST">
<div class="row">
<?php if ($user->readAll() > 0) : ?>
<?php foreach ($user->readAll() as $value) : ?>
<div class="col-md-3 ajax-del"> <!--Delete div with AJAX-->
<div class="card border-secondary mb-4">
<img src="<?= $value['image'] ?>" alt="<?= $value['name']?>" class="card-img-top img-fluid">
<div class="card-body bg-light text-center">
<input type="checkbox" class="float-left" value="<?php echo $value['id']?>" name="id"></<input>
<p class="card-text mt-3"><?=$value['barcode'] ?></p>
<h5 class="card-title text-danger font-weight-bold"><?= $value['name']?></h5>
<p class="card-text">$<?= number_format($value['price'], 2)?></p>
<p class="card-text"><?=$value['weight']?></p>
<p class="card-text"><?=$value['size']?></p>
<p class="card-text mb-4"><?=$value['height']?> <?=$value['width'] ?><?=$value['length']?></p>
</div>
</div>
</div>
<?php endforeach ?>
<?php endif ?>
</div>
<input type="submit" class="btn btn-danger float-right mr-3" id="delete" name="delete" onclick="return confirm('Are you sure?')"></input>
</form>
If you have multiple form controls with the same name, PHP will only get the last one, because the name attribute becomes an array key in $_POST, and array keys are distinct by definition. So name="id" in your checkbox means that PHP will only get the last one. You can define the name so that it will be accessible an array in $_POST using square brackets. Change it to name="id[]".
Then you'll either need to modify your function so that it takes an array or call it multiple times with each id in the array.
If it was my project I would prefer to modify the the function to take an array.
public function delete(array $ids) {
$placeholders = trim(str_repeat('?,', count($ids)), ',');
$sql = "DELETE FROM $this->table WHERE id IN ($placeholders)";
$stmt = DB::prepare($sql);
return $stmt->execute($ids);
}
If you don't change the function, you'll just need to call it multiple times.
if (isset($_POST['delete'])) {
foreach ($_POST['id'] as $id) {
if ($user->delete($id)) {
echo "Data Deleted Successfully for $id.. </br>";
}
}
}
Related
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?
I am trying to make a webpage that will add a card filled with data from a database if there is a row of data there. I have a <div class> that formats the card. Is there a way to programmatically add the <div class> so each <div class> is a row of data?
This is the PHP I have, it does read all the rows properly:
//SQL SELECT statement
$result = $conn->prepare("SELECT userid, pName, pDesc, dDate FROM test");
$result->execute();
// assign returned array elements to variables
for($i=0; $row=$result->fetch(); $i++){
$pName = $row['pName'];
$pDesc = $row['pDesc'];
$dDate = $row['dDate'];
}
Here is the HTML, it currently only displays the last row of data:
<h1>Project Dashboard</h1>
<div class="project-container">
<label>Project Owner:</label>
<span><?php echo $pName; ?></span><br>
<label>Project Description:</label>
<span><?php echo $pDesc; ?> </span><br>
<label>Project Due Date:</label>
<span><?php echo $dDate; ?> </span><br>
<div class="progress-bar">
<div id="myBar" class="container purple" style="height:24px;width:25%">
</div>
</div>
</div>
As mentioned in the comments, the PHP values are overwritten upon each iteration of the for loop, so only the last row of values will be displayed. For example, $pName can only hold one value at a time. So after the loop, $pName is defined as the last row's pName value.
I suggest using a while loop to output your HTML rows. Below, I'm assuming each .project-container is a row. I'm also using PDO.
<?php
while ($row=$result->fetch(PDO::FETCH_ASSOC)) {
?><div class="project-container">
<label>Project Owner:</label>
<span><?=$row['pName']?></span><br>
<label>Project Description:</label>
<span><?=$row['pDesc']?></span><br>
<label>Project Due Date:</label>
<span><?=$row['dDate']?></span>
</div><?php
}
Alternatively, you could fetch all the rows into a single PHP array and then loop through the array.
$rows=$result->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
// output row's HTML, just like above
}
See PDO::fetchAll vs. PDO::fetch in a loop
for performance considerations.
i created a group and what i wanted to do is when i join the group the join button should hide. but i dont know how to do it.. tbl_group is the list of created group and when you join the group the id will be saved on a diff table.. this code is for showing all list of groups.
group.php
<?php
$db = new Group($conn);
$res = $db->g_viewlist();
foreach ($res as $key => $value){
?>
<div class="col-lg-12" align="center" style="border:1.5px solid #59960b;padding-bottom:10px;padding-top:10px;">
<button class="btn2 btn-2 join" data-id="<?php echo $value['g_id']; ?>" data-toggle="modal" data-target="#joinModal" style="padding: 2px 2px;margin-left:50%"><strong> Join</strong></button>
<img src="./<?php echo $value['g_image']; ?>"class="pull-left" class="img-square" height="70" width="70" alt="Avatar">
<p align="left">
<strong class="font-1" style="color:#59960b;"><?php echo $value['g_name'];?> </strong><br>
<small style="font-family:courier,'new courier';" class="text">Member Since 2008<br></small>
<small style="font-family:courier,'new courier';" class="text-muted">Description:<?php echo $value['g_desc']; ?></small><br>
</p>
</div>
<?php
}
?>
SQL Query for showing all list of groups.
public function g_viewlist(){
$sql = "SELECT * FROM tbl_group ";
$result = $this->dbh->prepare($sql);
$result->execute();
$data = array();
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$data[] = $row;
}
return $data;
}
this table is where i store the user id and the group id this is a diff table..assuming the g_id = 25 from tbl_group and group_id =25 from tbljoingroup
You need to retrieve the array of groups user is a member of and inside your foreach loop just search through this list. If user is a member of $value['g_id'] just skip loop iteration with continue.
If you want to hide only the button and still display the rest of the code then do something like this:
<?php
$db = new Group($conn);
$res = $db->g_viewlist();
foreach ($res as $key => $value) {
?>
<div class="col-lg-12" align="center" style="border:1.5px solid #59960b;padding-bottom:10px;padding-top:10px;">
<?php if (!$user.memberOf($value['g_id'])) { ?>
<button class="btn2 btn-2 join" data-id="<?php echo $value['g_id']; ?>" data-toggle="modal" data-target="#joinModal" style="padding: 2px 2px;margin-left:50%"><strong> Join</strong></button>
<?php } ?>
<img src="./<?php echo $value['g_image']; ?>"class="pull-left" class="img-square" height="70" width="70" alt="Avatar">
<p align="left">
<strong class="font-1" style="color:#59960b;"><?php echo $value['g_name'];?> </strong><br>
<small style="font-family:courier,'new courier';" class="text">Member Since 2008<br></small>
<small style="font-family:courier,'new courier';" class="text-muted">Description:<?php echo $value['g_desc']; ?></small><br>
</p>
</div>
<?php
}
?>
If you have user object saved in $user then create memberOf() method which will return true if user is a member of the group or false otherwise.
Note: Do not search database on each memberOf() execution. Do it once and save results in object's property for reuse.
please someone help me to find the solution for how to retrieve data from mysql database and populate in list view in jquery mobile.
am having the php code as follows
<? php
include('libraries/config.php');
$result = mysql_query("SELECT * from category") or die(mysql_error());
while ($obj = mysql_fetch_object($result)) {
$arr[] = $obj;
}
echo json_encode($data);
echo '{"Deals":'.json_encode($arr).'}';
?>
here am getting the data from mysql in json format but i was not known how to populate this in listview, my html page is as follows
<div id="content-area" style="height:auto;">
<br/>
<ul data-role="listview">
<li>
<a href="comfort_list.html">
<div class="content-home-tab1">
<div class="img-content">
<img id="ic_home" src="images/next_btn.png" style="margin-top:37px; margin-left:448px;" width="22" height="28" />
</div>
<div class="content-home-p">
<b>Comfort</b>
</div>
</div>
</a>
</li>
<li>
<a href="#">
<div class="content-home-tab1">
<div class="img-content">
<img id="ic_home" src="images/next_btn.png" style="margin-top:37px; margin-left:448px;" width="22" height="28" />
</div>
<div class="content-home-p">
<b>Handling Your Lenses</b>
</div>
</div>
</a>
</li>
</ul>
</div>
Here in my code am giving static data to list that is comfort and handling your lens, am having this data in db and i need to get that and to be placed here.
in the page i am posting in a form like this
<form method="post" action="help.html">
<ul data-role="listview" >
<?php while ($row = $stmt->fetch()){
?>
<li>
<a href="help1.php?id=<?php echo $row['categoryID']; ?>">
<div class="content-home-tab1">
<div class="img-content">
<img id="ic_home" src="images/next_btn.png" style="margin-top:37px; margin-left:448px;" width="22" height="28" />
</div>
<div class="content-home-p">
<b><?php echo $row['title'];?>
</b>
</div></div></a>
</li>
<?php }?>
</ul>
</form>
and in another page am trying to get the id as follows
<?php
include('libraries/config.php');
$getID = $_GET['id'];
echo $getID;
$stmt = $db->prepare("SELECT * from category where categoryID ='$_GET['id']'");
$stmt->execute();
?>
but when going to that page it is showing nothing and when refreshed then it is showing so that only am asking how to get it to fetch data and print it when the page is loaded. thanks.
As C.S. says, you don't need to use JSON, just loop through your array and add your list items.
Edited to show basic use of PDO, and demo how to access query results.
The mysql_query extension is deprecated as of PHP 5.5.0, so you I would suggest you use PDO_MySQL
First set up your database connection:
$dbName = "your_database_name_here";
$dbUserName = "your_username_here";
$dbPassword = "your_password_here";
$db = new PDO( 'mysql:host=localhost;dbname='.$dbName, $dbUserName, $dbPassword );
Then run your query, and echo your list (or whatever you need from the database by accessing the $row array within the while loop):
$stmt = $db->prepare("SELECT * from category");
$stmt->execute();
while ($row = $stmt->fetch()){
echo "<li>". $row['title'] ."</li>";
}
p.s. you should get rid of that inline css, it's a bad habit to get into.
So I am trying to pull HEADLINES.. that I have saved in a DB, they all have unique IDs.. I need a way to be able to call them but type or ID for instance.
$stmt = $con->prepare("SELECT * FROM news WHERE type = 'sports'");
$stmt->execute();
while($rfr=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<div class="row">
<div class="col-lg-4">
<img src="<?php echo $rfr['folder'] . $rfr1['file'];?>.jpg" >
<h2><?php echo $rfr['headline'];?></h2>
<p>V.A. conducts study to determine effectiveness</p>
<p><a class="btn btn-primary" href="#" role="button">Read More »</a></p>
</div>
<div class="col-lg-4">
<img src="imgs/news/n4.jpg">
<h2><?php echo $rfr['headline'];?></h2>
<p>The Rev. Daniel Berrigan, a Roman Catholic priest and peace activist who was imprisoned for burning draft files in a protest against the Vietnam War, died Saturday. He was 94.</p>
<p><a class="btn btn-primary" href="#" role="button">Read More »</a></p>
</div>
<div class="col-lg-4">
<img src="imgs/news/n1.jpg">
<h2><?php echo $rfr['headline'];?></h2>
<p>President Barack Obama is getting one more chance to poke fun at fellow politicians, the press and himself at the annual White House Correspondents' Dinner.</p>
<p><a class="btn btn-primary" href="#" role="button">Read More »</a></p>
</div>
<?php
}
?>
Every time I run this code though.. It just enters only the headline from ID 1 everytime. and it makes a ton of duplicate post..
I want it to select through all the headlines in that type.. thats why im using the WHILE()
Please try this:
$stmt = $con->prepare("SELECT * FROM news WHERE type = 'sports'");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $rfr) {
?>
<div class="row">
<div class="col-lg-4">
<img src="<?php echo $rfr['folder'] . $rfr1['file'];?>.jpg" >
<h2><?php echo $rfr['headline'];?></h2>
<p>V.A. conducts study to determine effectiveness</p>
<p><a class="btn btn-primary" href="#" role="button">Read More »</a></p>
</div>
...
</div>
<?php } ?>
Why don't you just use a foreach? That way you don't have to worry about handling iterations and possible infinite loops that while loops have.
Also, I personally prefer not to make function calls and assignments in a while/foreach.. It's not that big of a deal to add 1 extra line just before the declaration. Will improve readability and make it easier to debug your code.