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.
Related
I am doing a pagination system and when I do the 'for' the file does not fetch any variable on require_once 'carregarOpinioes.php'.
In line 33 (
carregarOpinioes.php
<?php
require_once('../../../database/config.php');
include '../geral.php';
apenasAdmin();
function connectToDatabase()
{
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DATABASE);
if ($conn->connect_errno) {
$code = $conn->connect_errno;
$message = $conn->connect_error;
printf("<p>Connection error: %d %s</p>", $code, $message);
return false;
}
return $conn;
}
//Conexão à BD
if (!($conn = connectToDatabase())) {
exit();
}
// Se a página já tiver definida ela vai buscar o valor do $_GET['pagina'] se não tiver ela fica com o valor 1, o ? serve para verificar se o boolean é true ou false.
$pagina = (isset($_GET['pagina'])) ? $_GET['pagina'] : 1;
//Selecionar todas as opiniões onde o comentário não está vazio
$sqlOpinioesGeral = "SELECT * FROM opiniao WHERE comentario = ''";
$result = mysqli_query($conn, $sqlOpinioesGeral);
//Variavel para saber a quantidade total de opiniões existentes na tabela
$totalOpinioes = mysqli_num_rows($result);
//Quantidade de opiniões por página
$opPorPagina = 5;
//Calcular o número de páginas totais
$numPaginas = ceil($totalOpinioes/$opPorPagina);
//Calcular o numero da linha da tabela que dá inicio a cada página
$inicio = ($opPorPagina * $pagina) - $opPorPagina;
$query = "SELECT
u.Nome,
o.id_opiniao,
o.qtd_estrelas,
o.comentario,
o.data,
o.aprovacao
FROM
opiniao o
JOIN utilizador u ON
(o.id_user = u.id_user)
WHERE
o.comentario != ''
LIMIT $inicio, $opPorPagina";
$resultDois = mysqli_query($conn, $query);
$totalOpinioes = mysqli_num_rows($resultDois);
opinioesAdmin.php
.
.
.
<?php
require_once 'carregarOpinioes.php';
?>
<div class="container-fluid ">
<div class="row">
<div class="col-12 page">
<table class="table table-dark">
<thead>
<tr>
<th>ID</th>
<th>Data</th>
<th>Nome</th>
<th>Avaliação 1-5</th>
<th>Comentário</th>
<th>Gerir</th>
</tr>
</thead>
<tbody>
<?php while ($dadosOpiniao = mysqli_fetch_object($resultDois)) {
echo "
<tr>
<th scope=\"row\">#" . $dadosOpiniao->id_opiniao . "</th>
<td>" . $dadosOpiniao->data . "</td>
<td>" . utf8_encode($dadosOpiniao->Nome) . "</td>
<td>" . $dadosOpiniao->qtd_estrelas . "</td>
<td><button type=\"button\" class=\"btn botao botaoComentario\" data-toggle=\"modal\" data-target=\"#modal" . $dadosOpiniao->id_opiniao . "\"><i class=\"far fa-eye\"></i></button>
<div class=\"modal fade\" id=\"modal" . $dadosOpiniao->id_opiniao . "\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"exampleModalLabel\" aria-hidden=\"true\">
<div class=\"modal-dialog\" role=\"document\">
<div class=\"modal-content\">
<div class=\"modal-header\">
<h5 class=\"modal-title\" id=\"exampleModalLabel\">Opinião de " . utf8_encode($dadosOpiniao->Nome) . "</h5>
<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Fechar\">
<span aria-hidden='true'>×</span>
</button>
</div>
<div class=\"modal-body\">
<p>«" . utf8_encode(utf8_decode($dadosOpiniao->comentario)) . "»</p>
</div>
<div class=\"modal-footer\">
<button type=\"button\" class=\"btn btn-secondary\" data-dismiss=\"modal\">Fechar</button>
</div>
</div>
</div>
</div>
</td>
<td>
<div class=\"formsJuntos\">
<form><button type=\"submit\" class=\"btn botao botaoAprovar\"><i class=\"fas fa-check\"></i></button></form>
<form><button type=\"submit\" class=\"btn botao botaoApagar\"><i class=\"fa fa-trash\"></i></button></form>
</div>
</td>
</tr> ";
}
?>
</tbody>
</table>
<ul class="pagination justify-content-center">
<li class="page-item disabled">
<a class="page-link" href="#" tabindex="-1" aria-disabled="true">Previous</a>
</li>
<?php
for ($i = 1; $i < $numPaginas + 1; $i++) {
echo '<li class="page-item"><a class="page-link" href="opinioesAdmin.php?pagina=<?' . $i . '">'. $i .'</a></li>';
}
?>
<li class="page-item">
<a class="page-link" href="#">Next</a>
</li>
</ul>
</div>
</div>
</div>
.
.
.
Currently the output is 1
But it should be 2
because $resultDois has 8 rows!
I am hoping this community can help me.
Sry, my bad. That's a operator mistake on $sqlOpinioesGeral = "SELECT * FROM opiniao WHERE comentario = ''"; I wanted !=
I am trying to get my div card to stay right next to my other card board and also dont get strached out. The first one works perfectly, but I dont know how to place the next one right next to the first one...
$sql = "SELECT * FROM beitrag WHERE beitrag_id=97 OR beitrag_id=98";
$res = mysqli_query($db, $sql) or die(mysqli_error());
if(mysqli_num_rows($res) > 0) {
$beitrag = "
<div class='pagecontainer'>
<div class='container'>
<div class='jumbotron p- p-md-5 text-white rounded bg-dark'>
<div class='col-md-6 px-0'>
<h1 class='display-4 font-italic'>Student, Azubi, FSJler, Schüler...?</h1>
<p class='lead my-3'>Tauschen Sie sich noch heute mit tausenden Gleichgesinnten über Ihre finanzielle Planung aus!</p>
<p class='lead mb-0'><a href='beitraege.php' class='text-white font-weight-bold'>Ab zu den Beitraegen!</a></p>
</div>
</div>
<div class='row mb-2'>";
while ($row = mysqli_fetch_assoc($res)) {
$beitrag_id = $row['beitrag_id'];
$titel = $row['titel'];
$miete = $row['miete'];
$einkauf = $row['einkauf'];
$freizeit = $row['freizeit'];
$sonstiges = $row['sonstiges'];
$g_kosten = $row['g_kosten'];
$p_text = $row['p_text'];
$beitrag .="
<div class='col-md-6'>
<div class='card' style=''>
<div class='card-body'>
<h4 class='card-title'>$titel</h4>
<p class='card-text'>$p_text</p>
<a href='siehe_beitrag.php?pid=$beitrag_id' class='btn btn-primary'>Mehr erfahren</a>
</div>
</div>
";
$beitrag .="
</div>
</div>
</div>
</div>
";
}
echo $beitrag;
}
Try with this code istead of yours.
$sql = "SELECT * FROM beitrag WHERE beitrag_id=97 OR beitrag_id=98";
$res = mysqli_query($db, $sql) or die(mysqli_error());
if(mysqli_num_rows($res) > 0) {
$beitrag = "
<div class='pagecontainer'>
<div class='container'>
<div class='jumbotron p- p-md-5 text-white rounded bg-dark'>
<div class='col-md-6 px-0'>
<h1 class='display-4 font-italic'>Student, Azubi, FSJler, Schüler...?</h1>
<p class='lead my-3'>Tauschen Sie sich noch heute mit tausenden Gleichgesinnten über Ihre finanzielle Planung aus!</p>
<p class='lead mb-0'><a href='beitraege.php' class='text-white font-weight-bold'>Ab zu den Beitraegen!</a></p>
</div>
</div>
<div class='row mb-2'>";
while ($row = mysqli_fetch_assoc($res)) {
$beitrag_id = $row['beitrag_id'];
$titel = $row['titel'];
$miete = $row['miete'];
$einkauf = $row['einkauf'];
$freizeit = $row['freizeit'];
$sonstiges = $row['sonstiges'];
$g_kosten = $row['g_kosten'];
$p_text = $row['p_text'];
$beitrag .="
<div class='col-md-6'>
<div class='card' style=''>
<div class='card-body'>
<h4 class='card-title'>$titel</h4>
<p class='card-text'>$p_text</p>
<a href='siehe_beitrag.php?pid=$beitrag_id' class='btn btn-primary'>Mehr erfahren</a>
</div>
</div>
</div>
";
//you fault here. You should have the loop on this card only.
}
//you fault here. one </div> goes down bottom.
$beitrag .="
</div>
</div>
</div>
";
echo $beitrag;
}
hi i need help i have problem in my code and i can't figure the solutions please help me .
this is the dashboard:
image dashboard
and this is problem after click on delete:
delete problem
and this is my code php of posts file:
<?php
/*
===========================================================
=== Manage Members Page ===
=== You can add | edit | delete Members from here ===
===========================================================
*/
session_start();
if (isset($_SESSION['Username'])) {
include 'init.php';
$pageTitle = 'Posts';
$do = isset($_GET['do']) ? $_GET['do'] : 'Manage' ;
//Start Manage Page
if ($do == 'Manage'){ // Manage Members Page
$sort = 'ASC';
$sort_arry = array('ASC', 'DESC');
if(isset($_GET['sort']) && in_array($_GET['sort'], $sort_arry)) {
$sort = $_GET['sort'];
}
$stmt2 = $con->prepare("SELECT * FROM posts ORDER BY Ordering $sort");
$stmt2->execute();
$rows = $stmt2->fetchAll();
?>
<h1 class="text-center"> Manage Posts </h1>
<div class="container categories">
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-edit"></i> Manage Posts
<div class="ordering pull-right">
<i class="fa fa-sort"> </i>Ordering: [
<a class="<?php if ($sort == 'ASC') { echo 'active'; } ?>" href="?sort=ASC">Asc </a> |
<a class="<?php if ($sort == 'DESC') { echo 'active'; } ?>" href="?sort=DESC">Desc </a>
]
</div>
</div>
<div class="row">
<?php
foreach ($rows as $image) {
echo '<div class="col-md-3 col-sm-4 "><div class="thumbnail">';
echo '<h2 class="h4">'.$image['Name']. '</h2><div class="main">';
echo '<img src="data:image;base64,'.$image['Image'].' " alt="image name" title="image title" width="255" heigth="255">';
echo '</div>';
echo '<table class="table table-bordered">';
echo '<tr>';
echo '<td>' . "<a href='posts.php?do=Edit&id=". $image['ID'] ."' class='btn btn-xs btn-primary'><i class='fa fa-edit'></i> edit</a>" . '</td>';
echo '<td>' . "<a href='posts.php?do=Delete&id=". $image['ID'] ."' class='btn btn-xs btn-danger'><i class='fa fa-close'></i> Delete</a>" . '</td>';
echo '</tr>';
echo '</table>';
echo '</div>';
echo '</div>';
}
?>
</div>
<?php } elseif ($do == 'Add') { //add Member page ?>
<h1 class="text-center"> ajouter un nouveau post </h1>
<div class="container">
<form class="form-horizontal" enctype="multipart/form-data" action="?do=Insert" method="POST">
<!-- start Username fieled -->
<div class="form-group">
<label class="col-sm-2 control-label">Titre</label>
<div class="col-sm-10 col-md-8">
<input type="text" name="image-name" class="form-control" autocomplete="off" placeholder="username pour se connecter dans le site Web" required />
</div>
</div>
<!-- end Username fieled -->
<!-- start Password fieled -->
<div class="form-group">
<label class="col-sm-2 control-label">Image</label>
<div class="col-sm-10 col-md-8">
<input type="file" name="image" class="form-control" placeholder="mot de passe doit être difficile et complexe" required/>
</div>
</div>
<!-- end Password fieled -->
<!-- start Full name fieled -->
<div class="form-group">
<label class="col-sm-2" for="categorie">Categories:</label>
<div class="col-sm-10 col-md-8">
<select class="form-control" name="categorie">
<?php
$stmt = $con->prepare("SELECT * FROM `categories`");
// Execute the Statments
$stmt->execute();
// Assign to variable
$rows = $stmt->fetchAll();
?>
<?php
foreach ($rows as $cat) {
echo "<option value='" . $cat['ID'] . "'>". $cat['Name'] . "</option>";
}
?>
</select>
</div>
</div>
<!-- end Full name fieled -->
<!-- start submit fieled -->
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" value="Ajouter" class="btn btn-primary" />
</div>
</div>
<!-- end submit fieled -->
</form>
</div>
<?php
} elseif ($do == 'Insert') {
//insert Members Page
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo "<h1 class='text-center'> insert an post </h1>";
echo "<div class='container'>";
// Get variable from the form
$name = $_POST['image-name'];
$image= addslashes($_FILES['image']['tmp_name']);
$image= file_get_contents($image);
$image= base64_encode($image);
$cat = $_POST['categorie'];
//validate the form
$formErrors = array();
if (strlen($name) < 4) {
$formErrors[] = "title name cant be less then <strong> 4 caracter</strong>";
}
if (strlen($name) > 20) {
$formErrors[] = "title name cant be More then <strong> 20 caracter</strong>";
}
if (empty($name)) {
$formErrors[] = "Username Cant Be <strong>Empty</strong>";
}
// loop into eroos array and echo it
foreach ($formErrors as $Error) {
echo "<div class='alert alert-danger'>" . $Error . "</div>";
}
// check if There is no error procced the operations
if (empty($formErrors)) {
// check if user exist in database
$check = checkItem("Username", "users", $user);
if ($check == 1) {
$theMsg = "<div class='alert alert-danger'> Sorry this user is exist </div>";
redirectHome($theMsg, 'back');
} else {
// Insert User info into database
$stmt = $con->prepare("INSERT INTO posts(Name, Image, Cat_id)
VALUES (:name, :image, :cat)");
$stmt->execute(array(
'name' => $name,
'image' => $image,
'cat' => $cat,
));
// echo success message
$theMsg = "<div class='alert alert-success'>" . $stmt->rowCount() . ' Record Inserted </div> ';
redirectHome($theMsg, 'back', 5);
}
}
} else {
echo "<div class='container'>";
$theMsg = '<div class="alert alert-danger"> Sorry you cant browse this page directely </div>';
redirectHome($theMsg, 'back', 5); // 6 is secend of redirect to page in function
echo "</div>";
}
echo "</div>";
} elseif ($do == 'Edit') { // Edit Page
//check if GET request userid Is numeric & Get The integer value of it
$post = isset($_GET['id']) && is_numeric($_GET['id']) ? intval($_GET['id']) : 0;
//sellect All Data Depend On This ID
$stmt = $con->prepare("SELECT * FROM posts WHERE ID = ? LIMIT 1");
// execute Query
$stmt->execute(array($post));
//fetch the Data
$row = $stmt->fetch();
// The row count
$count = $stmt->rowCount();
// If Ther's Such Id show The Form
if ($count > 0) { ?>
<h1 class="text-center"> Modifier Post </h1>
<div class="container">
<form class="form-horizontal" enctype="multipart/form-data" action="?do=Update" method="POST">
<div class="col-md-6 col-md-offset-3 panel">
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>
<!-- start title fieled -->
<div class="form-group">
<label class="col-sm-2 control-label">Titre</label>
<div class="col-sm-10 col-md-8">
<input type="text" name="name" class="form-control" autocomplete="off" required value="<?php echo $row['Name']; ?>" >
</div>
</div>
<!-- end title field -->
<!-- start image filed -->
<div class="form-group">
<label class="col-sm-2 control-label">image</label>
<div class="col-sm-10 col-md-8">
<input type="file" name="image" class="form-control" />
</div>
</div>
<!-- end image filed -->
<!-- start Categories filed -->
<div class="form-group">
<label class="col-sm-2" for="categorie">Categories:</label>
<div class="col-sm-10 col-md-8">
<select class="form-control" name="categorie">
<?php
$stmt = $con->prepare("SELECT * FROM `categories`");
// Execute the Statments
$stmt->execute();
// Assign to variable
$rows = $stmt->fetchAll();
?>
<?php
foreach ($rows as $cat) {
echo "<option value='" . $cat['ID'] . "'>". $cat['Name'] . "</option>";
}
?>
</select>
</div>
</div>
<!-- Categories end-->
<!-- start submit fieled -->
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" value="sauvegarder" class="btn btn-primary" />
</div>
</div>
<!-- end submit fieled -->
</div>
</form>
</div>
<?php
// if there's No Such id Show Error Message
} else {
echo "<div class='container'>";
$theMsg = "<div class='alert alert-danger'>Theres is no such Id</div>";
redirectHome($theMsg);
echo "</div>";
}
} elseif ($do == 'Update') {
echo "<h1 class='text-center'> mis a jour Membre </h1>";
echo "<div class='container'>";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Get variable from the form
$id = $_POST['id'];
$name = $_POST['name'];
$image = addslashes($_FILES['image']['tmp_name']);
$image = file_get_contents($image);
$image = base64_encode($image);
$cat = $_POST['categorie'];
//validate the form
$formErrors = array();
if (empty($name)) {
$formErrors[] = "<div class='alert alert-danger'>Username Cant Be <strong>Empty</strong> </div>";
}
if (empty($image)) {
$formErrors[] = "<div class='alert alert-danger'>FullName Cant Be <strong>Empty</strong></div>";
}
if (empty($cat)) {
$formErrors[] = "<div class='alert alert-danger'>Email Cant Be <strong>Empty</strong></div>";
}
// loop into eroos array and echo it
foreach ($formErrors as $Error) {
echo $Error;
}
// check if There is no error procced the operations
if (empty($formErrors)) {
// Update The Database With This Info
$stmt = $con->prepare("UPDATE posts SET Name = ? , Image = ? , Cat_id = ? WHERE ID = ?");
$stmt->execute(array($name, $image, $cat, $id));
// echo success message
$theMsg = "<div class='alert alert-success'>" . $stmt->rowCount() . ' Record Updated </div> ';
redirectHome($theMsg, 'back');
}
} else {
$theMsg = '<div class="alert alert-danger">Sorry you cant browse this page directely </div>';
redirectHome($theMsg);
}
echo "</div>";
}
elseif ($do == 'Delete') { // Delete Member Page
echo "<h1 class='text-center'> Delete Membre </h1>";
echo "<div class='container'>";
//check if GET request userid Is numeric & Get The integer value of it
$id = isset($_GET['id']) && is_numeric($_GET['id']) ? intval($_GET['id']) : 0;
//sellect All Data Depend On This ID
$check = checkItem('id', 'posts', $id);
// If Ther's Such Id show The Form
if ($check > 0) {
$stmt = $con->prepare("DELETE FROM users WHERE ID = :id");
$stmt->bindParam(":id", $id);
$stmt->execute();
$theMsg = "<div class='alert alert-success'>" . $stmt->rowCount() . ' Record Deleted </div> ';
redirectHome($theMsg);
} else {
$theMsg = "<div class='alert alert-danger'>This id not exist</div>";
redirectHome($theMsg);
}
echo "</div>";
}
include $tpl . 'footer.php';
} else {
header('Location: index.php') ;
exit();
}
from the error, id is the problem.
isset($_GET['id']) && is_numeric($_GET['id'])
i think what u want is
(isset($_GET['id']) && is_numeric($_GET['id']) )//close parantheses in wrong position
Well i'm trying to make a website as you can see, and i'm having difficulty with the "LOAD MORE" button, what i in-vision is that whenever someone clicks this button it would go through preferably a php code that tells the database to load in 5 more posts.
show_posts.php
<?php
$query = $con->query("SELECT * FROM `posts` ORDER BY `id` DESC LIMIT 5");
if( isset( $_POST['load'] ) ){
//code goes here
}
while($result = mysqli_fetch_assoc($query)){
// if video is empty then echo this line
if($result["video"] == ""){
$account_assoc = $result["account_assoc"];
$result2 = mysqli_fetch_assoc($con->query("SELECT * FROM `Accounts` WHERE username='$account_assoc' OR email='$account_assoc'"));
if($result2["username"] == ""){
$identifier = $result2["firstname"];
}else{
$identifier = $result2["username"];
}
if($result2['image'] == ""){
$image = "http://jnvbaghmara.nic.in/images/staff/Blank.png";
}else{
$image = 'data:image/jpeg;base64,'.base64_encode($result2['image']);
}
if($result['dislikes'] > 1){
$dislike = "<label style='color: red;'>".format_num($result['dislikes'])."</label> Dislikes";
}else{
$dislike = "<label style='color: red;'>".format_num($result['dislikes'])."</label> Dislike";
}
if($result['likes'] > 1){
$like = "<label style='color: #0096f3;'>".format_num($result['likes'])."</label> likes";
}else{
$like = "<label style='color: #0096f3;'>".format_num($result['likes'])."</label> like";
}
echo '<li>
<h4><img src="'.$image.'"/> <label>'.$identifier.'</label></h4>
<div class="all-content">
<label style="color: #777;"> '.$like.' </label><label style="color: #777;"> | '.$dislike.'</label><label style="color: #777;"> | 2 comment</label>
<p>'.$result["text"].'</p>
</div></li>';
}
// if video is not empty then echo this line
elseif($result["video"] != ""){
$account_assoc = $result["account_assoc"];
$result2 = mysqli_fetch_assoc($con->query("SELECT * FROM `Accounts` WHERE username='$account_assoc' OR email='$account_assoc'"));
if($result2["username"] == ""){
$identifier = $result2["firstname"];
}else{
$identifier = $result2["username"];
}
if($result2['image'] == ""){
$image = "http://jnvbaghmara.nic.in/images/staff/Blank.png";
}else{
$image = 'data:image/jpeg;base64,'.base64_encode($result2['image']);
}
if($result['dislikes'] > 1){
$dislike = "<label style='color: red;'>".format_num($result['dislikes'])."</label> Dislikes";
}else{
$dislike = "<label style='color: red;'>".format_num($result['dislikes'])."</label> Dislike";
}
if($result['likes'] > 1){
$like = "<label style='color: #0096f3;'>".format_num($result['likes'])."</label> likes";
}else{
$like = "<label style='color: #0096f3;'>".format_num($result['likes'])."</label> like";
}
echo '<li>
<h4><img src="'.$image.'"/> <label>'.$identifier.'</label></h4>
<div class="all-content">
<iframe width="90%" height="90%" src="https://www.youtube.com/embed/'.$result["video"].'" frameborder="0" allowfullscreen></iframe>
<p>'.$result["text"].'</p>
<label style="color: #777;"> '.$like.' </label><label style="color: #777;"> | '.$dislike.'</label><label style="color: #777;"> | 2 comment</label>
</div>
</li>';
}
}
echo '<li>
<div class="all-content">
<form method="post" action="#">
<input type="submit" name="load" value="LOAD MORE..." class="load_more_button"/>
</form>
</div>
</li>';
?>
profile.php
<?php include('include/header.php'); ?>
<?php
$error = "";
if(isset($_POST['post'])){
$video = substr($_POST["video"], 17);
$text = $_POST['paragraph'];
$account_assoc = "";
if($_SESSION['username'] != ""){
$account_assoc = $_SESSION['username'];
}elseif($_SESSION['email'] != ""){
$account_assoc = $_SESSION['email'];
}
$con->query("INSERT INTO `posts` (`id`, `image`, `video`, `text`, `account_assoc`, `likes`, `dislikes`) VALUES ('', '$image', '$video', '$text', '$account_assoc', '0', '0')");
}
?>
<div class="content">
<div class="actual_content">
<div class="right-content">
<div style="padding: 10px;">
<div id="post">
<h3>Latest News</h3>
<ul class="inner-post">
<?php
$sql = $con->query("SELECT * FROM `news` ORDER BY `id` DESC LIMIT 5");
function myTruncate($string, $limit, $break=" ", $pad="..."){
if(strlen($string) <= $limit){
return $string;
}
$string = substr($string, 0, $limit);
if(false !== ($breakpoint = strrpos($string, $break))) {
$string = substr($string, 0, $breakpoint);
}
return $string . $pad;
}
while($result = mysqli_fetch_array($sql)){
$header = $result['header'];
$statement = $result['statement'];
$image = $result['image'];
$shortdesc = myTruncate($statement, 300);
echo '<li><h5><img src="#" /><label>'.$header.'</label></h5><p>'.$shortdesc.'</p></li>';
}
?>
</ul>
</div>
</div>
</div>
<div class="left-content">
<div class="post-holder" width="70%" style="padding: 10px;">
<form class="post" method="post" action="#">
<textarea name="paragraph" placeholder="Hey there! Share a game highlight with a photo or video... <?php echo $error; ?>" maxlength="250"></textarea>
<input type="submit" name="post" class="button_post" value="POST" />
<label class="video"><input type="text" name="video" placeholder="Use a YouTube link in order to post video..."/></label><br />
</form>
</div>
<div class="new-posts" style="padding: 10px;">
<ul>
<?php include('show_posts.php')?>
</ul>
</div>
</div>
</div>
</div>
<div class="footer">
</div>
</div>
</body>
</html>
Also if there is anyway to make my code simpler, then i'm open to suggestions.
*I want the code to be php because i understand php more than i do js, jquery etc.
$postsNum = $_GET['num'];
$query = $con->query("SELECT * FROM `posts` ORDER BY `id` DESC LIMIT $postsNum");
The LOAD MORE button with a link: YOURURL?num=n
n can change by your php code.
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