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?
Related
I have being trying to output data from database using the below code but finding difficult displaying the fetched data on screen. Using PDO in php to trigger the selection. What should I do to resolve this issue?
<?php
include ("core.php");
$output = array('data' => array());
$sql = "SELECT categories_id, categories_name, categories_active, categories_status FROM categories WHERE categories_status = ?";
$result = $connect->prepare($sql);
$result->execute([1]);
if($result->rowCount() > 0) {
// $row = $result->fetch_array();
$activeCategories = "";
while($row = $result->fetchAll()) {
$categoriesId = $row[0];
// active
if($row[2] == 1) {
// activate member
$activeCategories = "<label class='label label-success'>Available</label>";
} else {
// deactivate member
$activeCategories = "<label class='label label-danger'>Not Available</label>";
}
$button = '<!-- Single button -->
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Action <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a type="button" data-toggle="modal" id="editCategoriesModalBtn" data-target="#editCategoriesModal" onclick="editCategories('.$categoriesId.')"> <i class="glyphicon glyphicon-edit"></i> Edit</a></li>
<li><a type="button" data-toggle="modal" data-target="#removeCategoriesModal" id="removeCategoriesModalBtn" onclick="removeCategories('.$categoriesId.')"> <i class="glyphicon glyphicon-remove-sign"></i> Remove</a></li>
<li><a type="button" data-toggle="modal" data-target="#deleteCategoriesModal" id="deleteCategoriesModalBtn" onclick="deleteCategories('.$categoriesId.')"> <i class="glyphicon glyphicon-trash"></i> Delete</a></li>
</ul>
</div>';
$output['data'][] = array(
$row[1],
$activeCategories,
$button
);
} // /while
}// if num_rows
$connect = null;
echo json_encode($output);
?>
Please I below is the html code which accept the output. Please I'm just a beginner. Kindly help me.
<thead>
<tr>
<th>Categories Name</th>
<th>Status</th>
<th style="width:15%;">Options</th>
</tr>
</thead>
</table>```
The fetchAll() function will get you all the rows and columns, not just one. With that said, just get the variable $row outside of the while loop, call it differently (let's say, $rows), and then iterate over the loop using something like foreach ($rows as $row). Also, now your $row will not take numerical indices, but rather indices with the names of what you selected in the SQL query, like $row['categories_id'].
This should sort out iterating over the rows that you got. One more thing I'm not sure about is $result->execute([1]);, as that function takes parameters, and you're only giving it a 1-element array with the number 1, although I really can't tell because I don't have the rest of the code. My guess is that you're trying to use JavaScript with AJAX, as you're printing the encoded $output variable, so you'll need to get the input at the very beginning using php://input, where you'll get all the parameters that are sent by AJAX, and, before encoding, set the content type to application/json using the function header("Content-type: application/json");
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.
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>";
}
}
}
$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!
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.