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.
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?
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 have an employee database which includes images as well as their work location (specialty). I have created a page where I fill out a form and upload the image to a directory and the path to the database. I then load the main page where I pull in all the images from the database (into the "photos" DIV. Everything works fine.
What I would like to do is reload the images in the DIV based on a MySQL query from a button. For example, instead of showing all employees, I only want to see those who have a specific job function i.e. Management. I currently have this accomplished by redirecting to a new page, where I run a specific query and that works fine as well. However, I'd like to learn how this is done without creating a new page for each query. I've spent many days looking at AJAX and PHP tutorials, which I how I was able to accomplish what I have, but I can't find a method to do what I want. This is the relevant part of my code:
Main.php
<div class="container-fluid">
<div class="row">
<div class ="col-lg-12" style="width: 18%; height: 100%; border:3px solid red;">
MANAGEMENT
HIGH
</div>
<?php
include ('db_connect.php');
//include_once ('functions.php');
$result = $db->query("SELECT * from monctonfir order by initials ASC");
if($result->num_rows > 0){
while ($row = $result->fetch_assoc()){
$imageURL = 'image/'.$row["file"];
$initial = $row["initials"];
$name = $row["name"];
?>
<div id="photos" class = "col-lg-1 no-gutters" style="margin-top:1rem;">
<div class="card text-center" style="width: 5rem;">
<a href = "#">
<img class="img card-img-top" src = "<?php echo $imageURL ?>">
</a>
<div class = "card-body">
<h5 class = "card-title round-button" style="text-align: center;"><?php echo $initial ?></h5>
</div>
</div>
</div>
<?php }
} ?>
</div>
Can someone point me in the right direction?
Thanks!
You don't need jQuery for what you are doing. You can use query/GET parameters to build your sql so you don't have to create a different page. Like:
<div class="container-fluid">
<div class="row">
<div class ="col-lg-12" style="width: 18%; height: 100%; border:3px solid red;">
MANAGEMENT
HIGH
ALL
</div>
<?php
include ('db_connect.php');
//include_once ('functions.php');
$sql = "SELECT * from monctonfir WHERE 1 ";
if(isset($_GET['job'])) $sql .= " AND job = '".$_GET['job']."' ";
$sql .= " order by initials ASC";
$result = $db->query($sql);
if($result->num_rows > 0){
while ($row = $result->fetch_assoc()){
$imageURL = 'image/'.$row["file"];
$initial = $row["initials"];
$name = $row["name"];
?>
<div id="photos" class = "col-lg-1 no-gutters" style="margin-top:1rem;">
<div class="card text-center" style="width: 5rem;">
<a href = "#">
<img class="img card-img-top" src = "<?php echo $imageURL ?>">
</a>
<div class = "card-body">
<h5 class = "card-title round-button" style="text-align: center;"><?php echo $initial ?></h5>
</div>
</div>
</div>
<?php }
} ?>
</div>
The simplest way is to use the load function of Jquery
Jquery
For example:
$( "#divID" ).load( "loadEmploye.php", { parameters1: 25, parameters2:3 });
I need some ideas on how to edit my structure inside my database I am building a fast food order website for 1 take away client at the moment the user adds there items into the order table
Here is it the table: http://prntscr.com/g3o3kz
The user_id column is for the user who is ordering id to be stored then item id is what item they want takeawayid is the id of the take away and the status is were they order food its auto set to waiting then the take away can update it to accepted or declined.
Now the problem I'm having is the user adds 5 items into the table above for take away id 1 there will be 5 rows for the user id and take away id and item id (there are 5 items)
Now I'm onto the recent orders page and I print out all for each take away so like so
http://prntscr.com/g3o4uw
But then tomorrow if they order it will add another 5 items and it will show in the same box how would I group each order? So order 1 has xyz items then next time the order order2 has xyz and so on. because at the moment the way the database is laying out it will just all be order1 if this makes sense
Displaying the orders box
<div class="container" style="margin-top: 40px;">
<div class="row">
<div class="col-xs-12">
<?php
echo $_SESSION['username'] ;
foreach ($ordersByUsers as $userId => $item) {
$username = $item['username'];
$ordersPrice = $item['ordersPrice'];
$orders = $item['orders'];
?>
<div class="row">
<div class="col-xs-12 col-md-10" style="background-color: #FAFAF8; border: 1px solid #ddd; padding: 20px; margin-bottom: 20px;">
<div class="row" style="padding: 20px;">
<div class="col-xs-12 col-sm-3">
<div class="row">
<a href="#">
<img src="http://santetotal.com/wp-content/uploads/2014/05/default-user.png" class="img-responsive" alt="Restaurant logo" height="92" width="102">
</a>
</div>
<div class="row" style="padding-top: 10px;">
<a href="#" style="text-transform: uppercase;">
<?php echo $username; echo "<br> </br>";
?>
<?php
/////////// get status of order
$statement8 = $db->prepare("SELECT * FROM users WHERE username = ? ");
$statement8->execute(array($_SESSION['username']));
$count8 = $statement8->fetch();
$username233 = mysql_real_escape_string($count8['id']);
$username2312312 = strip_tags($username233);
$statement85 = $db->prepare("SELECT * FROM orders WHERE user_id = ? AND takeawayid = ? ");
$statement85->execute(array($username2312312,$_SESSION['userid']));
$count84 = $statement85->fetch();
if($count84 ['status']== "waiting") {
?>
<form action="dashboard.php" method="post">
<input type="hidden" name="accept" value="<?php echo $count84['id']?>">
<input type="image" name="submit" src="http://business.fsdfsdfsdf.com/beta/accept.png" border="0" alt="Submit" />
</p>
</form>
<form action="dashboard.php" method="post">
<input type="hidden" name="deny" value="<?php echo $count84['id']?>">
<input type="image" name="submit" src="http://business.sdfsdfdf.com/beta/deny.png" border="0" alt="Submit" />
</p>
</form>
<?php
}elseif ($count84 ['status']== "Accepted") {
echo "<img src='http://business.sfdfsdfsdf.com/beta/accepted.png' alt='error'>";
} else {
echo "<img src='http://business.sdfdsfsdfsdf.com/beta/declined.png' alt='error'>" ;
}
?>
</a>
</div>
</div>
<div class="col-xs-12 col-sm-9">
<?php
foreach ($orders as $order) {
$orderId = $order['orderId'];
$itemname = $order['itemname'];
$price = $order['price'];
$date = $order['date'];
$address = $order['address'];
?>
<div class="row">
<div class="col-xs-12" style="background-color: #FFF; border: 1px solid #ddd; padding: 20px; margin-bottom: 20px;">
<h4>
<a href="profile.html" style="color: orange;">
<?php echo $itemname; ?>
</a>
</h4>
<div>
<div>
<span>
<?php echo $date; ?>
</span>
</div>
<div class="ratings">
<span>5 STARS</span>
</div>
</div>
</div>
Address: <b> <?php echo $address; ?></b>
</div>
<?php
}
?>
</div>
</div>
</div>
<div class="col-xs-12 col-md-2" style="padding: 20px; padding-top: 40px; font-size: 20px; color: #666; text-transform: uppercase;">
Total: <?php echo $ordersPrice; ?>
</div>
</div>
<?php
}
?>
query
function fetchPaidOrdersByTakeaway($connection, $takeawayId, $paid) {
if (!isset($takeawayId)) {
throw new Exception('Takeaway ID not provided!');
}
if (!isset($paid)) {
throw new Exception('Paid not provided!');
}
// Sql statement.
$sql = 'SELECT
ord.id AS orderId,
usr.id AS userId,
usr.username,
ord.itemname,
ord.address,
ord.price,
ord.date
FROM orders AS ord
LEFT JOIN users AS usr ON usr.id = ord.user_id
WHERE
user_id = :takeawayid
AND paid = :paid
ORDER BY
usr.username ASC,
ord.date DESC';
// Prepare and check sql statement (returns PDO statement).
$statement = $connection->prepare($sql);
if (!$statement) {
throw new Exception('The SQL statement can not be prepared!');
}
// Bind values to sql statement parameters.
$statement->bindValue(':takeawayid', $_SESSION['userid'], getInputParameterDataType($_SESSION['userid']));
$statement->bindValue(':paid', $paid, getInputParameterDataType($paid));
// Execute and check PDO statement.
if (!$statement->execute()) {
throw new Exception('The PDO statement can not be executed!');
}
// Fetch data.
$fetchedData = $statement->fetchAll(PDO::FETCH_ASSOC);
if ($fetchedData === FALSE) {
throw new Exception('Fetching data failed!');
}
return $fetchedData;
}
/**
* Group orders by users.
*
* #param array $orders [optional] Orders list.
* #return array Orders list grouped by users.
* #throws Exception
*/
function groupOrdersByUsers(array $orders = array()) {
$groupedOrders = array();
foreach ($orders as $order) {
$userId = $order['userId'];
$username = $order['username'];
$price = $order['price'];
// Check and add user name as key, if not already.
if (!array_key_exists($userId, $groupedOrders)) {
$groupedOrders[$userId] = array(
'username' => $username,
'orders' => array(),
'ordersPrice' => 0,
);
}
// Add order to grouped orders list.
$groupedOrders[$userId]['orders'][] = $order;
$groupedOrders[$userId]['ordersPrice'] += $price;
}
return $groupedOrders;
}
would i need a extra column maybe orderid then have all the order the same id then display each by order id ?Problem is adding the same number to each item inside the order then next order adding a new number and not having 2 the same numbers
Edit
at the moment i show there cart like so
$statement = $db->prepare("SELECT * FROM orders WHERE user_id = ? AND status = ? AND takeawayid = ? ");
// $statement->execute(array($username2,$md5password,$mod));
$statement->bindParam(1, $_SESSION['userid'], PDO::PARAM_STR, 50); // check your lengths
$statement->bindParam(2, $testing, PDO::PARAM_STR, 60);
$statement->bindParam(3, $id1, PDO::PARAM_INT);
$statement->execute();
this of course works perfect because old orders will ether be accepted or declined so the waiting status ones will be the current ones. Im just finding it hard to print out old orders and group them together
Learn how to achieve third normal form for your database.
That magic phrase simply means that if you have something may be isolated as one entity - create a separate table for it.
In your case there should be 1 table for orders and 1 table for items, tables will be joined with foreign keys, which in Mysql are made as said in that article: MySQL foreign key examples (How to define foreign keys in MySQL)
To untie your imagination with proper tool I would recommend you to use MySQL Workbench which will help you to visualize database structure while you will design it. It may be a "From a cannon by a sparrow" approach in your particular case but will definitely help to rapidly advance your skills in future.
And finally answering your question in detail
Create items table with id, name and price fields. It will contain list of items you are offering to your users
id will be Primary key with auto increment property
Create users table with id and name fields
id will be Primary key with auto increment property
Create orders table with id and user_id fields
id will be Primary key with auto increment property
user_id will have Foreign key linked with users table
Create order_items table with id, order_id, price and quantity fields
id will be Primary key with auto increment property
order_id will have Foreign key linked with orders table
item_id will have Foreign key linked with items table
I can't understand what address and date fields are for, so attach then to appropriate table listed above.
As a result you will have list of orders for every user, with a list of items ordered inside connected with price-list. You will be able to SELECT all the joined data from all tables at once OR a part of data to show it to user or to you.
The great thing here is that there is no problem with IDs anymore.
I've got a new online store written in PHP and MySQL.
<div class="content-area">
<div class="page-heading">
<h1>Store</h1>
</div>
<p style="padding-top: 5px;"><strong>You are here:</strong> Home » Store</p>
<table border="0" cellpadding="0" cellspacing="0" width="500">
<?php
$categories=mysql_query("SELECT * FROM categories WHERE parent='0' ORDER by owner ASC, title ASC");
while($categoriesRow=mysql_fetch_array($categories)) {
$categoriesSub=mysql_query("SELECT * FROM categories WHERE parent='$categoriesRow[id]'");
?>
<tr>
<td valign="top">
<div class="product_list">
<div class="image_product">
<img alt="<?php echo $categoriesRow['title']; ?>" src="<?php echo $cls->truska(true); ?>/theme_section_image.gif" border="0" style="vertical-align: middle;" />
</div>
<div>
<h3 class="product"><?php echo $categoriesRow['title']; ?> <?php if(mysql_num_rows($categoriesSub) > 0) { ?>(<?php while($categoriesSubRow=mysql_fetch_array($categoriesSub)) { }?>)<?php } ?></h3>
</div>
</div>
</td>
</tr>
<tr>
<td class="dotted_line_blue" colspan="1">
<img src="<?php echo $cls->truska(true); ?>/theme_shim.gif" height="1" width="1" alt=" " />
</td>
</tr>
<?php
}
?>
</table>
</div>
Where my second While loop is, I need to work out what is the last result, so I can omit a comma from my while loop.
It will show as 'Lego (Lego City, Lego Starwars,)' but I want it to show as 'Lego (Lego City, Lego Starwars)'.
How can I get if the current result is the last?
You can fix this by coming at it from the other direction.
Instead of appending a comma after each result except the last, try pre-pending a comma on every result except the first.
Set up a variable called $first outside your loop, and set it to 1. Inside the loop:
if ($first == 0) {
echo ",";
} else {
$first = 0;
}
don't add the comma if it is the first result, and add it before in all the next ones.
Just build your array of results and implode it. This takes care of any counting automatically:
$comma_separated = implode(",", $array);
You shouldn't use plain mysql access, look at PDO.
Answering your question, try something like this:
$items = array();
while ($row = mysql_fetch_assoc($result)) {
$items[] = $row['foo'];
}
echo implode(', ', $items);