How to display data from multiple table with php - php

Here is my Song.php code which i created a class so i can use it in the index.php file
<?php
require_once("dbInfo.php");
Class Song{
public $length;
public $picture;
public $urlSong;
public $songId;
public $lastname;
public static function getAllRecords($pageNo, $pageSize, &$totalRecords) {
// Connect to database.
$options = array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$dsn = "mysql:host=" . DatabaseInfo::getServer() . ";dbname=" . DatabaseInfo::getDatabaseName() . ";charset=utf8";
$conn = new PDO($dsn, DatabaseInfo::getUserName(), DatabaseInfo::getPassword(), $options);
$pageNo = (int)$pageNo;
$pageSize = (int)$pageSize;
$sql = "SELECT COUNT(*) AS Count
FROM `
(SELECT song.SongId,song.Picture,song.Length,song.UrlSong,artist.Lastname FROM song LEFT JOIN
songandartist on song.SongId= songandartist.SongId INNER JOIN artist on songandartist.ArtistId=artist.ArtistId)AS T1`";
// Prepare statement.
$stmt = $conn->prepare($sql);
// Execute the statement.
$stmt->execute();
// Get total records count.
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$totalRecords = $row['Count'];
$stmt = NULL;
$totalPages = ceil($totalRecords / $pageSize);
if ($pageNo > $totalPages) {
$pageNo = $totalPages;
}
$start = $pageSize * $pageNo - $pageSize;
if($start < 0) {
$start = 0;
}
$sql = "SELECT `Length`,`Picture`,`SongId`,`Lastname`,`UrlSong` FROM
`(SELECT song.SongId,song.Picture,song.Length,song.UrlSong,artist.Lastname FROM song left join songandartist on song.SongId= songandartist.SongId INNER JOIN artist on songandartist.ArtistId=artist.ArtistId)AS T1`
LIMIT $start, $pageSize;";
// Prepare statement.
$stmt = $conn->prepare($sql);
// Execute the statement.
$stmt->execute();
// Fetch all records.
$list = Array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$song = new GetAllSong();
$song->length = $row["Length"];
$song->picture = $row["Picture"];
$song->songId = $row["SongId"];
$song->lastname = $row["Lastname"];
$song->urlSong = $row["UrlSong"];
array_push($list, $song);
}
// Close the database connection.
$conn = NULL;
return $list;
}
}
?>
And here is my index.php code, i called the class and used the function but it did not work
<?php
include '../Song.php';
?>
<div class="container">
<div class="row py-5">
<div class="col-lg-12 mx-auto">
<div class="p-5 rounded shadow "
style="border-radius: 1rem;background-color: rgba(255, 255, 255, 0.58);">
<h2 class="mb-5">Table Song</h2>
<div class="p-1 bg-light rounded rounded-3 shadow-sm mb-4">
<div class="input-group">
<input type="search" placeholder="Search..." aria-describedby="button-addon1" class="form-control border-0 bg-light">
<div class="input-group-append">
<button id="button-addon1" type="submit" class="btn btn-link text-primary"><strong><i class="bi bi-search"></i></strong></button>
</div>
</div>
</div>
<form class="col-lg-8"name="get_Song" action="<?php echo $_SERVER['PHP_SELF'] ?>?page=listsong" method="POST" enctype="multipart/form-data">
<div class="form-row mb-4 align-items-center">
<!-- <label class="fs-5 fw-bold text-secondary mr-0" for="inlineFormInput">Page No</label>-->
<div class="col-sm-4">
<input type="number" class="form-control form-control-lg mb-2 border-0" name="PageNo" id="PageNoid" placeholder="Page No">
</div>
<!-- <label class="fs-5 fw-bold text-secondary mr-0" for="inlineFormInputGroup">Page Size</label> -->
<div class="col-sm-4">
<input type="number" class="form-control form-control-lg mb-2 border-0" name="PageSize" id="Pagesizeid" placeholder="Page Size">
</div>
<div class="col-sm-3 text-center">
<input type="submit" class="btn btn-info mb-2 form-control-lg fs-5 fw-bold" id="ResetId" name="reset" value="Reset" />
</div>
</div>
</form>
<div class="table-responsive custom-table-responsive">
<table class="table custom-table">
<thead>
<tr>
<th scope="col">
<label class="control control--checkbox">
<input type="checkbox" class="js-check-all" />
<div class="control__indicator"></div>
</label>
</th class="">
<th scope="col">SongId</th>
<th scope="col">Lastname</th>
<th scope="col">Length</th>
<th scope="col">Picture</th>
<th scope="col">UrlSong</th>
</tr>
</thead>
<tbody>
<?php
$pageNo = 1;
$pageS = 4;
if (!empty($_POST['reset'])) {
$pageNo = $_POST['PageNo'];
$pageS = $_POST['PageSize'];
}
$getdb = new Song();
$arr = $getdb->getAllRecords($pageNo, $pageS, $totalRecords);
// $strTbl = "";
//
// $stt = 1;
for ($i = 0; $i < count($arr); $i++) {
$obj = $arr[$i];
?>
<tr scope='row'>
<th scope="row">
<label class="control control--checkbox">
<input type="checkbox" />
<div class="control__indicator"></div>
</label>
</th>
<td> <?php echo $obj->songId ?></td>
<td> <?php echo $obj->lastname ?></td>
<td> <?php echo $obj->length ?></td>
<td> <?php echo $obj->picture ?></td>
<td> <?php echo $obj->urlSong ?></td>
<td>
<div style='display:flex;'>
<a href="Admin.php?page=addsong&id=<?php echo $obj->songId; ?>" class='btn btn-info mr-1' id='updatef'><i class='i bi-arrow-repeat'></i></a>
<a href="../backend/delete/delsong.php?id=<?php echo $obj->songId; ?>" class='btn btn-danger mr-1' id='deletef'><i class='bi bi-trash'></i></a>
</div>
</td>
</tr>
<tr class="spacer"><td colspan="100"></td> </tr>
<?php } ?>
</tbody>
</table>
<?php
if (!empty($_POST['reset'])) {
echo "Page : " . $pageNo . " " . "Size: " . $pageS;
}
;
?>
</div>
</div>
</div>
</div>
</div>
I want to display multiple tables from the database with these code, but it did not work, it only showed the blank page without any errors when i click the button. I tried to change the sql to echo test and it worked, so i think the problem in my code is that i did not use the right sql statement.Please help me with this, thank you very much.

I can see a couple of problems.
First, in index.php you're calling an instance method, rather than a static method. Instead of
$getdb = new Song();
$arr = $getdb->getAllRecords($pageNo, $pageS, $totalRecords);
You should use
$arr = Song::getAllRecords($pageNo, $pageS, $totalRecords);
... but that's not what's causing your error.
In your class definition, you have
$song = new GetAllSong();
but I think it should be
$song = new Song();
Also although I can't see an error with your SQL, I'm not sure why you're using a nested query. It might be easier and more peformant to use a simple SQL statement?
Edit: Also you have an SQL injection vulnerability. You're taking whatever someone has POSTed and passing it directly into your SQL statement. If someone crafts a malicious POST request to your web page they could perform whatever SQL they wanted to on your database.

Related

Get all order in shoplify API

I am trying it fetch all orders from the specific date range in Shopify. The problem is I am only able to get 250 orders. I am using the following code.
<div id="main-content1">
<div class="container-fluid">
<?php
function nextorders($lastorderno,$orderfm,$orderto,$orders) {
$orders_obj_url = 'XXXXXXXXXXXXXXXXXXX.myshopify.com/admin/api/2019-10/orders.json&since_id='.$lastorderno.'&status=any&created_at_min='.$orderfm.'T00:00:00&created_at_max='.$orderto.'T23:59:59&fields=created_at,id,order_status_url,total_price_set,number,note,note_attributes';
$orders_content = #file_get_contents( $orders_obj_url );
$orders_json = json_decode( $orders_content, true );
$orders_new = $orders_json['orders'];
$orders = $orders_json['orders'];
if ($remaningprder > 0) {
$lastorderno = $orders['0']["number"];
nextorders($lastorderno,$orderfm,$orderto,$orders_new);
}
return $orders_new;
}
if ($_POST) {
$orderfm = date("Y-m-d", strtotime($_POST['start']));
$orderto = date("Y-m-d", strtotime($_POST['end']));
$orders_obj_url = 'XXXXXXXXXXXXXXXXXXX.myshopify.com/admin/api/2019-10/orders.json?limit=250&fields=created_at,id,order_status_url,total_price_set,number,note,note_attributes&status=any&created_at_min='.$orderfm.'T00:00:00&created_at_max='.$orderto.'T23:59:59';
$orders_content = #file_get_contents( $orders_obj_url );
$orders_json = json_decode( $orders_content, true );
$orders = $orders_json['orders'];
if (count($orders) > 249) {
$remaningprder = $total_order - count($orders);
$lastorderno = $orders['0']["number"];
$orders = nextorders($lastorderno,$orderfm,$orderto,$orders);
}
}
?>
<div class="row clearfix" style="margin-top:20px;margin-bottom:20px;">
<div class="offset-lg-3 offset-md-3 col-lg-6 col-md-6">
</div>
<div class="offset-lg-3 offset-md-3 col-lg-6 col-md-6">
<div>
<form method="POST" action="">
<label>Date Range</label>
<div class="input-daterange input-group" data-provide="datepicker">
<input type="text" class="input-sm form-control" value="<?=$startset;?>" name="start" autocomplete="off">
<span class="input-group-addon range-to">to</span>
<input type="text" class="input-sm form-control" value="<?=$endset; ?>" name="end" autocomplete="off">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="submit">Search</button>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-lg-12">
<div class="card">
<div class="header">
<h2>Last order</h2>
<ul class="header-dropdown dropdown">
<li><i class="icon-frame"></i></li>
</ul>
</div>
<div class="body">
<div class="table-responsive hide-table">
<?php if (count($orders) > 0) { ?>
<table class="table table-striped table-hover dataTable js-exportable">
<thead>
<tr>
<th>#</th>
<th>Order No</th>
<th>Amount</th>
<th>Token</th>
</tr>
</thead>
<tbody>
<?php
$i=1;
foreach ($orders as $order) {
?>
<tr>
<th scope="row" data-title="Date"><?=$i++;?></th>
<td data-title="Order No"><?=$order["number"];?></td>
<td data-title="Amount"><?=$order["total_price_set"]["shop_money"]["amount"];?></td>
<td data-title="Token"></td>
</tr>
<?php } ?>
</tbody>
</table>
<?php } ?>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
And then use the $orders variable to create the output table. It is only sowing 250 orders even if I increase the order limit.
Can anyone help me with this
Thanks
This is an old question I know, but perhaps someone can find use of this answer.
There is a way to get all orders by using the since_id option in the fetch url and cURL. This way you get 250 (or a number of your choosing below 250 since that is the max number you can fetch in one go) orders, starting with the order id 0. This will start at the first order. From here, you loop and fetch orders from (using since_id) the last order in the previous call. And when the number of orders returned is below the number of orders you fetch in each call, you exit.
Example from a Symfony (5) app:
private function getShopifyOrders(): array
{
$this->store_name = $this->params->get('app.shopify_store_name');
$this->api_key = $this->params->get('app.shopify_api_key');
$this->api_pass = $this->params->get('app.shopify_password');
$this->api_url = 'https://' . $this->api_key . ':' . $this->api_pass . '#' . $this->store_name;
$last = 0;
$allOrders = [];
while (true) {
$orders_url = $this->api_url . '/admin/orders.json?limit=250&status=any&since_id=' . $last;
error_log($orders_url); // Show each call in the log for reference
$ch = curl_init($orders_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$orders = json_decode($response);
foreach ( $orders->orders as $order ) {
$allOrders[] = $order;
$last = $order->id;
}
if ( count( $orders->orders ) < 250 ) {
break;
}
}
return $allOrders;
}
You need to use the page_info-based paging that Shopify uses. Essentially, you need to look at the headers of the return, and call a new URL from there if applicable (if there are more results available).
Unfortunately this means you can't use get_file_contents() since it doesn't allow you to view the headers. Check out curl or another library to make proper HTTP requests.
The relevant Shopify docs are here: https://help.shopify.com/en/api/guides/paginated-rest-results

How to fix pagination problem with filter in PHP and SQL?

PHP enthusiast here..
I have a script where it does a query and brings the entire database rows into table cells and it's paginated.
The problem is when a user types something in the search box to filter the pagination, it only works in page 1 showing the filtered results but then it stops working on page 2, on page 2 is goes back to all the paginated results and ignores the filter.
How do I bring the filter value into the url so it stays throughout the pagination?
Sorry if it's obvious I just can't figure it out
<?php require('includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: index.php'); exit(); }
//include header template
require('layout/header.php');
$stmt = $db->query("SELECT name, last_name FROM `designers` WHERE `username` = '" . $_SESSION['username'] . "'");
$result1 = $stmt->fetch(PDO::FETCH_ASSOC);
$name = $result1['name'];
$last_name = $result1['last_name'];
if (isset($_GET['pageno'])) {
$pageno = $_GET['pageno'];
} else {
$pageno = 1;
}
$no_of_records_per_page = 15;
$offset = ($pageno-1) * $no_of_records_per_page;
$conn=mysqli_connect("xxxx", "xxxx", "xxxx", "xxxx");
$total_pages_sql = "SELECT COUNT(*) FROM protonumbers WHERE designer LIKE '".$name.'_'.$last_name."'";
$result = mysqli_query($conn,$total_pages_sql);
$total_rows = mysqli_fetch_array($result)[0];
$total_pages = ceil($total_rows / $no_of_records_per_page);
?>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
text-align: center;
padding: 8px;
}
tr:nth-child(even){background-color: #f2f2f2}
th {
background-color: #428bca;
color: white;
}
</style>
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">
<form action="search.php" autocomplete="off" method="post">
<h3>My Proto Numbers</h3><hr><br>
<?php
//check for any errors
if(isset($error)){
foreach($error as $error){
echo '<p class="bg-danger">'.$error.'</p>';
}
}
?>
</div>
</div>
</div>
<?php
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `protonumbers` WHERE UPPER(CONCAT(`brand`, `protoID`, `season`, `program`, `protonumber`)) LIKE UPPER('%".$valueToSearch."%') AND designer LIKE '".$name.'_'.$last_name."' LIMIT $offset, $no_of_records_per_page";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `protonumbers` WHERE designer LIKE '".$name.'_'.$last_name."' LIMIT $offset, $no_of_records_per_page";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$connect = mysqli_connect("xxxx", "xxxx", "xxxx", "xxxx");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
}
?>
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">
<div class="form-group">
<input type="text" name="valueToSearch" class="form-control input-lg" placeholder="Search by Proto number, Season, Brand, Program" tabindex="1">
<div class="row"><br />
<div class="col-xs-6 col-md-6">
<input type="submit" name="search" value="Search" class="btn btn-primary btn-block btn-lg" tabindex="2"> .
</form></div></div></div></div>
<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">
Back<br><br> <ul class="pagination">
<li>First</li>
<li class="<?php if($pageno <= 1){ echo 'disabled'; } ?>">
Prev
</li>
<li class="<?php if($pageno >= $total_pages){ echo 'disabled'; } ?>">
<a href="<?php if($pageno >= $total_pages){ echo '#'; }
else { echo "?pageno=".($pageno + 1); } ?>">Next</a>
</li>
<li>Last</li>
</ul>
<table>
<tr>
<th>ProtoID</th>
<th>Brand</th>
<th>Season</th>
<th>Program</th>
<th>Proto Number</th>
</tr>
<!-- populate table from mysql database -->
<?php while($row =
mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['protoID'];?></td>
<td><?php echo $row['brand'];?></td>
<td><?php echo $row['season'];?></td>
<td><?php echo $row['program'];?></td>
<td><?php echo $row['protonumber'];?></td>
</tr>
<?php endwhile;?>
</table>
</div></div>
<?php
//include header template
require('layout/footer.php');
?>
Ok, so, as stated in the comments this boils down to HTTP not being stateful, you'll need to persist those filters values across requests. So, storing things in say session, or simply keeping the URIs query string in state.
So building out that query string...
<?php
$assignedFilters = [];
if (!empty($name)) $assignedFilters['name'] = $name;
if (!empty($last_name)) $assignedFilters['last_name'] = $last_name;
$filterParams = http_build_query($assignedFilters);
?>
And then getting it on the href for you pagination links... Here is one example
<a href="<?php if($pageno <= 1) { echo '#';
} else {
echo "?pageno=".($pageno - 1) . '&' . $filterParams; } ?>">Prev</a>
In other words append . '&' . $filterParams to your existing pagination links.

How to validate checkbox in a for loop

I am creating a seat reservation system. In my system, the code check number of seats a bus contains then pass it inside a for loop. When a user pick 2 passengers, it means two seats will be booked. How can I validate the checkbox in the for loop depending on the number of passenger(s) selected.
Using the GUI for more explanation.
on the main page, 2 there indicates number of passenger(s) selected.
When you come to the second page where the values are passed to, you can see 2 Adults as the selected number of passengers. When you click on Submit Button it does not validate the checkbox based on the number of passenger(s) selected. And if I should put required in the checkbox it validates the whole checkbox since it is in a loop
$_SESSION['seat_no'] is the number of seat(s) a bus contains. Let assume a user that want to book a seat selected two passengers which means two seats is booked, how can I validate the checkbox based on the number of seat(s) selected?
Here is my code:
<?php
for ($i = 1; $i <= $_SESSION['seat_no']; $i++) {
if(in_array($i,$mseat)){
echo "<div class='checkbox_wrapper_pick'>
<label>".$i."</label>
</div>";
}else{
echo "<div class='checkbox_wrapper'>
<input type='checkbox' value=".$i." name='seat_book[]' />
<label>".$i."</label>
</div>";
}
}
?>
The full source code:
<?php include("header.php"); error_reporting(0); ?>
<?php
if(isset($_POST['submit'])){
$from = $_POST['from'];
$to = $_POST['to'];
$date = $_POST['d_date'];
$nop = $_POST['nop'];
$_SESSION['from'] = $from;
$_SESSION['to'] = $to;
$_SESSION['date'] = $date;
$_SESSION['nop'] = $nop;
$get = mysqli_query($mysqli,"SELECT * FROM routes WHERE present_loc = '$from' and destination = '$to' ");
while($roys = mysqli_fetch_array($get)){
//get bus details
$bno = $roys['bus_no'];
$ploc = $roys['present_loc'];
$des = $roys['destination'];
$time = $roys['dept_time'];
$_SESSION['time'] = $time;
$amt = $roys['amount'];
$_SESSION['amt'] = $amt;
$b = str_replace( ',', '',$_SESSION['amt'] );
if( is_numeric($b) ) {
$a = $b;
}
$bus = mysqli_query($mysqli,"select * from bus where bus_no = '$bno'");
while($bu = mysqli_fetch_array($bus)){
$_SESSION['model'] = $bu['model'];
$_SESSION['seat_no'] = $bu['seat_no'];
$_SESSION['ac'] = $bu['bus_type'];
$_SESSION['excess_luggage'] = $bu['excess_luggage'];
$_SESSION['more_legs'] = $bu['more_legs'];
$_SESSION['id'] = $bu['id'];
}
$coun = mysqli_query($mysqli, "select count(booking_id) as seat, seats from booking where bus_no = '$bno' and seats !='' GROUP by booking_id" );
$mseat = array();
while($e = mysqli_fetch_array($coun)){
$bseat = $e['seat'];
$mseat[] = $e['seats'];
}
//$seatss = array();
$seat_string = implode(",",$mseat);
//get seats
$couns = mysqli_query($mysqli, "select sum(counter) as seat from booking where bus_no = '$bno' and seats !='' GROUP by bus_no" );
$rseats = mysqli_fetch_array($couns);
$lseat = $rseats['seat'];
if($_SESSION['seat_no'] == $lseat){
$tell = " No more seat(s) available.";
}else{
$tell = $_SESSION['seat_no'] - $lseat. " Seat(s) remaining.";
}
}
}
?>
<!--Main layout-->
<main class="mt-5">
<!--Main container-->
<form action="details" method="POST">
<!--Grid row-->
<div class="row">
<div class="col-lg-12 title-header mb-3 mx-auto z-depth-1">
<div class="row">
<div class="col-lg-8">
<?php echo '<h2> '.$_SESSION['from']. ' to '. $_SESSION['to']. '</h2>'; ?><br/>
<b><?php echo $_SESSION['date']; ?> :: <?php if($_SESSION['nop'] < '2') { echo $_SESSION['nop'] . ' Adult'; }
elseif($_SESSION['nop'] > 1) { echo $_SESSION['nop'] . ' Adults'; }
?></b>
</div>
</div>
</div>
<div class="col-lg-12 mbody"> <label style="margin-left: 4%; font-weight:bolder; font-size:20px; color:#000;">Details </label> </div>
<div class="col-lg-12 mbody bg-white ">
<table class="table table_view" style = "width: 100%; margin-left: 4%; margin-right:4%;">
<tbody>
<tr>
<td><b><?php echo $_SESSION['model']; ?></b><br/><?php echo $_SESSION['from']. ' to '. $_SESSION['to']; ?>
<br/><?php if($_SESSION['ac'] == 'AC') { echo '<span class="alert-info ac">'. $_SESSION['ac'] .'</span>'; }
else{ echo '<span class="alert-warning">No AC</pan>'; } ?>
<?php if($_SESSION['more_legs'] == 'Yes') { echo '<span class="alert-info ac">More Leg Room</span>'; }
else{ echo '<span class="alert-warning no">More Leg Not Available</pan>'; } ?>
</td>
<td><b>Departing Time</b><br/><i class="fa fa-clock-o" aria-hidden="true"></i> <?php echo $_SESSION['time']; ?></td>
<td> <img id = "seatimg" src="../images/seatsLayout/av.gif" class="img-responsive"> <?php echo $tell; ?></td>
<td>Adult <b>₦<?php echo $_SESSION['amt']; ?></b></td>
</tr>
</tbody>
</table>
</div>
<div class="col-lg-12">
<div class="col-lg-12 mbody"> <label style="margin-left: 3%; font-weight:bolder; font-size:20px; color:#000;"><img id = "seatimg" src="../images/seatsLayout/av.gif" class="img-responsive"> Select Seat</label> </div>
<div class="row detail">
<!--Grid column-->
<div class="col-lg-7 animation slideUp" >
<div class="well" id="bus_seats_layout" >
<table class="table table-bordered" cellspacing = "1" id="seatstable">
<tr>
<td><img id = "driverimg" src="../images/seatsLayout/steering.png" class="img-responsive" width="25" height="25"></td>
<td colspan="2" rowspan="3">
<?php
for ($i = 1; $i <= $_SESSION['seat_no']; $i++) {
if(in_array($i,$mseat)){
echo "
<div class='checkbox_wrapper_pick'>
<label>".$i."</label>
</div>
";
}else{
echo "
<div class='checkbox_wrapper'>
<input type='checkbox' value=".$i." name='seat_book[]' />
<label>".$i."</label>
</div>
";
}
}
?>
</td>
</tr>
</table>
</div>
</div>
<div class="col-lg-5">
<ul class="bt">
<li><img src="../images/seatsLayout/seat_available.png" class="img-responsive"> Available</li>
<li><img src="../images/seatsLayout/picked.png" class="img-responsive"> Selected</li>
<li><img src="../images/seatsLayout/seat_booked.png" class="img-responsive"> Booked</li>
</ul>
</div>
</div>
<div class="col-lg-12">
<input type="hidden" name="bus_no" value="<?php echo $bno; ?>">
<input type="hidden" name="to" value="<?php echo $to; ?>">
<input type="hidden" name="from" value="<?php echo $from; ?>">
<input type="hidden" name="amt" value="<?php echo $nop*$a; ?>">
<input type="hidden" name="nop" value="<?php echo $nop; ?>">
<div class="form-group">
<div align="right">
<input type="submit" name="submit" class="bme" value="Continue">
</div>
</div>
</div>
</div>
</div>
</form>
</main>
<?php include("footer.php"); ?>

multiple entry of products in the database - PHP

I explain briefly I created a table that shows all my products on video, where inside the container that contains it are two select, enclosed in a form, which pass values ​​in order to populate the table in my db, and everything works perfectly. The only thing though that when I select more than one product the db correctly registers only the last one selected from the checkbox,place my code in order to reach my goal, that of being able to insert more products(impianto_id_campagna),for the same customer id (cliente_id_campagna), and event id (id_campagna_cliente):
code:
<?php
$messaggio = "";
if (isset($_POST['submit'])) {
include '../connessione.php';
$id_campagna_cliente = $connessione->real_escape_string($_POST['id_campagna_cliente']);
$cliente_id_campagna = $connessione->real_escape_string($_POST['cliente_id_campagna']);
$impianto_id_campagna = $connessione->real_escape_string($_POST['impianto_id_campagna']);
$connessione->query("INSERT INTO campagne_cliente (
id_campagna_cliente,
cliente_id_campagna,
impianto_id_campagna)
VALUES (
'$id_campagna_cliente',
'$cliente_id_campagna',
'$impianto_id_campagna')");
$messaggio = "Registrazione Completata!";
}
?>
<main>
<?php
include '../connessione.php';
$query_string = "SELECT * FROM store_locator WHERE store_locator.id NOT IN (SELECT impianto_id_campagna FROM campagne_cliente)";
$query = mysqli_query($connessione, $query_string);
?>
<?php
include '../connessione.php';
$query_string = "SELECT * FROM clienti";
$clienti = mysqli_query($connessione, $query_string);
?>
<?php
include '../connessione.php';
$query_string = "SELECT * FROM campagne_cliente
INNER JOIN clienti
ON clienti.cliente_id = campagne_cliente.cliente_id_campagna
INNER JOIN campagne
ON campagne.id_campagna = campagne_cliente.id_campagna_cliente GROUP BY cognome";
$campagne = mysqli_query($connessione, $query_string);
?>
<!-- Datatables initialization -->
<script>
// Basic example
$(document).ready(function () {
$('#dtBasicExample').DataTable();
$('.dataTables_length').addClass('bs-select');
});
</script>
<!-- Structured data: Breadcrumbs -->
<form method="post" action="index.php">
<div class="container-fluid text-center">
<div class="row">
<div class="col-md-6">
<select name="cliente_id_campagna" class="ciao colorful-select dropdown-primary" multiple searchable="Cerca il Cliente">
<option value="" disabled selected>Cliente</option>
<?php
while($row = mysqli_fetch_assoc($clienti)){ ?>
<option value="<?php echo $row['cliente_id'] ;?>"><?php echo $row['nome'].' '.$row['cognome'] ;?></option>
<?php } ?>
</select>
<script type="text/javascript">
// Material Select Initialization
$(document).ready(function() {
$('.ciao').material_select();
});
</script>
</div>
<div class="col-md-6">
<select name="id_campagna_cliente" class="ok colorful-select dropdown-primary" multiple searchable="Cerca la campagna">
<option value="" disabled selected>Cliente</option>
<?php
while($row = mysqli_fetch_assoc($campagne)){ ?>
<option value="<?php echo $row['id_campagna_cliente'] ;?>"><?php echo $row['nome'].' '.$row['cognome'].' INIZIO['.$row['data_inizio'].'] FINE['.$row['data_fine'].']' ;?></option>
<?php } ?>
</select>
<script type="text/javascript">
// Material Select Initialization
$(document).ready(function() {
$('.ok').material_select();
});
</script>
</div>
</div>
<div class="col-md-12">
<?php if ($messaggio != "") echo $messaggio . "<br><br>"; ?>
<table id="dtBasicExample" class="table table-striped table-bordered table-sm" cellspacing="0" width="100%">
<thead>
<tr>
<th class="th-sm">ID
<i class="fa fa-sort float-right" aria-hidden="true"></i>
</th>
<th class="th-sm">Cimasa
<i class="fa fa-sort float-right" aria-hidden="true"></i>
</th>
<th class="th-sm">Proprietaria
<i class="fa fa-sort float-right" aria-hidden="true"></i>
</th>
<th class="th-sm">Concessionaria
<i class="fa fa-sort float-right" aria-hidden="true"></i>
</th>
<th class="th-sm">City
<i class="fa fa-sort float-right" aria-hidden="true"></i>
</th>
<th class="th-sm">Latitudine
<i class="fa fa-sort float-right" aria-hidden="true"></i>
</th>
<th class="th-sm">Longitudine
<i class="fa fa-sort float-right" aria-hidden="true"></i>
</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_assoc($query)){ ?>
<tr>
<td>
<!-- Material unchecked -->
<div class="form-check">
<input type="checkbox" name="impianto_id_campagna" class="form-check-input" value="<?php echo $row['id'] ;?>" id="<?php echo $row['id'] ;?>">
<label class="form-check-label" for="<?php echo $row['id'] ;?>"></label>
</div>
</td>
<td><?php echo $row['cimasa'] ;?></td>
<td><?php echo $row['proprietaria'] ;?></td>
<td><?php echo $row['concessionaria'] ;?></td>
<td><?php echo $row['city'] ;?></td>
<td><?php echo $row['lat'] ;?></td>
<td><?php echo $row['lng'] ;?></td>
</tr>
<?php } ?>
</tfoot>
</table>
<input class="btn btn-primary" name="submit" type="submit" value="Register..."><br>
</form>
</div>
</div>
It register only the last one selected product because you have the same name attribute for every checkbox. Set the name to impianto_id_campagna[] in order to return an array in your $_POST variable.
<input type="checkbox" name="impianto_id_campagna[]" class="form-check-input" value="<?php echo $row['id'] ;?>" id="<?php echo $row['id'] ;?>">
Then you loop all your checkbox values inserting one product at a time:
<?php
$id_campagna_cliente = $connessione->real_escape_string($_POST['id_campagna_cliente']);
$cliente_id_campagna = $connessione->real_escape_string($_POST['cliente_id_campagna']);
foreach ($_POST['impianto_id_campagna'] as $value)
{
$impianto_id_campagna = $connessione->real_escape_string($value);
$connessione->query("INSERT INTO campagne_cliente (
id_campagna_cliente,
cliente_id_campagna,
impianto_id_campagna)
VALUES (
'$id_campagna_cliente',
'$cliente_id_campagna',
'$impianto_id_campagna')");
$messaggio = "Registrazione Completata!";
}
Checkbox items are passed as an array. In order to get them in to the database, you have to loop through the array and act accordingly.
foreach($impianto_id_campagna as $row){
//Iterate through and do what you need to do with the data.
}

data insert into database automatically in php

I have a problem which is the user when write in my comments form is insert successfully but when I refresh the page it will insert the last comments again , I read the solution in this link how to stop data automatically insert into database in php
but does not work for me
this is my codes I would appreciate for your help :)
file viewhospital.php contain include comments.php file
--look at the bottom of the codes--
<?php
include ('header.php');
if(!isset($_GET['hospital_id'])){
echo '<div class="alert alert-danger" role="alert"><b>You should choose hospital before opening this page!</b></div>';
include ('footer.php');
die();
}
include ('setting.php');
$sql = 'select * from hospital where hid = '. $_GET['hospital_id'];
$result = $conn->query($sql) or die(mysql_error($conn));
$hospital = null;
if ($result->num_rows > 0) {
$hospital = $result->fetch_assoc();
} else {
die('Could not find hospital!');
}
$sql = 'select * from doctor where hospital_id = '. $_GET['hospital_id'];
$doctor_result = $conn->query($sql) or die(mysql_error($conn));
$conn->close();
?>
<div class="row">
<div class="col-md-6">
<p class="text-center">
<img src="<?php echo $hospital['image']; ?>" class="img-thumbnail" style="height: 400px;">
</p>
</div>
<div class="col-md-6">
<p class="text-center">
<img class="img-thumbnail" src="https://maps.googleapis.com/maps/api/staticmap?center=<?php echo $hospital['location']; ?>&zoom=13&size=400x400&maptype=roadmap&markers=color:blue%7Clabel:S%7C<?php echo $hospital['location']; ?>&key=AIzaSyD59nHXpZgqZwjJvsAcPe2CYcIEWoaQ9yY" style="height: 400px;">
</p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<h1 class="page-header">
<?php echo $hospital['name']; ?>
</h1>
<p>
<?php echo $hospital['description']; ?>
</p>
<p>
Address: <?php echo $hospital['address']; ?>
</p>
<p>
Phone: <?php echo $hospital['phone']; ?>
</p>
<p>
Go To Hospital
</p>
<p>
Online Appointment
</p>
</div>
</div>
<!--<div class="row">
<div class="col-md-12 text-center">
<div class="btn-group" role="group" aria-label="...">
<a type="button" class="btn btn-info">Edit</a>
<a type="button" class="btn btn-danger">Remove</a>
<a type="button" class="btn btn-primary" href="doctor_form.php?hospital_id=<?php echo $hospital['hid']; ?>">Add Doctor</a>
</div>
</div>
</div>-->
<div class="row">
<div class="col-md-12">
<table class="table table-striped">
<caption>Doctors:</caption>
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Field</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
if ($doctor_result->num_rows > 0) {
while($row = $doctor_result->fetch_assoc()) {
?>
<tr>
<th scope="row">
<?php echo $row['did'];?>
</th>
<td>
<?php echo $row['name'];?>
</td>
<td>
<?php echo $row['field'];?>
</td>
<td>View</td>
</tr>
<?php
}
}else{
?>
<tr>
<th scope="row"></th>
<td>No doctors found</td>
<td></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
<?php
include ('comments.php');
include ('footer.php');
?>
the comments.php file
<?PHP
# comments PHP code
date_default_timezone_set('Asia/Riyadh');
function setComments (){
if (isset($_POST['submitComments'])){
include('setting.php');
//$uid = $_POST['uid'];
$date = $_POST['date'];
$message = $_POST['message'];
$sql = "INSERT INTO comments ( date, message) VALUE ( '$date', '$message')";
$result = mysqli_query($conn,$sql);
}
}
function getComments (){
if (isset($_POST['submitComments'])){
include('setting.php');
$sql = "SELECT * FROM comments";
$result = mysqli_query($conn,$sql);
while ($row = $result->fetch_assoc()){
echo "<div class='comments-box'>";
echo $row['date']."<br>";
echo nl2br($row['message'])."<br><br>";
echo "</div>";
}
}
}
echo "
<form action='".setComments ()."' method='POST'>
<input type='hidden' name='uid' value=''>
<input type='hidden' name='date' value='".date('Y-m-d H:i:s')."'>
<textarea name='message' class='form-control' rows='3'></textarea>
<br>
<button type='submit' name='submitComments' class='btn btn-primary'>Comments</button>
</form>
<br><br>
";
getComments ();
?>
When you refresh in the browser, you send the last request again. That request was the POST of the form. So the user (browser) is telling the code to insert another comment.
Generally this is handled by redirecting after posting a form, rather than re-displaying the form again. Move all of your logic for (and only for) inserting the new content to its own PHP file (something like addComment.php) and have the form post to that file. Then in that file ensure that there is no actual output except perhaps to display an error message if something goes wrong?) and just a redirect back to the page:
header("Location: viewhospital.php");
This will instruct the browser in the response to make a new GET request for viewhospital.php. So if the user reloads the browser, all they're doing is repeating that GET request.

Categories