I have a checkbox list with 10 options ik the image just have 9:
and a db:
How can I compare the input in the checkbox list with the information inside the column requerimientos in my db?, it means values from the checkbox list must contain all of the values from requerimientos and it will happen with every id, just i didn't fill the other values yet, hope this clarify it
This is what I got, if it seems I have no clue what I am doing it can't be more accurate, but I dont give up. XD
<form action="" method="post">
<?php
$query = $mysqli->query("SELECT idclasificacion,clasificacion FROM clasificacion");
while ($rows = $query->fetch_array()) {
echo'<div class="list-group-item" id='. $rows['idclasificacion'] .'>
<label>
<input type="checkbox" name="requerimiento[]" id="" value="'.$rows['clasificacion'].'">'. $rows['clasificacion'] . '
</label>
</div>';
}
?>
<button class="btn btn-primary" type="submit">Ingresar</button>
</form>
<?php
//extrae los requerimiento seleccionados en forma de string, notar que requerimiento va sin []
if (isset($_POST['requerimiento'])){
$requerimientos = implode ( ',', $_POST['requerimiento']);
echo $requerimientos;
}else {
echo'no ha selecionado ningun requerimiento para su evento';
}
echo '<br>';
$query = $mysqli->query("SELECT requerimientos FROM tipologia");
$rows = $query->fetch_assoc();
var_dump($rows);
$requetipo=explode(',', $rows['requerimientos']);
var_dump($requetipo);
$validacion=in_array($requerimientos,$requetipo);
var_dump ($validacion);
?>
tthis code compare the checked options, with the data inside requerimientos and if both are equal returns true if not false.
Now i just need to do the other options hope a for loop will help me XD
<?php
//extrae los requerimiento seleccionados en forma de string, notar que requerimiento va sin []
if (isset($_POST['requerimiento'])){
$requerimientos = implode ( ',', $_POST['requerimiento']);
// echo $requerimientos;
}else {
echo'no ha selecionado ningun requerimiento para su evento';
}
echo '<br>';
$query = $mysqli->query("SELECT requerimientos FROM tipologia where tipologia='Conferencia'");
$rows = $query->fetch_assoc();
if($requerimientos==$rows['requerimientos']){
echo 'right';
}else{
echo 'wrong';
}
Related
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.
I'm trying to modify my DB after a query. My goal is this: query the values, echo them with a little modify form that, if I hit "modify", the values will be modified in the DB. I don't know if I'm being clear enough, so here's my code, maybe it'll help me explain.
<h3>¿Quieres editar tu receta?</h3>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<h3>Introduce tu email: </h3><input type="text" name="email" placeholder="email"/><br/>
<input type="submit" name="editar" value="Buscar mi receta" class="send-btn">
</form>
<?php
date_default_timezone_set('Europe/Madrid');
$link = mysqli_connect("localhost", "root", "root", "db_csw");
if(!$link){
die("Conexion fallida: ". mysqli_error());
}
if(isset($_POST['editar'])){
$email = $_POST["email"];
$query = "SELECT * FROM datosformulario WHERE email LIKE '%".$email."%'";
$res = mysqli_query($link, $query);
if($res !== false && mysqli_num_rows($res) > 0){
while ($aux = mysqli_fetch_array($res)){
$accion = $_SERVER['PHP_SELF'];
$id = $aux['id'];
echo "Nombre de la receta: ".$aux['nombrereceta']."<br>";
echo "Pasos de la receta: ".$aux['pasosreceta']."<br>";
echo "<br><br>";
echo "¿Quieres editar esta receta?<br/>";
echo "<form method='POST' action='".$accion."'>";
echo "<input type='text' name='nombreRecetaEditada' placeholder='Nombre de la receta'/><br/>";
echo "<textarea cols='42' rows='10' name='pasosRecetaEditada' placeholder='Pasos de la receta'></textarea><br/>";
echo "<input type='submit' name='editarReceta' value='Editar' class='send-btn'><br/>";
echo "</form>";
if(isset($_POST["editarReceta"])){
$nombreRecetaEditada = $_POST["nombreRecetaEditada"];
$pasosRecetaEditada = $_POST["pasosRecetaEditada"];
$actualizaReceta = "UPDATE datosformulario SET nombrereceta='$nombreRecetaEditada',pasosreceta='$pasosRecetaEditada' WHERE id=$id";
$exito = mysqli_query($link, $actualizaReceta);
if($exito !== false){
echo "Receta modificada";
} else {
echo "No se pudo modificar la receta";
}
}
}
} else {
echo "El email introducido no se ha usado para enviar ninguna receta. Por favor, prueba de nuevo";
}
}
mysqli_close($link);
?>
Thanks in advance.
The problem is, the control will never reach to this if(isset($_POST["editarReceta"])){ ... block even though you've click on the submit button the update the values in the table. And that's because it has to cross this if(isset($_POST['editar'])){ ... block to reach the former mentioned if block.
The solution is, take this entire if(isset($_POST["editarReceta"])){ ... } outside of the if(isset($_POST['editar'])){ ... } block, like this:
// your code
if(isset($_POST["editarReceta"])){
...
}
if(isset($_POST['editar'])){
...
}
// your code
Also, to get the $id value in the UPDATE query, you have to change the form's action attribute in the following way,
echo "<form method='POST' action='".$accion."?id='".$id.">";
So that you could catch the appropriate $id in the following way,
$id = (int)$_GET['id'];
Here's the complete code,
<h3>¿Quieres editar tu receta?</h3>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<h3>Introduce tu email: </h3><input type="text" name="email" placeholder="email"/><br/>
<input type="submit" name="editar" value="Buscar mi receta" class="send-btn">
</form>
<?php
date_default_timezone_set('Europe/Madrid');
$link = mysqli_connect("localhost", "root", "root", "db_csw");
if(!$link){
die("Conexion fallida: ". mysqli_error());
}
if(isset($_POST["editarReceta"])){
$id = (int)$_GET['id'];
$nombreRecetaEditada = $_POST["nombreRecetaEditada"];
$pasosRecetaEditada = $_POST["pasosRecetaEditada"];
$actualizaReceta = "UPDATE datosformulario SET nombrereceta='$nombreRecetaEditada',pasosreceta='$pasosRecetaEditada' WHERE id=$id";
$exito = mysqli_query($link, $actualizaReceta);
if($exito !== false){
echo "Receta modificada";
} else {
echo "No se pudo modificar la receta";
}
}
if(isset($_POST['editar'])){
$email = $_POST["email"];
$query = "SELECT * FROM datosformulario WHERE email LIKE '%".$email."%'";
$res = mysqli_query($link, $query);
if($res !== false && mysqli_num_rows($res) > 0){
while ($aux = mysqli_fetch_array($res)){
$accion = $_SERVER['PHP_SELF'];
$id = $aux['id'];
echo "Nombre de la receta: ".$aux['nombrereceta']."<br>";
echo "Pasos de la receta: ".$aux['pasosreceta']."<br>";
echo "<br><br>";
echo "¿Quieres editar esta receta?<br/>";
echo "<form method='POST' action='".$accion."?id='".$id.">";
echo "<input type='text' name='nombreRecetaEditada' placeholder='Nombre de la receta'/><br/>";
echo "<textarea cols='42' rows='10' name='pasosRecetaEditada' placeholder='Pasos de la receta'></textarea><br/>";
echo "<input type='submit' name='editarReceta' value='Editar' class='send-btn'><br/>";
echo "</form>";
}
} else {
echo "El email introducido no se ha usado para enviar ninguna receta. Por favor, prueba de nuevo";
}
}
mysqli_close($link);
?>
Sidenote: Learn about prepared statement because right now your queries are susceptible to SQL injection. Also see how you can prevent SQL injection in 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?
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.
I am having this annoying problem with my query:
I have the table tbl_profissao with the fields
idtbl_profissao (INT(11), A.I.,UNSIGNED, NOT NULL),
cbo (INT(6), UNSIGNED, ZERO FILL) and
profissao (VARCHAR(110)).
I split my query into two PHP pages - profissao_busca.php and profissao_busca_input.php, with the following codes:
For profissao_busca.php:
<?php include "header.php"; ?>
<body>
<h2>PESQUISA: PROFISSÃO (CBO) </h2>
<form id="form_profissao_busca" method="post" action="profissao_busca.php?go">
<p>Por favor, escreva o número CBO da profissão que quer encontrar:<br/><br/>
<input name="busca_cbo" type="text" id="busca_cbo" size="11" maxlength="11" />
<input name="submit" type="submit" value="PROCURAR" /></p>
</form>
<?php
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("/^[ a-zA-Z]+/", $_POST['busca_cbo'])){
$name=$_POST['busca_cbo'];
$db=mysql_connect ("localhost", "root", "root") or die ('Não foi possível conectar-se ao Banco de Dados (erro No.): ' . mysql_error());
$mydb=mysql_select_db("grcc_db_pr");
$sql="SELECT idtbl_profissao, cbo, profissao FROM tbl_profissao WHERE profissao LIKE '%$name%' OR idtbl_profissao LIKE '%$name%' OR cbo LIKE '%$name%'";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)){
$Pessoa=$row['cbo'];
$ident=$row['idtbl_profissao'];
$prof=$row['profissao'];
echo "<ul>\n";
echo "<li> CBO requisitado: " . $Pessoa . "</li><li> Identificador: ". $ident . "</li><li>Ocupação:" . $prof . "</li><li>
<form id=\"form_profissao_busca\" method=\"post\" action=\"profissao_busca_input.php?go\">
<input name=\"button\" type=\"submit\" value=\"BUSCAR ESTE CBO\" />
<input name=\"busca_cbo\" type=\"hidden\" value=\"". $ident. "\" /></form></li>\n";
echo "</ul>";
}
}
else{
echo "<p>Este número não existe no Banco de Dados</p>";
}
}
}
?>
</body>
</html>
And for profissao_busca_input.php:
<?php include "header.php";
$nome_proc = $_POST['busca_cbo'];
// ================== Dados pessoais e documentos
$listagem = "SELECT idtbl_profissao, cbo, profissao FROM tbl_profissao WHERE profissao LIKE '%$name%' OR idtbl_profissao LIKE '%$name%' OR cbo LIKE '%$name%'";
$resultado = mysql_query($listagem);
$listagem = mysql_fetch_array($resultado);
print "<ul><li> CBO requisitado: $listagem[1] </li><li> Identificador: $listagem[0] </li><li>Ocupação: $listagem[2] </li></ul>";
Having a small sample of the table as:
idtbl_profissao,cbo,profissao
1,'010205','Oficial da aeronáutica'
2,'010210','Oficial do exército'
3,'010210','X5020'
4,'010215','Oficial da marinha'
5,'010215','X6020'
6,'010215','X6030'
The problem is that when I put any value belonging to "cbo" column the result is "Este número não existe no Banco de Dados" (meaning the value does not exist in the Database). Whenever I put either a word or alphanumeric value from column "profissao" it works fine.
Now I don't know what is going on, or if I missed something because "cbo" is in INT format.
Anyway, thank you in advance for your attention.
Nicole