Var not affected on mysql - php

Good morning all !
I have a problem with a var in my code :
<?Php
error_reporting(E_ALL);
//Si IP correspond pas au PC autorisé, on retourne au debut.
include "./_protection.php";
$data='';
$rep='';
$requete='';
$val = '';
$Reference= '';
echo '<h2><u>Commander des pièces</u></h2><br>';
/*****************************************************************************************************
* AJOUT DE PIECE DANS LA BASE DE DONNEES
*****************************************************************************************************/
if(#$_POST['action'] == "ajouter")
{
if(!empty($_POST['choix'])){
foreach($_POST['choix'] as $val){
$Reference.="$val,";
}
//Injection dans la base SQL
include "./../connexion.inc";
mysql_query("INSERT INTO `tbl_commandes` ( `id`, `Eleve`, `Reference`, `Quantite`, `Date`, `Statut` )
VALUES ( '', '".$_POST['Eleve']."', '".$_POST['Reference']."', '".$_POST['Quantite']."', '".$_POST['Date']."', '".$_POST['Statut']."' )");
mysql_close();
}
}
/*****************************************************************************************************
* FORMULAIRE POUR L'AJOUT DE PIECE
*****************************************************************************************************/
echo '
<fieldset>
<legend>Commander des Pièces</legend>
<FORM action="./?page=commande_piece_full_php" method="POST">
<p align="left">
<H2>Pièces :</h2>
<br>';
echo $Reference;
include "./../connexion.inc";
$rep = mysql_query("SELECT id_categorie_piece, categorie_piece FROM tbl_categorie_piece ORDER BY categorie_piece");
mysql_close();
include "./../connexion.inc";
while($data = mysql_fetch_array($rep))
{
echo $data['categorie_piece'];
echo '<br>';
$requete = $data['id_categorie_piece'];
$reponse = mysql_query("SELECT id_piece, piece FROM tbl_piece WHERE idr_categorie_piece='$requete' ORDER BY piece");
while($donnees = mysql_fetch_array($reponse)){
?> <input type="checkbox" name="choix[]" value="<? echo $donnees['id_piece'] ?>"><? echo $donnees['piece'] ?><br> <?
}
echo '<br>';
}
mysql_close();
echo '
Elève :
<select name="Eleve">';
include "./../connexion.inc";
$reponse2 = mysql_query("SELECT id_client, client FROM tbl_client ORDER BY client");
while($donnees2 = mysql_fetch_array($reponse2))
{
?> <option value="<? echo $donnees2['client'] ?>"><? echo $donnees2['client'] ?></option> <?
}
mysql_close();
echo '
</select>
<br>
Date souhaitée : <input type="textbox" name="Date">
<br>
Quantité : <input type="textbox" name="Quantite">
<br>
<input type="submit" value="ajouter">
<input type="hidden" name="action" value="ajouter">
</form>
</fieldset>';
?>
my var $reference is Ok, i can echo $reference; and get the content rightly
BUT when i wanna send $reference to my mysql table .. that doesn't send it
When i submit, i get this notice from the parser : Notice:
Undefined index: Reference in /home/bddstock/www/admin/commande_piece_full_php.php on line 27
but when it is submited i get the right content in my echo line under PIECES
so i really don't understand ..
can someone help me ?

Change your insert statement to
mysql_query("INSERT INTO `tbl_commandes` ( `id`, `Eleve`, `Reference`,
`Quantite`, `Date`, `Statut` )
VALUES ( '', '".$_POST['Eleve']."', '".$Reference."', '".$_POST['Quantite']."', '".$_POST['Date']."', '".$_POST['Statut']."' )");
i.e change $_POST['Reference'] to $Reference as you have not posted this field and it seems you derive it from looping $_POST['choix'].
Note : use mysqli instead of mysql and refer How can I prevent SQL injection in PHP?

Related

How to store POST elements in an array

It is for a "recipes personal website", I am stuck with the Search function.
First let me tell you how is the database :
1 table categories : the type of recipe
Link for image
1 table ingredients : all the ingredients used in the recipes
Link for image
1 table recettes : all recipes stored with a column for their categories
Link for image
1 table ingredient_recette : to link all ingredients and quantity that composed a specific recipe
Link for image
Here I would like to make a page where I can search for recipes that contain for example 1 or 2 special ingredients, and in which category I would like to search. Link for search page image
This is the search.php I've done for the moment... (you can see it on codeshare.io)
How can I proceed to search recipes that contain only selected
ingredients ?
<?php
include("cnx.php");
include("functions.php");
// Query pour les catégories
$rq_cat = "SELECT * FROM categories ORDER BY id_cat";
$result_cat = $mysqli->query($rq_cat);
if(isset($_POST["Recherche"]) AND $_POST["Recherche"] == "Go")
{
if($_POST["cat_recette"] == "") // Si aucune catégorie sélectionnée
{
echo "Aucune catégorie ";
$rq_recettes = "SELECT * FROM recettes";
$result_recettes = $mysqli->query($rq_recettes);
}
elseif($_POST["cat_recette"] == "Entrée") // Si catégorie Entrée sélectionnée
{
echo "Catégorie Entrée ";
}
elseif($_POST["cat_recette"] == "Plat") // Si catégorie Plat sélectionnée
{
echo "Catégorie Plat ";
$rq_recettes = "SELECT * FROM recettes WHERE cat_recette='Plat'";
$result_recettes = $mysqli->query($rq_recettes);
}
elseif($_POST["cat_recette"] == "Dessert") // Si catégorie Dessert sélectionnée
{
echo "Catégorie Dessert ";
$rq_recettes = "SELECT * FROM recettes WHERE cat_recette='Dessert'";
$result_recettes = $mysqli->query($rq_recettes);
}
elseif($_POST["cat_recette"] == "Soupe") // Si catégorie Soupe sélectionnée
{
echo "Catégorie Soupe ";
$rq_recettes = "SELECT * FROM recettes WHERE cat_recette='Soupe'";
$result_recettes = $mysqli->query($rq_recettes);
}
elseif($_POST["cat_recette"] == "Autre") // Si catégorie Autre sélectionnée
{
echo "Catégorie Autre ";
$rq_recettes = "SELECT * FROM recettes WHERE cat_recette='Autre'";
$result_recettes = $mysqli->query($rq_recettes);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css?family=Quando&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/style.css">
<title>cooketal</title>
</head>
<body class="search">
<header>
<?php
include("nav.php");
?>
</header>
<div class="banner">
<h2>Recherche</h2>
</div>
<section class="all-recipes add left">
<div class="frigo-ing col-3">
<table>
<div class="contenu">
<form action="" method="POST">
<h1>Les ingrédients que je possède</h1>
<?php for ($i=1; $i < 10 ; $i++) { ?>
<table>
<th><span><?php echo $i ?></span></th>
<td>
<select name="ing<?php echo $i; ?>">
<option value="" selected>- - - -</option>
<?php
$rq_ingredients = "SELECT * FROM ingredients ORDER BY nom_ingredient ASC";
$result_ingredients = $mysqli->query($rq_ingredients);
while($row_ingredients = $result_ingredients->fetch_object()){ ?>
<option value="<?php echo $row_ingredients->id_ingredient; ?>"><?php echo $row_ingredients->nom_ingredient; ?></option>
<?php } ?>
</select>
</td>
</table>
<?php } ?>
<h1>Une catégorie en particulier ?</h1>
<select id="cat-recette" name="cat_recette">
<option value="">- - - -</option>
<?php
$rq_cat = "SELECT * FROM categories ORDER BY id_cat";
$result_cat = $mysqli->query($rq_cat);
while( $row_cat = $result_cat->fetch_object()){ ?>
<option value="<?php echo $row_cat->cat_recette; ?>" <?php if( isset( $_POST["cat_recette"]) AND $_POST["cat_recette"] == $row_cat->cat_recette){ echo "selected";} ?>><?php echo $row_cat->cat_recette; ?></option>
<?php } ?>
</select><br>
<input type="submit" name="Recherche" value="Go">
</form>
</div>
</table>
</div>
<div class="frigo-ing col-3">
<h1>Résultats</h1>
</div>
</section>
If suggest you to use ajax and make select in html and set the ajax call when the select's value has changed.Like this.
SELECT:
<select name='select' class='ingredient'>
<option value="" selected>- - - -</option>
<?php
$rq_ingredients = "SELECT * FROM ingredients ORDER BY nom_ingredient ASC";
$result_ingredients = $mysqli->query($rq_ingredients);
while($row_ingredients = $result_ingredients->fetch_object()){ ?>
<option value="<?php echo $row_ingredients->id_ingredient; ?>"><?php echo $row_ingredients->nom_ingredient; ?></option>
<?php } ?>
</select>
AJAX CALL:
$('.ingredient').change(function() {
var selected = $('.ingredient').val();
var data = "";
$.ajax({
type:"GET",
url : "search.php?ingredient='+selected+'',
data : "",
async: false,
success : function(response) {
//Here you get recipe name in response as return .. I hope it work.
},
error: function() {
alert('Error occured');
}
});
Make another page called search.php
Here you get recipe having ingredient
<?php
$id = $_GET["ingredient"];
$sql = "SELECT * FROM recettes WHERE cat_recette='$id'";
$result = $conn->query($statement);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "".$row["nom_recette"]."";
}
}
?>

My SQL Update query won't update the specified record [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(2 answers)
Closed 3 years ago.
I'm making a system where you can assign guests to certain rooms. To unassign a guest, two UPDATE queries must be executed in two different tables, but only one of these is actually executing. The one that doesn't work, doesn't put out an error message, but doesn't seem to do anything.
I've already printed out all the variables I'm using in my query to check for mistakes, but I haven't found any data in those which was wrong. I also checked if there were errors in my query using phpMyAdmin, but they properly executed there. I used the same type of method on another page, updating something else, and that worked. Could someone take a look in my code and tell me what I've done wrong?
Thanks in advance!
if(isset($_GET['view'])) {
$viewid = $_GET['view'];
$sql = "SELECT * FROM renterinfo LEFT JOIN apartments ON apartments.renterid = renterinfo.renterid WHERE renterinfo.renterid = $viewid";
$xresult = mysqli_query($conn, $sql);
$xrow = mysqli_fetch_array($xresult);
}
$freeroomquery = "SELECT * FROM apartments WHERE status = 1 ORDER BY apartmentno ASC";
$freerooms = mysqli_query($conn, $freeroomquery);
$rentername = $xrow['name'];
$renteremail = $xrow['email'];
$roomno = $xrow['apartmentno'];
$enddate = $xrow['leaveroom'];
if(isset($_POST['submit'])){
//------------------------------------
$name = $_POST['newNaam'];
$email = $_POST['newEmail'];
$room = $_POST['newKamer'];
$leaveroom = $_POST['newEinde'];
$insertSql = "UPDATE renterinfo SET name = '$name', email = '$email', leaveroom = '$leaveroom'";
$updateRoom = "UPDATE apartments SET renterid = NULL WHERE apartmentno = '$roomno'";
The second UPDATE query doesn't update the renterid. The first UPDATE query does work.
if ($conn->query($insertSql) === TRUE) {
$success = "Huurder <strong>'" . $name . " - CobbenCampus'</strong> is succesvol toegevoegd.";
} else {
$error = "Er is een fout opgetreden bij het toevoegen van appartement <strong>'" . $apartmentno . " - CobbenCampus'</strong>. Zijn alle velden ingevuld?<br><strong>Foutmelding:</strong> " . $sql . "<br>" . $conn->error;
}
if ($conn->query($updateRoom) === TRUE) {
echo "Succeeded.";
} else {
echo "Query unsuccessfull.";
}
$conn->close();
}
HTML-code:
<form action="viewrenter.php" method="POST" enctype="multipart/form-data">
<label id="first">Voor- en achternaam huurder:</label><br>
<input type="text" name="newNaam" value="<?php echo $rentername ?>"><br><br>
<hr class="line-black">
<label id="first">E-mailadres van huurder:</label><br>
<input type="text" name="newEmail" value="<?php echo $renteremail ?>"><br><br>
<hr class="line-black">
<label id="first">Kamernummer:</label><br/>
<p>Een kamer toewijzen aan een huurder, zal de kamer automatisch op bezet zetten.</p>
<select name="newKamer">
<option value="<?php echo $roomno ?>"><?php echo $roomno ?></option>
<option value="0">Geen kamer</option>
<?php
while($rooms = mysqli_fetch_array($freerooms)) {
echo "<option value='" . $rooms['apartmentno'] . "'>" . $rooms['apartmentno'] . "</option>";
}
?>
</select><br><br>
<hr class="line-black">
<label id="first">Afloopdatum huurdersovereenkomst:</label><br>
<input type="text" name="newEinde" placeholder="Als: 25-04-2019" value="<?php echo $enddate ?>"><br><br>
<button class="spaced btn btn-primary btn-wide" type="submit" name="submit">Voeg huurder toe</button>
<hr class="bigspacer">
</form>
UPDATE apartments SET `renterid` = NULL WHERE `apartmentno` = `$roomno`
Write query like this. I think it will work.

MySql query returning all the data

I'm trying to use checkbox to look into my DB but i don't know why, the answer is made of all the data of the table and not the specific entry I want!
Code
$req_lieux = $sqlQuery->query("select lieux.nom from lieux, type_lieu WHERE lieux.id_type_lieu = type_lieu.ID");
PHP code:
<fieldset>
<legend class="title-color-bloc">Couleur</legend>
<?php
require_once 'search.php';
/* la requête est dans search.php */
while ($couleurs = $query_check_color->fetch())
{?>
<input class="color-choice" type="checkbox" id="color-choice<?php echo $couleurs['ID']; ?>" name="color-choice[]" value="<?php echo $couleurs['ID']; ?>">
<label for="color-choice<?php echo $couleurs['ID']; ?>"><?php echo $couleurs['couleur']; ?></label>
<?php
}
$query_check_color->closeCursor();
?>
</fieldset>
<fieldset>
<legend class="title-color-bloc">Lieux</legend>
<?php
/* la requête est dans search.php */
while ($types = $query_check_types->fetch())
{?>
<input class="type-choice" type="checkbox" id="type-choice<?php echo $types['ID']; ?>" name="type-choice[]" value="<?php echo $types['ID']; ?>">
<label for="type-choice<?php echo $types['ID']; ?>"><?php echo $types['libelle']; ?></label>
<?php
}
$query_check_types->closeCursor();
?>
</fieldset>
<input type="submit" value="Afficher" class="submit-btn" name="submit-btn">
</form>
<?php
if(isset($_POST))
{
if(!empty($_POST['type-choice']))
{
$type = implode("," , $_POST['type-choice']);
while ($type = $req_lieux->fetch())
{ ?>
<h1><?php echo $type['nom'] ?></h1>
<?php }
}
}
?>
Thanks for your help!
You're not restricting the results of your query to any specific type.
select lieux.nom from lieux, type_lieu WHERE lieux.id_type_lieu = type_lieu.ID
This query will select every record from lieux where a record exists in type_lieu.
So if you have a specific type_lieu you're trying to use then you do something like the following:
SELECT l.nom from lieux AS l INNER JOIN type_lieu AS tl ON l.id_type_lieu = tl.ID WHERE tl.type = xxxx

getting the value out of a select tag (automatic made)

I'm a starter in php and I want to get the value out of the select tag.
I am using PHP en MYSQLi, and use mysqli_fetch_row to create the tag.
I open my mysqli server, get all the values I need and it all works fine. I just want to get the selected value of the user, in the select menu.
My code is:
<?php
if(isset($_POST['verzenden']))
{ ... = $_POST['$data[0]'] ;}
?>
<form method="post">
<?php
$cmd = "SELECT * FROM gegevens";
$result = mysqli_query($verbinding, $cmd);
echo '<select>';
# zet rij per rij de resultaten in de tabel
while($data = mysqli_fetch_row($result))
{
echo ("<option value='$data[0]'>$data[0]</option><br>");
};
echo '</select>';
mysqli_close($verbinding);
?>
<button name="verzenden"> Verzend uw keuze </button>
To be able to get the value when the form is posted, you must add a NAME attibute to your SELECT tag. For example:
<?php
if(isset($_POST['verzenden']))
{ ... = $_POST['verzenden']; }
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];">
<?php
$cmd = "SELECT * FROM gegevens";
$result = mysqli_query($verbinding, $cmd);
echo "<select name='verzenden'>\r\n";
# zet rij per rij de resultaten in de tabel
while($data = mysqli_fetch_row($result)){
echo ("\t<option value='{$data[0]}'>{$data[0]}</option>\r\n");
};
echo "</select>\r\n";
mysqli_close($verbinding);
?>
<button name="verzenden"> Verzend uw keuze </button>
The NAME is important. You can then get the value from $_POST['verzenden'] in your PHP after the form is posted.

Retrieve Value with insert PDO

I'm working on a page where the user can add rows with fields of a form, dynamic, depending on the model this page http://www.linhadecomando.com/scripts/input-dinamico/
I'm having problem RECOVER FROM values ​​of the second row inserted as the first I can get quietly. Check my code:
<?php
// exibindo os dados
if ($_POST){
$IDCliente = $_POST['IDCliente'];
$IDBanco = $_POST['Banco'];
$Titular = $_POST['Titular'];
$Agencia = $_POST['Agencia'];
$CC = $_POST['CC'];
$quant_linhas = count($IDBanco);
for ($i=0; $i<$quant_linhas; $i++) {
//$pdo = conectar();
$sql = "INSERT INTO Clientes_Referencias_Bancos (IDCliente, IDBanco, Titular, Agencia, CC) VALUES (:IDCliente, :IDBanco, :Titular, :Agencia, :CC)";
$cadastrar = $pdo->prepare($sql);
$cadastrar ->bindValue(':IDCliente', $IDCliente[$i]);
$cadastrar ->bindValue(':IDBanco', $IDBanco[$i]);
$cadastrar ->bindValue(':Titular', $Titular[$i]);
$cadastrar ->bindValue(':Agencia', $Agencia[$i]);
$cadastrar ->bindValue(':CC', $CC[$i]);
$cadastrar ->execute();
if($cadastrar->rowCount() == 1):
echo "Departamento cadastrado com sucesso!<br/>";
else:
echo "Erro ao cadastrar o Departamento!";
endif;
echo "Cliente: ".$IDCliente[$i]."<br />";
echo "Banco: ".$IDBanco[$i]."<br />";
echo "Titular: ".$Titular[$i]."<br />";
echo "Agência: ".$Agencia[$i]."<br />";
echo "Conta Corrente: ".$CC[$i]."<br />";
}
}
?>
Here is my form...
<select name="Banco[]">
<input type="text" name="Titular[]" id="Titular[]" />
<input type="text" name="Agencia[]" id="Agencia[]" />
<input type="text" name="CC[]" id="CC[]" />
<input name="IDCliente[]" id="IDCliente[]" type="hidden" value="1" />
You can use transactions. You should first prepare the query. In for loop you should bind variables and execute the queries

Categories