PHP insert an order in a table with all the prizes - php

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

Related

Problem with PHP, using load jquery + GET

I'm currently doing a private chat (style messenger), and I got a problem..
I have a href a link which sends an ID using GET to another page, the thing is that on the other page I load a jquery script which again sends to another page, suddenly it no longer finds the ID GET, what should I do? I want to actualise the page (the messages) thanks (noted that I'm new, I'm not enough good to use ajax or something..)
message.php
message
<?php
// $allUsers = 'SELECT * FROM members WHERE name LIKE "%cc%" ORDER BY id DESC' / SEARCH MEMBERS
$allUsers = $dbh->query('SELECT * FROM members ORDER BY id DESC LIMIT 0, 5');
if ($allUsers->rowCount() > 0)
{
while ($user = $allUsers->fetch())
{
?>
<div id="s_un_main">
<div class="s_un_main_pun">
<img src="../images/avatar/<?php echo $user['avatar'];?>">
<p><?php echo $user['name']; ?></p>
</div>
<div class="s_un_main_pdeux">
<a class="private" target="_blank" href="private.php?id=<?php echo $user['id']; ?>">Message</a>
</div>
</div>
<?php
}
}
else
{
echo "<p>" . "Aucun utilisateur trouvé. " . "</p>";
}
?>
private.php
private
<div id="get_name">
<?php
// USERINFO
if (isset($_SESSION['id']) AND !empty($_SESSION['id']))
{
$getid = $_GET['id'];
$req = $dbh->prepare('SELECT * FROM members WHERE id = :getid');
$req->bindValue('getid', $getid);
$req->execute();
$userinfo = $req->fetch();
}
?>
<div>
<img id="img_header" width="50" src="../images/avatar/<?php echo $userinfo['avatar'];?>">
</div>
<?php echo "<p>" . $userinfo['name'] . "</p>"; ?>
</div>
<section id="zz">
<div id="show_msg">
<?php
// AFFICHER LES MESSAGES
$getid = $_GET['id'];
$takeMsg = $dbh->prepare('SELECT * FROM private WHERE id_sender = :sender AND id_receipter = :receipter OR id_sender = :senderr AND id_receipter = :receipterr');
$takeMsg->bindValue('sender', $_SESSION['id']);
$takeMsg->bindValue('receipter', $getid);
$takeMsg->bindValue('senderr', $getid);
$takeMsg->bindValue('receipterr', $_SESSION['id']);
$takeMsg->execute();
while ($message = $takeMsg->fetch())
{
if ($message['id_receipter'] == $_SESSION['id'])
{
?>
<p style="color: red"><?php echo $message['message']; ?></p>
<?php
}
elseif ($message['id_receipter'] == $_GET['id'])
{
?>
<p style="color: green "><?php echo $message['message']; ?></p>
<?php
}
}
?>
</div>
</section>
<form id="private_form" method="POST" action="">
<textarea name="message"></textarea>
<input type="submit" name="send"></input>
</form>
<script>
setInterval('load_messages()', 1500);
function load_messages()
{
$('#zz').load('private_message.php');
}
</script>
private_message.php
error
<!-- DB -->
<?php include("../db/db.php"); ?>
<!-- DB -->
<?php
// AFFICHER LES MESSAGES
$getid = $_GET['id'];
var_dump($getid);
$takeMsg = $dbh->prepare('SELECT * FROM private WHERE id_sender = :sender AND id_receipter = :receipter OR id_sender = :senderr AND id_receipter = :receipterr');
$takeMsg->bindValue('sender', $_SESSION['id']);
$takeMsg->bindValue('receipter', $getid);
$takeMsg->bindValue('senderr', $getid);
$takeMsg->bindValue('receipterr', $_SESSION['id']);
$takeMsg->execute();
while ($message = $takeMsg->fetch())
{
if ($message['id_receipter'] == $_SESSION['id'])
{
?>
<p style="color: red"><?php echo $message['message']; ?></p>
<?php
}
elseif ($message['id_receipter'] == $_GET['id'])
{
?>
<p style="color: green "><?php echo $message['message']; ?></p>
<?php
}
}
?>
var_dump($id) = not found

Why I cant get my variable from a required file?

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 !=

prepare different mysqli statement [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 2 years ago.
I get lost when I need to prepare multiple statements. I have problems with prepared statement and connection..
I have a function and I pass to it the connection to the database ($con variable). Inside this function i prepare more statement but i have an error, the server replied with:
mysql_error() expects parameter 1 to be resource, object given in select.php on line 1086
This is the page where i call the function and pass the connection variable:
include('include/connect.php');
echo show_volanti($con);
This is the connection file that I included above:
$con = mysqli_connect($host,$user,$password,$db);
if (!$con) {
die('Connection Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error()); }
if(!mysqli_set_charset($con, "utf8mb4")) {
printf("Error loading character set utf8: %s\n", mysqli_error($con));
exit(); }
and this is the function:
function show_volanti($data){
$con = $data; // PASSO CONNESSIONE
$con2 = ''; // SECONDA CONNESSIONE
$id = 1; // 1 VOLANTE
$visibile = 1; // VARIABILE DI VISIBILITA'
$rows1 = array(); // PREPARO ARRAY 1 PER ID ARTICOLI VOLANTE
$rows2 = array(); // PREPARO ARRAY 2 PER ARTICOLI VOLANTE
$rows3 = array(); // PREPARO ARRAY PER GALLERIA IMMAGINI ARTICOLI
$stmt1 = ''; // PREPARO GLI STATEMENT
$stmt2 = ''; // PREPARO GLI STATEMENT
$stmt3 = ''; // PREPARO GLI STATEMENT
$g = ''; // RIFERIMENTO ASSOCIAZIONE GALLERY VIEWER
$id_articoli = array(); // IMMAGAZZINO ID ARTICOLI DA RECUPERARE NELLA GALLERIA
$con2 = mysqli_stmt_init($con); // INIZIALIZZO LA CONNESSIONE
$stmt1 = mysqli_stmt_prepare($con2,'SELECT
articoli.id
FROM articoli
WHERE articoli.genere1 = ?
AND articoli.visibile = ?')
or die(mysql_error($con2));// QUERY INSERIMENTO DATI
mysqli_stmt_bind_param($stmt1,'ii',$id,$visibile); // LEGO I PARAMETRI
mysqli_stmt_execute($stmt1); // ESEGUO LA QUERY
mysqli_stmt_bind_result($stmt1,$rows1['id']);
while(mysqli_stmt_fetch($stmt1)){
$id_articoli = $rows1['id'];
}
// CREO RIFERIMENTO PER GALLERIA NEL VIEWER
$g .= "g";
$g .= $id_articoli;
$stmt2 = mysqli_stmt_prepare($con2,'SELECT
articoli.id,
articoli.titolo,
articoli.descrizione
FROM articoli
WHERE articoli.genere1 = ?
AND articoli.visibile = ? ')
or die(mysqli_error($con2)); // QUERY INSERIMENTO DATI
mysqli_stmt_bind_param($stmt2,'ii',$id,$visibile); // LEGO I PARAMETRI
mysqli_stmt_execute($stmt2); // ESEGUO LA QUERY
mysqli_stmt_bind_result($stmt2,$rows2['id'],$rows2['titolo'],$rows2['descrizione']);
// PREPARO QUERY PER LA GALLERIA
$stmt3 = mysqli_stmt_prepare($con2,'SELECT
galleria.id,
galleria.foto
FROM galleria
WHERE galleria.rif_id = ?
AND articoli.visibile = ? ')
or die(mysqli_error($con2)); // QUERY INSERIMENTO DATI
mysqli_stmt_bind_param($stmt3,'ii',$id_articoli,$visibile); // LEGO I PARAMETRI
mysqli_stmt_execute($stmt3); // ESEGUO LA QUERY
mysqli_stmt_bind_result($stmt3,$rows3['id'],$rows3['foto']);
$html = "";
$html .= "<div class='container'>";
$html .= " <div class='row'>";
$html .= " <div class='col-sm-12'>";
$html .= " <div class='panel panel-default'>";
$html .= " <div class='panel-body'>";
while (mysqli_stmt_fetch($stmt2)){
$html .= " <div class='col'>";
$html .= " <div class='panel panel-default'>";
$html .= " <div class='panel-heading'>$rows2[titolo]</div>";
$html .= " <div class='panel-body'>";
$html .= " <div class='row'>";
$html .= " <div class='class_p'>$rows2[descrizione]</div>";
$html .= " <div> <!-- end first row -->";
$html .= " <div class='class_container clearfix'>";
while(mysqli_stmt_fetch($stmt3)){
$html .= " <div class='thumbnail col-sm-2'>";
$html .= " <div class='class_img'>";
$html .= " <a href='$rows3[foto]' data-toggle='lightbox' data-gallery='$g' >";
$html .= " <img src='$rows3[foto]' class='img-responsive' class='img-fluid'>";
$html .= " </a>";
$html .= " </div> <!-- end class_img -->";
$html .= " </div> <!-- end thumbnail col-sm-2- -->";
}
$html .= " </div> <!-- end class_container -->";
$html .= " </div> <!-- end panel body -->";
$html .= " </div> <!-- end panel panel-default -->";
$html .= " </div> <!-- end col -->";
}
$html .= " </div> <!-- end panel-body -->";
$html .= " </div> <!-- end panel panel-default -->";
$html .= " </div> <!-- end col-sm-12 -->";
$html .= " </div> <!-- end row -->";
mysqli_close($con2); // CHIUDO CONNESSIONE
return $html;
}
This results in the error:
$stmt1 = mysqli_stmt_prepare($con2,'SELECT
articoli.id,
FROM articoli
WHERE articoli.genere1 = ?
AND articoli.visibile = ?')
or die(mysql_error($con2));// QUERY INSERIMENTO DATI
Change mysql_error to mysqli_error and your problem should be fixed.
Note: Using or die() is a bad way to handle an error.

While loop use variable 2 times

Hello guys I got a for loop cicle that prints me divs and information from SQL, I print the slider fields with the settings on the mysql like, Slider number, Field postion and so on, the problem is I have a Modal Bootstrap to be printed aswell but I cant print it inside the currently loop .
My question is, is there anyway to store a variable from a for cicle so it can be reutilized?
There is the code
$ID=$row['ID'];
$sql = "SELECT NUM_Slides as valmax FROM slider_settings,Paginas, slider_config where slider_settings.ID = $ID and Paginas.ID= $ID and slider_config.ID=$ID";
$sqlconnect =$connect->query($sql);
$sqlresult =$sqlconnect->fetch_assoc();
for ($k = 1 ; $k <= $sqlresult['valmax']; $k++){
echo "<div class='slider1'>";
$sql1 = "SELECT P$k as campos, tituloP$k as titulo FROM slider_settings, Paginas,slider_config where slider_settings.ID = $ID and Paginas.ID= $ID and slider_config.ID = $ID";
$sqlconnect1 =$connect->query($sql1);
$sqlresult1 =$sqlconnect1->fetch_assoc();
echo "<div class='titulo'>
<h2>$sqlresult1[titulo]</h2>
</div>";
for ($l = 1 ; $l <= $sqlresult1[campos]; $l++){
$campo = "SELECT Butao,Titulo,Texto FROM slider_config, Paginas, slider_settings where slider_config.ID = $ID and Paginas.ID = $ID and slider_settings.ID =$ID and P_NUM = $k and Campo = $l";
$sqlconnect2 = $connect->query($campo);
$sqlresult2 = $sqlconnect2->fetch_assoc();
echo "<div class='part' id='part".$l."'>
<div id='imagem' class='button' data-toggle='modal' data-target='#myModal".$l."'>
<img src='data:image/png;base64," . base64_encode($sqlresult2['Butao']) . "'/>
</div>
<div id='titulo'>
<h4>$sqlresult2[Titulo]</h4>
</div>
<div id='texto'>
$sqlresult2[Texto]
</div>
</div>";
}
echo "</div>";
}
and There is the code that cant printed inside of the div or modal wont display
$modal = "SELECT Titulo_modal , Imagem_modal , Texto_modal FROM modal_settings , Paginas where modal_settings.ID = $ID and Paginas.ID= $ID and P_NUM_modal = $k and Campo_modal = $l";
$sqlconnect33 =$connect->query($modal);
$sqlresult33 =$sqlconnect33->fetch_assoc();
for ($n = 1 ; $n <= $sqlresult1[campos]; $n++){
echo "<div class='modal fade' id='myModal".$n."'>
<div class='modal-dialog modal-lg'>
<div class='modal-content'>
<div class='modal-header'>
<h4 class ='titulopopup'>$sqlresult33[Titulo_modal]</h4>
<button type='button' class='close' data-dismiss='modal'>
<span aria-hidden='true'>×</span></button>
</div>
<div class='modal-body'>
<div class='imagem'>
<img src='data:image/png;base64," . base64_encode($sqlresult33['Imagem_modal']) . "'/>
</div>
<div class='texto'>
$sqlresult33[Texto_modal]
</div>
</div>
</div>
</div>
</div>";
}
NOTE : the $ID is comming from another file :) and its work fine the first half of the code
maybe create array like that
$array = [];
for ($n = 1 ; $n <= $sqlresult1[campos]; $n++) {
$array[$k] = $i;
}
this way u can reuse your var stored in array in other for loop like
foreach ($array as $k => $i) {
// and u get all your var :)
}
with your code u can do somethings like
$ID=$row['ID'];
// here
$array = [];
//
$sql = "SELECT NUM_Slides as valmax FROM slider_settings,Paginas, slider_config where slider_settings.ID = $ID and Paginas.ID= $ID
and slider_config.ID=$ID";
$sqlconnect =$connect->query($sql);
$sqlresult =$sqlconnect->fetch_assoc();
for ($k = 1 ; $k <= $sqlresult['valmax']; $k++){
echo "<div class='slider1'>";
$sql1 = "SELECT P$k as campos, tituloP$k as titulo FROM slider_settings, Paginas,slider_config where slider_settings.ID = $ID and Paginas.ID= $ID and slider_config.ID = $ID";
$sqlconnect1 =$connect->query($sql1);
$sqlresult1 =$sqlconnect1->fetch_assoc();
echo "<div class='titulo'>
<h2>$sqlresult1[titulo]</h2>
</div>";
for ($l = 1 ; $l <= $sqlresult1[campos]; $l++){
// here
$array[$k] = $l;
$campo = "SELECT Butao,Titulo,Texto FROM slider_config, Paginas, slider_settings where slider_config.ID = $ID and Paginas.ID = $ID and slider_settings.ID =$ID and P_NUM = $k and Campo = $l";
$sqlconnect2 = $connect->query($campo);
$sqlresult2 = $sqlconnect2->fetch_assoc();
echo "
<div class='part' id='part".$l."'>
<div id='imagem' class='button' data-toggle='modal' data-target='#myModal".$l."'>
<img src='data:image/png;base64," . base64_encode($sqlresult2['Butao']) . "'/>
</div>
<div id='titulo'>
<h4>$sqlresult2[Titulo]</h4>
</div>
<div id='texto'>
$sqlresult2[Texto]
</div>
</div>";
}
echo "</div>";
}

Form submitting more than once

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> &nbsp 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> &nbsp 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> &nbsp 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> &nbsp 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.

Categories