I have an array that picks from the database the staff_id and display them randomly in a table.
But I want to duplicate the array based on the staff_level, such that junior staffs will be duplicated while senior staff will not be duplicated.
This is to make the Junior staffs appear twice than the senior staff. This is the code:
foreach ($invigilator_array_indexes as $array_index) {
if ($row['level'] == 1){
$invi_array = $invigilators[$array_index]['staffid_pdo'].', ';
$output .=$invi_array;
$output .=$invi_array.concat();
}else {
$invi_array = $invigilators[$array_index]['staffid_pdo'].', ';
$output .=$invi_array;
}
}
Please note:
foreach ($invigilator_array_indexes as $array_index) {
$invi_array = $invigilators[$array_index]['staffid_pdo'].', ';
$output .=$invi_array;
}
outputs the staff_id in a random order originally
All help is welcome and will be appreciated. Thank you in anticipation
full code:
<?php
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$records_per_page = 50;
$from_record_num = ($records_per_page * $page) - $records_per_page;
include_once 'includes/config.php';
include_once 'includes/data.inc_course.php';
include 'includes/shuffle2.php';
$database = new Config();
$db = $database->getConnection();
$product = new Data($db);
$stmt = $product->readAll($page, $from_record_num, $records_per_page);
$num = $stmt->rowCount();
//range declaration
$range = $_POST['range'];
?>
<?php include('includes/header.php');
$output1 = "
<body>
<div id='wrapper'>";
echo $output1;
include('includes/nav.php');
$output2 = "
<!-- Page Content -->
<div id='page-wrapper'>
<div class='container-fluid'>
<div class='row'>
<div class='col-lg-12'>
<h1 class='page-header'>Timetable Details</h1>
</div>
<!-- /.col-lg-12 -->
<!-- niyicode -->
<div class='col-lg-12'>
<p>
<a class='btn btn-primary' href='courses/add.php' role='button'>Add Course</a>
<a class='btn btn-primary fleft' href='staff/add.php' role='button'>Add Staff</a>
</p>";
echo $output2;
if($num>0){
if($range>0){
$query1 = "SELECT staffid_pdo,level FROM staff_list WHERE avail_pdo = 1 ORDER BY id_pdo ASC ";
$invi_stmt = $db->prepare($query1);
$invi_stmt->execute();
$invigilators = $invi_stmt->fetchAll(PDO::FETCH_ASSOC);
//generate an array containing the range of keys in the invigilators resultset we got above
$invigilators_array_range = range(0, (count($invigilators) - 1));
$output = "
<table class= 'table table-bordered table-hover table-striped js-serial' id='printTable'>
<caption>Timetable with number of students</caption>
<thead>
<tr class='success'>
<th style='width: 4%'>#</th>
<th>No. Students</th>
<th>Code</th>
<th>Date</th>
<th>Start Time</th>
<th>End Time</th>
<th>Venue</th>
<th>Duration</th>
<th>Invigilator</th>
<!-- <th>Edit/Del</th> -->
</tr>
</thead>
<tbody>
";
// echo $output;
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
extract($row);
$invigilators_needed = round(($row['snb_pdo'] / $range), 0, PHP_ROUND_HALF_EVEN);
print_r($invigilators_needed);
$date_active = $row['dat_pdo'];
$output .= ' <tr>' ;
$output .= '' ;
$output .= ' <td>'.$row['snb_pdo'].'</td>' ;
$output .= ' <td>'.$row['coscd_pdo'].'</td>' ;
$output .= ' <td>'.$date_active.'</td>' ;
$output .= ' <td>'.$row['starttim_pdo'].'</td>' ;
$output .= ' <td>'.$row['endtim_pdo'].'</td>' ;
$output .= ' <td>'.$row['ven_pdo'].'</td>' ;
$output .= ' <td>'.$row['dur_pdo'].'</td>' ;
$output .= ' <td>';
$invigilator_array_indexes = array_rand($invigilators_array_range, $invigilators_needed);
if (count($invigilator_array_indexes)) {
foreach ($invigilator_array_indexes as $array_index) {
if ($row['level'] == 1){
$invi_array = $invigilators[$array_index]['staffid_pdo'].', ';
$output .=$invi_array;
$output .=$invi_array.clone();
}else {
$invi_array = $invigilators[$array_index]['staffid_pdo'].', ';
$output .=$invi_array;
}
print_r($invi_array);
}
} else $output .= "
<div class='alert alert-danger' role='alert'>
<button type='button' class='close' data-dismiss='alert' aria-label='Close'></button>
Not enough <strong>invigilators!</strong>
</div>
";
$output .= '</td>' ;
// Add more here if appropriate .... ;
$output .= ' </tr>' ;
?>
<?php
// }
}
$output .=' </tbody>
</table>
';
$results->free();
mysqli_close($mysqli);
echo $output;
$page_dom = "index.php";
include_once 'includes/pagination.inc_course.php';
?>
<center><button onclick="printData();" class="btn btn-primary hideprint"> Print </button></center>
<br/>
<?php
//range ending
} else {
?>
<div class="alert alert-warning alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>Warning!</strong> No valid range entered. Please enter a valid range here!
</div>
<?php
}
?>
<?php
//if num ending
}
else{
?>
<div class="alert alert-warning alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>Warning!</strong> No Data. Please add data to view timetable
</div>
<?php
}
?>
<?php
$output5 = " </div>
</div>
<!-- /.row -->
</div>
<!-- /.container-fluid -->
</div>
<!-- /#page-wrapper -->
</div>
<!-- /#wrapper -->
";
echo $output5;
?>
<!-- echo $output; -->
<?php include('includes/footer.php'); ?>
I have a page displaying data from an array. When the user click on one of the picture displayed, I would need to save the value $row["Rif"] as I'd need to display the item details in another page.
I was looking around but it seems that Jquery, Ajax are the only available solutions but I don't know these.
Is there any way to implement it using just PHP?
Thank you!
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<div class='col-md-3 col-sm-6 col-xs-12'>
<div class='property-container'>
<div class='property-image'>
<img src='img/img02.jpg' alt='test theme'>
<div class='property-price'>
" . $row["DescCom"] . "<br>
<span>" . "€ ". $row["Pre"] . " </span>
</div>
<div class='property-status'>
<span>" . $row["Rif"] . "</span>
</div>
</div>
<div class='property-features'>
<span><i class='fa fa-home'></i> " . $row["Mq"] . " m<sup>2</sup></span>
<span><i class='fa fa-hdd-o'></i> " . $row["Cam"] . " Cam</span>
<span><i class='fa fa-male'></i> Piano " . $row["Pia"] . " </span>
</div>
<div class='property-content'>
<h3>" . $row["TIP"] . "<small>" . $row["Fra"] . "</small></h3>
<button type='submit' name='submit' class='btn btn-default btn-warning btn-xs pull-right btn-dettagli'>Details</button>
</div>
</div>
</div>";
}
} else {
echo '0 results';
}
$conn->close();
?>
Assuming the data is stored in $row["Rif"]
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<div class='col-md-3 col-sm-6 col-xs-12'>
<div class='property-container'>
<div class='property-image'>
// if this is the image you can hyper-link it to next page that will carry the id as well.
<img src='img/img02.jpg' alt='test theme'>
<div class='property-price'>
" . $row["DescCom"] . "<br>
<span>" . "€ ". $row["Pre"] . " </span>
</div>
<div class='property-status'>
<span>" . $row["Rif"] . "</span>
</div>
</div>
<div class='property-features'>
<span><i class='fa fa-home'></i> " . $row["Mq"] . " m<sup>2</sup></span>
<span><i class='fa fa-hdd-o'></i> " . $row["Cam"] . " Cam</span>
<span><i class='fa fa-male'></i> Piano " . $row["Pia"] . " </span>
</div>
<div class='property-content'>
<h3>" . $row["TIP"] . "<small>" . $row["Fra"] . "</small></h3>
<button type='submit' name='submit' class='btn btn-default btn-warning btn-xs pull-right btn-dettagli'>Details</button>
</div>
</div>
</div>";
}
} else {
echo '0 results';
}
$conn->close();
?>
if this is the image you can hyper-link it to next page that will carry the id as well.
<img src='img/img02.jpg' alt='test theme'>
I have one problem with my form. I am trying to add something to the database with a from using ajax and php, but when I first time add something it works fine, perfect, but when I try to add another item directly after the first one, the form is submitted three times, then when I try again it is submitted five times ....
My ajax code is :
<script type="text/javascript">
$(document).ready(function() {
$("#addPetForm").submit(function(e){
e.preventDefault();
});
$(document).on("click","#btn-add-pet", function(){
var bootstrapValidator = $("#addPetForm").data('bootstrapValidator');
bootstrapValidator.validate();
if(bootstrapValidator.isValid()){
//function after succesful file upload (when server response)
function afterSuccess(msg)
{
bootstrapValidator.resetForm();
$('#input-700').fileinput('clear');
$("#info-middle-register").hide();
$("#pleaseWaitGif").hide();
if(msg.status == "NotUpdated"){
//Ako nije uspijesno dodano
$("#addpeterror").html(msg.result).fadeIn(400).fadeOut(10000);
}else if(msg.status == "Updated"){
$("#addpetsuccess").html(msg.result).fadeIn(400).fadeOut(10000);
if(msg.noPhotosAdded == "No photos added"){
$("#addpeterror").html("<i class=\"fa fa-exclamation-triangle\"></i> De nieuwe foto's zijn niet toegevoegd!").fadeIn(400).fadeOut(10000);
}
if(msg.noPhotosSelected == "No photos selected"){
$("#addpetwarning").html("<i class=\"fa fa-exclamation-circle\"></i> Er zijn geen nieuwe foto's gekozen. Het is aanbevolen om minstens één foto toe te voegen.").fadeIn(400).fadeOut(10000);
}
$("#addPetForm").find("input[type=text], textarea, select]").val("");
$('[name="geslacht"]').val('').selectpicker('refresh');
$("#oldPhotos").hide();
$("#cancelBack").html("<button id=\"dataTitle\" class=\"btn btn-danger btn-cancel\" data-title=\"Ga terug\"><i class=\"fa fa-arrow-left\"></i>   Terug naar profiel</button>");
}else if(msg.status == "NotAdded"){
//Ako nije uspijesno dodano
$("#addpeterror").html(msg.result).fadeIn(400).fadeOut(10000);
}else{
//Ako je query bio uspijesan, tj dodana je zivotinja u bazu
if(msg.status == "Added"){
$("#addpetsuccess").html(msg.result).fadeIn(400).fadeOut(10000);
$("#totalPets").html(msg.nrPets);
if(msg.noPhotosAdded == "No photos added"){
$("#addpeterror").html("<i class=\"fa fa-exclamation-triangle\"></i> De foto's zijn niet toegevoegd!").fadeIn(400).fadeOut(10000);
}
if(msg.noPhotosSelected == "No photos selected"){
$("#addpetwarning").html("<i class=\"fa fa-exclamation-circle\"></i> Er zijn geen foto's gekozen. Het is aanbevolen om minstens één foto toe te voegen.").fadeIn(400).fadeOut(10000);
}
$('[name="geslacht"]').val('').selectpicker('refresh');
}
}
}
//function to check file size before uploading.
function beforeSubmit(){
$("#info-middle-register").show();
$("#pleaseWaitGif").show();
}
//progress bar function
function OnProgress()
{
$("#info-middle-register").show();
$("#pleaseWaitGif").show();
}
var options = {
beforeSubmit: beforeSubmit, // pre-submit callback
success: afterSuccess, // post-submit callback
uploadProgress: OnProgress, //upload progress callback
dataType: "json",
resetForm: true // reset the form after successful submit
};
$(document).on("submit", "#addPetForm", function(e) {
$(this).ajaxSubmit(options);
// always return false to prevent standard browser submit and page navigation
return false;
});
}
else return;
});
});
</script>
My php form is :
<div id="signupbox" style="display:block; margin:0 auto;float:none;" class="mainbox">
<div class="panel panel-info">
<div class="panel-heading">
<div class="panel-title"><i class="fa fa-user-plus"></i> Voeg uw verloren dier toe</div>
</div>
<div class="panel-body">
<div id="info-middle-register" style="display:none;z-index:99999999;"><img src="img/ajax-loader.gif" title="Even geduld aub"></div>
<!-- Ispis poruka vracenih iz dier-toevoegen-submit -->
<div id="addpetsuccess" style="display:none;text-align:center;" class="alert alert-success alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div id="addpeterror" style="display:none;text-align:center;" class="alert alert-danger alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div id="addpetwarning" style="display:none;text-align:center;" class="alert alert-warning alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<form id="addPetForm" action="dier-toevoegen-submit.php" class="form-horizontal" role="form" method="post" enctype="multipart/form-data">
<div class="help-block" style="text-align:center;margin:10px 0 30px 0;">
Beschrijf uw huisdier via het onderstaande formulier zo <b>volledig</b> mogelijk (het is ook aanbevolen om minstens één foto toe te voegen) zodat de mensen uw dier gemakkelijker kunnen herkennen.
</div>
<input type="hidden" value="<?php echo $_POST["changeID"]; ?>" name="txtHiddenID" >
<div class="left-inner-addon form-group col-lg-6" style="margin: 0 0 15px 0;">
<span><i class="fa fa-paw"></i></span>
<input id="addPetName" type="text" class="form-control" name="name" placeholder="Naam van uw dier" required value="<?php echo $petNameOld; ?>">
</div>
<div class="left-inner-addon form-group col-lg-6" style="margin: 0 0 15px 0;">
<span><i class="fa fa-reddit-alien"></i></span>
<input id="addPetBreed" type="text" class="form-control" name="breed" placeholder="Ras van uw dier" required value="<?php echo $petBreedOld; ?>">
</div>
<div style="clear:both"></div>
<div class="left-inner-addon form-group col-lg-6" style="margin: 0 0 15px 0;">
<span><i class="fa fa-fire-extinguisher"></i></span>
<input id="addPetColor" type="text" class="form-control" name="color" placeholder="Kleur van uw dier" required value="<?php echo $petColorOld; ?>">
</div>
<div class="left-inner-addon form-group col-lg-6" style="margin: 0 0 15px 0;">
<span><i class="fa fa-map-marker"></i></span>
<input id="addPetLastSeen" type="text" class="form-control" name="lastSeen" placeholder="Laatste keer gezien in?" required value="<?php echo $petLostPlaceOld; ?>">
</div>
<div style="clear:both"></div>
<?php
$selected = "selected";
if($changeID){
if($petGenderOld == "Mannelijk"){
$mannelijk = "selected";
$selected = "";
$vrouwelijk = "";
}else{
if($petGenderOld == "Vrouwelijk"){
$vrouwelijk = "selected";
$selected = "";
$mannelijk = "";
}
}
}
?>
<div class="form-group col-md-6 col-xs-12">
<div class="col-md-12 col-xs-12 selectContainer ">
<select name="geslacht" class="form-control">
<option disabled <?php echo $selected; ?> hidden data-icon="glyphicon glyphicon-chevron-right">Kies geslacht</option>
<option value="Mannelijk" <?php echo $mannelijk; ?>>Mannelijk</option>
<option value="Vrouwelijk" <?php echo $vrouwelijk; ?>>Vrouwelijk</option>
</select>
</div>
</div>
<div class="form-group col-md-6 col-xs-12 pull-right">
<div class="col-md-12 col-xs-12 date">
<div class="input-group date" id="dateRangePicker">
<input type="text" class="form-control" name="date" placeholder="Vermist sinds?" value="<?php echo $petlostDateOld; ?>"/>
<span class="input-group-addon add-on"><span class="glyphicon glyphicon-calendar"></span></span>
</div>
</div>
</div>
<div style="clear:both"></div>
<div class="form-group">
<div class="col-xs-12 col-md-12">
<textarea name="dierDescription" class="form-control" rows="5" required placeholder="Beschrijf hier uw huisdier"><?php echo $petDetailsOld; ?></textarea>
</div>
</div>
<!-- Ovdje se prikazuju slike kad se radi update -->
<?php
if($changeID){
echo "<div id=\"oldPhotos\">";
$rezOldPhotos = mysqli_query($kon, "SELECT * FROM petsfotos WHERE pet_id = ". $changeID ."");
$nrPhotos = mysqli_num_rows($rezOldPhotos);
if($nrPhotos > 0){
while($redOldPhotos = mysqli_fetch_assoc($rezOldPhotos)){
$photoAlt = $redOldPhotos["id"] . "." . $petNameOld;
$photoName = $redOldPhotos["name"];
$photoId = $redOldPhotos["id"];
echo "<div class=\"file-preview-frame\" data-fileindex=\"0\" id=\"oldFoto-". $photoId ."\">
<img class=\"file-preview-image\" style=\"width:auto;height:160px;\" alt=\"". $photoAlt ."\" title=\"". $photoAlt ."\" src=\"images/uploads/pets/". $changeID ."/". $photoName ."\">
<div class=\"file-thumbnail-footer\">
<div class=\"file-footer-caption\" title=\"". $photoName ."\">". $photoName ."</div>
<div class=\"file-actions\">
<div class=\"file-footer-buttons\">
<button class=\"linkDelOldFoto kv-file-remove btn btn-xs btn-danger\" title=\"Verwijder deze foto\" type=\"button\" id=\"btnDelOldFoto-". $photoId ."\">
<i class=\"glyphicon glyphicon-trash text-danger\" style=\"color:#fff;\"></i> Delete
</button>
</div>
<div class=\"clearfix\"></div>
</div>
</div>
</div> ";
}
}else{
echo "<div style=\"text-align:center;\" class=\"alert alert-warning alert-dismissible\">
<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">×</span></button>
Er zijn geen foto's voor <b>". $petNameOld ."</b> toegevoegd!
</div>";
}
echo "</div>";
}
?>
<div style="clear:both"></div>
<div class="form-group">
<div class="col-xs-12 col-md-12">
<input id="input-700" name="kartik-input-700[]" type="file" multiple class="file-loading" data-show-upload="false" data-show-caption="true">
<span class="help-block" style="color:#31708f;margin-top:2px;font-size:12px;">U kan meerdere fotos (max 6) selecteren door op CTRL te blijeven duwen en fotos aan te duiden</span>
</div>
</div>
<div style="clear:both"></div>
<div class="form-group pull-right">
<!-- Button -->
<!-- Ako nije poslan changeID znaci da nije promjena, tako da imamo dugme za toevoegen -->
<?php
if(!$_POST["changeID"]){
?>
<div class="col-md-12">
<div id="pleaseWaitGif" style="display:none;z-index:99999999;float:left;margin:5px 3px 0 0;"><img src="img/ajax-loader-small.gif" title="Even geduld aub"></div>
<button id="btn-add-pet" type="submit" class="btn btn-info"><i class="fa fa-plus-circle"></i>   Toevoegen</button>
</div>
<?php
// Ako je poslan changeID znaci da je za update, tako da prikazujemo dugme za update //
}else{
echo "<div class=\"col-md-6 col-lg-6 col-xs-12\">
<div id=\"pleaseWaitGif\" style=\"display:none;z-index:99999999;float:left;margin:5px 3px 0 0;\"><img src=\"img/ajax-loader-small.gif\" title=\"Even geduld aub\"></div>
<button id=\"btn-add-pet\" type=\"submit\" class=\"btn btn-success\" data-title=\"Wijzig de gegevens\"><i class=\"fa fa-pencil-square-o\"></i>   Wijzigen</button>
</div>";
}
?>
</div>
</form>
<?php
if($_POST["changeID"]){
echo "<div id=\"cancelBack\" class=\"col-md-6 col-lg-6 col-xs-12\">
<button id=\"dataTitle\" class=\"btn btn-danger btn-cancel\" data-title=\"Ga terug\"><i class=\"fa fa fa-ban\"></i>   Cancel</button>
</div>";
}
?>
</div>
</div>
And the dier-toevoegen-submit.php file is :
<?php
session_start();
include("config.php");
global $kon;
ob_start();
$hiddenID = $_POST["txtHiddenID"];
if(isset($_SESSION["user"]) || isset($_COOKIE["user"])){
if($hiddenID){
$petName = addslashes(preg_replace("#[^0-9a-zA-Z ,.\'?!;:\-()\"èéíîçïàçùèûâêôëËÀÇÙÈÛÂÊÔËÄÖÜßäöüßáüÜÉëàçùèûâêôëäöüÈÉÍÎÇÏÀÇÙÈÛÂÊÔËßÄÖÜßÁÜÜÉÑñóÓœŒúÚŸÿóÓñÑòÒìÌãÃęĘąĄšč枊ĐČĆŽ]#i"," ",$_POST["name"]));
$petBreed = addslashes(preg_replace("#[^0-9a-zA-Z ,.\'?!;:\-()\"èéíîçïàçùèûâêôëËÀÇÙÈÛÂÊÔËÄÖÜßäöüßáüÜÉëàçùèûâêôëäöüÈÉÍÎÇÏÀÇÙÈÛÂÊÔËßÄÖÜßÁÜÜÉÑñóÓœŒúÚŸÿóÓñÑòÒìÌãÃęĘąĄšč枊ĐČĆŽ]#i"," ",$_POST["breed"]));
$petLostPlace = addslashes(preg_replace("#[^0-9a-zA-Z ,.\'?!;:\-()\"èéíîçïàçùèûâêôëËÀÇÙÈÛÂÊÔËÄÖÜßäöüßáüÜÉëàçùèûâêôëäöüÈÉÍÎÇÏÀÇÙÈÛÂÊÔËßÄÖÜßÁÜÜÉÑñóÓœŒúÚŸÿóÓñÑòÒìÌãÃęĘąĄšč枊ĐČĆŽ]#i"," ",$_POST["lastSeen"]));
$petColor = addslashes(preg_replace("#[^0-9a-zA-Z ,.\'?!;:\-()\"èéíîçïàçùèûâêôëËÀÇÙÈÛÂÊÔËÄÖÜßäöüßáüÜÉëàçùèûâêôëäöüÈÉÍÎÇÏÀÇÙÈÛÂÊÔËßÄÖÜßÁÜÜÉÑñóÓœŒúÚŸÿóÓñÑòÒìÌãÃęĘąĄšč枊ĐČĆŽ]#i"," ",$_POST["color"]));
$petGender = $_POST["geslacht"];
$petLostDate = $_POST["date"];
$petChangedDate = date("Y/m/d");
$petDesc = addslashes(preg_replace("#[^0-9a-zA-Z ,.\'?!;:\-()\"èéíîçïàçùèûâêôëËÀÇÙÈÛÂÊÔËÄÖÜßäöüßáüÜÉëàçùèûâêôëäöüÈÉÍÎÇÏÀÇÙÈÛÂÊÔËßÄÖÜßÁÜÜÉÑñóÓœŒúÚŸÿóÓñÑòÒìÌãÃęĘąĄšč枊ĐČĆŽ]#i"," ",$_POST["dierDescription"]));
//We get the user info from a database with a cookie or session
if(isset($_SESSION["user"])){
$session_code = $_SESSION["user"];
}else{
if(isset($_COOKIE["user"])){
$session_code = $_COOKIE["user"];
}
}
//Uzimamo korisnika koji ima trenutnu sesiju
$rezUser = mysqli_query($kon, "SELECT * FROM korisnici WHERE sessionCode = '" . $session_code . "' LIMIT 1");
$redUser = mysqli_fetch_assoc($rezUser);
$idUser = $redUser["id"];
if(mysqli_query($kon,"UPDATE pets SET
name = '". $petName ."',
breed = '". $petBreed ."',
lostPlace = '". $petLostPlace ."',
color = '". $petColor ."',
gender = '". $petGender ."',
lostDate = '". $petLostDate ."',
details = '". $petDesc ."',
changedDate = '". $petChangedDate ."'
WHERE id = ". $hiddenID .""
)
){
//Slike
$images_arr = array();
if(!empty($_FILES['kartik-input-700']['name'][0])){
foreach($_FILES['kartik-input-700']['name'] as $key=>$val){
$image_name = $_FILES['kartik-input-700']['name'][$key];
$tmp_name = $_FILES['kartik-input-700']['tmp_name'][$key];
$size = $_FILES['kartik-input-700']['size'][$key];
$type = $_FILES['kartik-input-700']['type'][$key];
$error = $_FILES['kartik-input-700']['error'][$key];
//Ovdje uzimamo id od zadnje zivotinje koju je dodao user cija je sesija ili cookie aktivan
$rezPet = mysqli_query($kon, "SELECT * FROM pets WHERE user_id = ". $idUser ." ORDER BY id DESC LIMIT 1");
$redPet = mysqli_fetch_assoc($rezPet);
$petId = $redPet["id"];
if(!file_exists("images/uploads/pets/". $petId ."/")){
mkdir("images/uploads/pets/". $petId ."/",0777);
}
$target_dir = "images/uploads/pets/". $petId ."/";
$target_file = $target_dir.$_FILES['kartik-input-700']['name'][$key];
if(move_uploaded_file($_FILES['kartik-input-700']['tmp_name'][$key],$target_file)){
$images_arr[] = $target_file;
mysqli_query($kon, "INSERT INTO petsfotos VALUES (NULL, '". $type ."','". $image_name ."',". $petId .")");
require_once 'ThumbLib.inc.php';
$thumb = PhpThumbFactory::create("images/uploads/pets/". $petId ."/". $image_name ."");
$thumb->resize(800, 0);
$thumb->save("images/uploads/pets/". $petId ."/thumbbig_". $image_name . "");
$thumb->resize(220, 0);
$thumb->save("images/uploads/pets/". $petId ."/thumb_". $image_name . "");
$thumb->resize(140, 0);
$thumb->save("images/uploads/pets/". $petId ."/thumbsmall_". $image_name . "");
}else{
$noPhotosAdded = "No photos added";
}
}
}
if (empty($images_arr)) {
$noPhotosSelected = "No photos selected";
}
echo json_encode(array(
'result' => "<span style=\"font-size:16px;font_weight:bold;\"><i class=\"fa fa-thumbs-o-up\"></i>Uw huisdier is succesvol gewijzigd.</span><br/><br/> Wij hopen dat <b>". $petName ."</b> zo snel mogelijk terug naar huis zal komen!",
'status' => "Updated",
'noPhotosAdded' => $noPhotosAdded,
'noPhotosSelected' => $noPhotosSelected
));
}else{
echo json_encode(array(
'result' => "Uw huisdier is niet gewijzigd.",
'status' => "NotUpdated"
));
}
}else{
$petName = addslashes(preg_replace("#[^0-9a-zA-Z ,.\'?!;:\-()\"èéíîçïàçùèûâêôëËÀÇÙÈÛÂÊÔËÄÖÜßäöüßáüÜÉëàçùèûâêôëäöüÈÉÍÎÇÏÀÇÙÈÛÂÊÔËßÄÖÜßÁÜÜÉÑñóÓœŒúÚŸÿóÓñÑòÒìÌãÃęĘąĄšč枊ĐČĆŽ]#i"," ",$_POST["name"]));
$petBreed = addslashes(preg_replace("#[^0-9a-zA-Z ,.\'?!;:\-()\"èéíîçïàçùèûâêôëËÀÇÙÈÛÂÊÔËÄÖÜßäöüßáüÜÉëàçùèûâêôëäöüÈÉÍÎÇÏÀÇÙÈÛÂÊÔËßÄÖÜßÁÜÜÉÑñóÓœŒúÚŸÿóÓñÑòÒìÌãÃęĘąĄšč枊ĐČĆŽ]#i"," ",$_POST["breed"]));
$petLostPlace = addslashes(preg_replace("#[^0-9a-zA-Z ,.\'?!;:\-()\"èéíîçïàçùèûâêôëËÀÇÙÈÛÂÊÔËÄÖÜßäöüßáüÜÉëàçùèûâêôëäöüÈÉÍÎÇÏÀÇÙÈÛÂÊÔËßÄÖÜßÁÜÜÉÑñóÓœŒúÚŸÿóÓñÑòÒìÌãÃęĘąĄšč枊ĐČĆŽ]#i"," ",$_POST["lastSeen"]));
$petColor = addslashes(preg_replace("#[^0-9a-zA-Z ,.\'?!;:\-()\"èéíîçïàçùèûâêôëËÀÇÙÈÛÂÊÔËÄÖÜßäöüßáüÜÉëàçùèûâêôëäöüÈÉÍÎÇÏÀÇÙÈÛÂÊÔËßÄÖÜßÁÜÜÉÑñóÓœŒúÚŸÿóÓñÑòÒìÌãÃęĘąĄšč枊ĐČĆŽ]#i"," ",$_POST["color"]));
$petGender = $_POST["geslacht"];
$petLostDate = $_POST["date"];
$petFoundDate = NULL;
$petChangedDate = NULL;
$petDesc = addslashes(preg_replace("#[^0-9a-zA-Z ,.\'?!;:\-()\"èéíîçïàçùèûâêôëËÀÇÙÈÛÂÊÔËÄÖÜßäöüßáüÜÉëàçùèûâêôëäöüÈÉÍÎÇÏÀÇÙÈÛÂÊÔËßÄÖÜßÁÜÜÉÑñóÓœŒúÚŸÿóÓñÑòÒìÌãÃęĘąĄšč枊ĐČĆŽ]#i"," ",$_POST["dierDescription"]));
$found = 0;
$addedDate = date("Y/m/d");
$views = 0;
$paid = 0;
//We get the user info from a database with a cookie or session
if(isset($_SESSION["user"])){
$session_code = $_SESSION["user"];
}else{
if(isset($_COOKIE["user"])){
$session_code = $_COOKIE["user"];
}
}
//Uzimamo korisnika koji ima trenutnu sesiju
$rezUser = mysqli_query($kon, "SELECT * FROM korisnici WHERE sessionCode = '" . $session_code . "' LIMIT 1");
$redUser = mysqli_fetch_assoc($rezUser);
$idUser = $redUser["id"];
if(mysqli_query($kon,"INSERT INTO pets VALUES (
NULL,
'". $petName ."',
'". $petBreed ."',
'". $petLostPlace ."',
'". $petColor ."',
'". $petGender ."',
'". $petLostDate ."',
'". $petFoundDate ."',
'". $petDesc ."',
". $found .",
'". $addedDate ."',
'". $petChangedDate ."',
". $idUser .",
". $views .",
". $paid .")"
))
{
//Slike
$images_arr = array();
if(!empty($_FILES['kartik-input-700']['name'][0])){
foreach($_FILES['kartik-input-700']['name'] as $key=>$val){
$image_name = $_FILES['kartik-input-700']['name'][$key];
$tmp_name = $_FILES['kartik-input-700']['tmp_name'][$key];
$size = $_FILES['kartik-input-700']['size'][$key];
$type = $_FILES['kartik-input-700']['type'][$key];
$error = $_FILES['kartik-input-700']['error'][$key];
//Ovdje uzimamo id od zadnje zivotinje koju je dodao user cija je sesija ili cookie aktivan
$rezPet = mysqli_query($kon, "SELECT * FROM pets WHERE user_id = ". $idUser ." ORDER BY id DESC LIMIT 1");
$redPet = mysqli_fetch_assoc($rezPet);
$petId = $redPet["id"];
if(!file_exists("images/uploads/pets/". $petId ."/")){
mkdir("images/uploads/pets/". $petId ."/",0777);
}
$target_dir = "images/uploads/pets/". $petId ."/";
$target_file = $target_dir.$_FILES['kartik-input-700']['name'][$key];
if(move_uploaded_file($_FILES['kartik-input-700']['tmp_name'][$key],$target_file)){
$images_arr[] = $target_file;
mysqli_query($kon, "INSERT INTO petsfotos VALUES (NULL, '". $type ."','". $image_name ."',". $petId .")");
require_once 'ThumbLib.inc.php';
$thumb = PhpThumbFactory::create("images/uploads/pets/". $petId ."/". $image_name ."");
$thumb->resize(800, 0);
$thumb->save("images/uploads/pets/". $petId ."/thumbbig_". $image_name . "");
$thumb->resize(220, 0);
$thumb->save("images/uploads/pets/". $petId ."/thumb_". $image_name . "");
$thumb->resize(140, 0);
$thumb->save("images/uploads/pets/". $petId ."/thumbsmall_". $image_name . "");
}else{
$noPhotosAdded = "No photos added";
}
}
}
if (empty($images_arr)) {
$noPhotosSelected = "No photos selected";
}
$rezPets = mysqli_query($kon, "SELECT * FROM pets");
$nrPets = mysqli_num_rows($rezPets);
echo json_encode(array(
'result' => "<span style=\"font-size:16px;font_weight:bold;\"><i class=\"fa fa-thumbs-o-up\"></i>Uw huisdier is toegevoegd.</span><br/><br/> Wij hopen dat <b>". $petName ."</b> zo snel mogelijk terug naar huis zal komen!",
'status' => "Added",
'noPhotosAdded' => $noPhotosAdded,
'noPhotosSelected' => $noPhotosSelected,
'nrPets' => $nrPets
));
}else{
echo json_encode(array(
'result' => "Uw huisdier is niet toegevoegd.",
'status' => "NotAdded"
));
}
}
}else{
header("Location:index.php");
}
ob_flush();
?>
Any ideas? Thanks.
I'm currently working on a super simple Online shop idea with a shopping cart. At the end i want to print out a table with the products you ordered. Currently using a foreach but i have no idea how to solve this. I tried to use sessions as a way to give the loop an idea how many different products are ordered. But it seems like the $_SESSION way will take all the current active sessions. And using a simple variable f.e. $piano will make it print 2 rows ( using 2 piano's in my shop, tried to solve it with a if (session active) $piano1 = active. But it seems the foreach statement doesn't give a whoop about that and will print 2 rows anyways.
Sorry for the long block of text. Here's my page. Again apologies. I just started php.
Variable names are dutch but that shouldn't really matter for you guys i think.
Starting from line 103.
Thanks in advance!
<div class="logincontainer"><!-- Php Session Script Actief? -->
<?php
session_start();
if(isset($_SESSION['naam'])) :
echo "<div class='content_login'>";
echo "Hallo " . $_SESSION['naam'] . ". Welkom bij de Pianoshop.</br></br>";?>
<form method='post' action='uitlog.php'>
<input type='submit' name='loguit' Value='Loguit!'></form><br />
<form action='winkelmand.php' class="left">
<input type='image' src='images/winkelwagen-knop.png'/>
</form><br />
<form method='post' name='emptycart' action='emptycart.php' class="right">
<input type="submit" id="submitpic" name="leegwinkelmand" value="">
<?php
if(isset($_SESSION['winkelmand'])) {
echo $_SESSION['aantalproducten'] . " Item(s) - €" . $_SESSION['totaalprijs'] . ",-";
} else {
echo "Jouw winkelwagen is leeg.";
}?>
</form>
</div>
<?php else :?>
<div class='content_login'>
<form method='post' action='checklogin.php'>
<p><input type='text' name='gebruikersnaam' required='required' value='' placeholder='Gebruikersnaam'></p>
<p><input type='password' name='password' required='required' value='' placeholder='Wachtwoord'></p>
<font color="red"><p class='submit'>
<input type='submit' name='login' value='Login'>
<?php if(isset($_SESSION['logged_in'])) :?>
Verkeerd wachtwoord.
<?php session_destroy();
endif; ?>
</p></font>
<p>Nog niet geregistreerd? Doe dat hier!.</p>
</form>
</div>
<?php endif; ?></div>
<div id="site">
<div id="menubar">
<div id="logo">
<img src="images/pianotoetsen.png" >
</div>
<div id="menu_items">
<ul id="menu">
<li>Home</li>
<li>Toetsinstrumenten</li>
<li>Jouw account</li>
<li class="current">Winkelmand</li>
<li>Contact</li>
</ul>
</div></div>
<div id="site_content">
<div class="sidebar_container">
<div class="sidebar">
<h2>Sale!</h2>
<div id="thumbnail"><img src="images/piano1.jpg"></div>
<p>Yamaha CLP-575 voor maar €2599,- !</p>
<div id="thumbnail"><img src="images/piano2.jpg"></div>
<p>Ritmuller 120SL €4999,- !</p>
</div>
<div class="sidebar">
<h2>Laatste Updates</h2>
<h3>Juni 2015</h3>
<p>Site in constructie.</p>
</div>
<div class="sidebar">
<h3>Wij zijn op Facebook</h3>
<p>Klik hier.</p>
</div>
</div>
<div id="content">
<div id="wallpaperbanner">
<img src="images/banner.jpg">
</div>
<div class="content_item">
<h1>Winkelmand</h1>
<?php
$user = 'root';
$pass = '';
$db = 'online shop';
$conn = mysql_connect('localhost', $user, $pass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
if(isset($_SESSION['winkelmand'])) {
echo "Deze producten staan in je winkelwagen</br></br>";
if(isset($_SESSION['totaalprijs2']) == 0) {
// Do nothing?
} else {
mysql_select_db($db);
$query = mysql_query("SELECT * FROM product WHERE productnummer='2'");
$productgegevens = mysql_fetch_row($query);
$piano["piano2"] = "ritmuller";
$pianoarray[1] = $productgegevens['1'];
$pianoarray[2] = $productgegevens['2'];
$pianoarray[3] = $productgegevens['4'];
$pianoarray[5] = $productgegevens['3'];
$pianoarray[4] = $_SESSION['aantal_prod2'];
}
if(isset($_SESSION['totaalprijs1']))
{
mysql_select_db($db);
$query = mysql_query("SELECT * FROM product WHERE productnummer='1'");
$productgegevens = mysql_fetch_row($query);
$piano["piano1"] = "yamaha";
$pianoarray[4] = $_SESSION['aantal_prod1'];
$pianoarray[1] = $productgegevens['1'];
$pianoarray[2] = $productgegevens['2'];
$pianoarray[3] = $productgegevens['4'];
$pianoarray[5] = $productgegevens['3'];
$pianoarray[4] = $_SESSION['aantal_prod2'];
}
echo "<br />
<table width='80%' >
<thead>
<tr><th>Productnaam</th><th>Merk</th>
<th>Voorraad</th><th>Aantal</th><th>Prijs</th>
</tr>
</thead>
<tbody>";
foreach($piano as $key => $value) {
echo $key . "</br>" . $value . "<br />";
$row = "<tr>";
for ($x=1; $x<=sizeof($pianoarray); $x++){
$row = $row . "<td>" . $pianoarray[$x] . "</td>";
}
$row = $row . "</tr>";
echo $row;
}
echo "<tr><td></td><td></td><td></td><td></td><td>" . '€' . $_SESSION['totaalprijs'] . ',-' . "</td></tr></tbody></table>";
}
else {
echo "Jouw winkelwagen is leeg. <br />" . "Klik <a href='toetsinstrumenten.php'>Hier</a> om wat items toe te voegen.";
}?>
</div>
</div>
</div>
</div>
Create an array variable in the $_SESSION array and do a foreach loop on that
$_SESSION['cart']['piano1'] = 'piano1';
$_SESSION['cart']['piano2'] = 'piano2';
$cart = $_SESSION['cart'];
foreach ($cart as $key => $item) {
//do something with $item or $key
}
I'm making a shop as a work for school and I have to add into a database the selections of the customer.
The insert is ok, however, in the CommandeTotal column, the prize is only the one of the last item I choose (I choose 2 or more products who have different prize), here's my code to understand my problem:
The instruction for add into the table Commandes is ok.
The problem is when it's time to do the insert instruction for add into the table commandeDetails, the products are all inserted, but the prize for all the products in the table after the insert instruction is from the last product.
<?php
if (empty($_SESSION["achats"]))
echo "Votre panier est Vide!";
else {
//afficher les éléments du panier
$mysqli = new mysqli("localhost", "root", "", "magasin");
mysqli_set_charset($mysqli, "utf8");
if (isset($_POST["PasserCommande"])) {
//0) Pogner le ID du user logué
if(isset($_SESSION["nom"]))
{
$queryUser = "SELECT MAX(UserID) AS No FROM Users WHERE UserName = '".$_SESSION["nom"]."'";
$resultUser = $mysqli->query("$queryUser");
$UserID = $resultUser->fetch_assoc()["No"];
//1) Ajouter une commande(enlever CommandeID dans la requête)
$queryOrder = "INSERT INTO commandes(UserID, CommandeDate) VALUES('".$UserID."', CURRENT_TIMESTAMP())";
$mysqli->query($queryOrder);
//2) Pogner le ID de la commande
$queryOrderID = "SELECT MAX(CommandeID) AS id FROM commandes";
$result = $mysqli->query($queryOrderID);
$orderID = $result->fetch_assoc()["id"];
echo"<h3>Résultat de votre commande : </h3>";
echo "Commande # " . $orderID . " enregistrée.";
//3) Ajouter des détails
while ($element = each($_SESSION["achats"])) {
if(isset($_SESSION["prix"]))
{
$queryOrderDetail = "INSERT INTO detailcommande(CommandeID, ProduitID, CommandeTotal, CommandeDate) VALUES('".$orderID."','".$element["key"]."', '".$_SESSION["prix"]."', CURRENT_TIMESTAMP())";
$mysqli->query($queryOrderDetail);
echo $queryOrderDetail;
}
}
unset($_SESSION["achats"]);
}
}
if (isset($_SESSION["achats"])) {
$total = 0;
echo"<h3>Vos achats de la journée : </h3>";
while ($element = each($_SESSION["achats"])) {
$query = "SELECT * FROM produits WHERE ProduitID = '" . $element["key"] . "'";
$result = $mysqli->query($query);
$ligne = $result->fetch_assoc();
echo"<div class='col-sm-4 col-lg-4 col-md-4'>
<div class='thumbnail'>
<div class='caption'>";
echo"<img src='IMAGES/max/$ligne[ProduitLien]' width='100' height='50' />
<h4 class='pull-right'>$ligne[ProduitPrix]$</h4>
<h5><a href='#'>$ligne[ProduitNom]</a></h5>
<h6>Qté : $element[value]</h6>
</div>
<div class='ratings'>
<p>
<span class='glyphicon glyphicon-star'></span>
<span class='glyphicon glyphicon-star'></span>
<span class='glyphicon glyphicon-star'></span>
<span class='glyphicon glyphicon-star'></span>
<span class='glyphicon glyphicon-star'></span>
</p>
</div>
</div>
</div>";
$total += $element["value"] * $ligne["ProduitPrix"];
$_SESSION["prix"] = $ligne["ProduitPrix"];
}
echo "<div>total : <strong>" . $total . "$</strong></div>";
echo "<div>total après taxes <strong>: " . round($total * 1.15,2) . "$</strong></div>";
}
$mysqli->close();
}
?>
<form method="POST" action="#">
<input type="submit" name="PasserCommande" value="Commandez maintenant" />
</form>
Based on the information you provided, I can only think of the following :
$_SESSION["achats"] is a array and isset($_SESSION["prix"]) is NOT(or having only 1 value)
For example, you have:
$_SESSION["achats"] = array( '1' => '1', '2' => '2');
$_SESSION["prix"] = "65"
Please provide more code, perhaps your input if this is not what you after.
I've sold the problem, I added this and it's working :
while ($element = each($_SESSION["achats"])) {
$queryTest = "SELECT ProduitPrix FROM produits WHERE ProduitID = ". $element["key"];
$res = $mysqli->query($queryTest);
while($prixCommandes = $res->fetch_assoc())
{
$queryOrderDetail = "INSERT INTO detailcommande(CommandeID, ProduitID, CommandeTotal, CommandeDate) VALUES('".$orderID."','".$element["key"]."', '".$prixCommandes["ProduitPrix"]."', CURRENT_TIMESTAMP())";
$mysqli->query($queryOrderDetail);
}
}
Thank you for trying to help me