HTML form sends the wrong database ID PHP - php

I made a user system for my website. If you open it you well see a list of all users and you can lock or unlock them by changing "n_gesperrt" in the database to 1 or 0. 1 means locked.
The form you see here is always sending the last user id (n_id) to the php script on the top. So if I want to change something it only works with the last user shown on the list.
How can I solve that problem?
These are the code pieces:
THE FORM:
while ($zeile = mysqli_fetch_assoc($res))
{
echo "<form name=\"nutzer_sperren\" method=\"POST\" action=\"index.php?page=nutzer_sperren\">";
echo "<input type=\"hidden\" name=\"n_id\" value=\"".$zeile['n_id']."\">";
echo $zeile['n_id'];
if($zeile['n_gesperrt'] == 0){
echo "<input type =\"submit\" name=\"sperren\" value=\"Nutzer sperren\">";
}
else {
echo "<input type =\"submit\" name=\"entsperren\" value=\"Nutzer entsperren\">";
}
echo '</form">';
THE EDITING IN DATABASE:
if(isset($_POST['sperren']))
{
$sperrung = mysqli_real_escape_string($verbinde, 1);
mysqli_query($verbinde, 'UPDATE nutzer SET n_gesperrt ="'.$sperrung.'" WHERE n_id ='.$_POST["n_id"].'') or die(mysqli_error($verbinde));
echo "Daten wurden erfolgreich geändert. <br>Bitte aktualisieren Sie die Seite!";
echo $_POST["n_id"];
echo "<hr>";
}
if(isset($_POST['entsperren']))
{
$entsperren = mysqli_real_escape_string($verbinde, 0);
mysqli_query($verbinde, 'UPDATE nutzer SET n_gesperrt ="'.$entsperren.'" WHERE n_id ='.$_POST["n_id"].'') or die(mysqli_error($verbinde));
echo "Daten wurden erfolgreich geändert. <br>Bitte aktualisieren Sie die Seite!";
echo $_POST["n_id"];
echo "<hr>";
}

There are few things you need to change in your code, such as:
... The form you see here is always sending the last user id (n_id) to the php script on the top. So if I want to change something it only works with the last user shown on the list.
That's because you've assigned the same name attribute for all of your hidden input elements. Change your name attribute in the following way,
... name='n_id[]' ...
Change the name attribute of submit elements to just submit, because in this way you don't have to use two separate if blocks to handle user's response.
Remove the double quote from echo '</form">';, otherwise your form would break.
So your while() loop should be like this:
while ($zeile = mysqli_fetch_assoc($res)){
echo "<form method='POST' action='index.php?page=nutzer_sperren'>";
echo "<input type='hidden' name='n_id[]' value='".$zeile['n_id']."'>";
if($zeile['n_gesperrt'] == 0){
echo "<input type ='submit' name='submit' value='Nutzer sperren'>";
}
else {
echo "<input type ='submit' name='submit' value='Nutzer entsperren'>";
}
echo '</form>';
}
Furthermore, as I said above, you don't have to use two separate if blocks, just use one if block to check whether the form is submitted or not and toggle the n_gesperrt column value in your UPDATE operation, like this:
if(isset($_POST['submit'])){
mysqli_query($verbinde, 'UPDATE nutzer SET n_gesperrt = IF(n_gesperrt = 1, 0, 1) WHERE n_id ='.$_POST["n_id"][0]) or die(mysqli_error($verbinde));
echo "Daten wurden erfolgreich geändert. <br>Bitte aktualisieren Sie die Seite!";
}

bro use name as array
like below and you will get your result in array
while ($zeile = mysqli_fetch_assoc($res))
{
echo "<form name=\"nutzer_sperren\" method=\"POST\" action=\"index.php?page=nutzer_sperren\">";
echo "<input type=\"hidden\" name=\"n_id[]\" value=\"".$zeile['n_id']."\">";
echo $zeile['n_id'];
if($zeile['n_gesperrt'] == 0){
echo "<input type =\"submit\" name=\"sperren[]\" value=\"Nutzer sperren\">";
}
else {
echo "<input type =\"submit\" name=\"entsperren[]\" value=\"Nutzer entsperren\">";
}
echo '</form">';
on submission page get value like
$name=$_POST['entsperren'];
print_r($name);

Related

Error when trying to get the button id using PHP

I am generating a list of buttons with the id being a value extracted from a database. Then I want to take this id and display. But, when I try to do that, I get an error. Can some one tell me what I'm doing wrong here.
Button generation
//This function will display items
function showItems($sqlString)
{
$result = mysqli_query($this->connectToDb(), $sqlString);
//var_dump($result);
if(mysqli_num_rows($result) > 0)
{
foreach ($result as $row)
{
echo "<div class='div_item'>";
echo "<img src='../images/uploads/".$row['It_image']."' style='width:200px;height:150px;'>"."<br>";
echo "IT CODE: ".$row['It_code']."<br>";
echo "ITEM: ".$row['It_name']."<br>";
echo "DESC: ".$row['It_desc']."<br>";
echo "QTY AVAIL: ".$row['qty']."<br>";
echo "PRICE: ".$row['price']."<br>";
echo "<form enctype='multipart/form-data' action='' method='POST'>";
echo "<button type='submit' name='id' id='".$row['It_code']."'>Buy</button>";
echo "</form>";
echo "</div>";
}
}
}
Displaying the ID when the respective button is clicked
//get id of the button
if (isset($_POST['id']))
{
echo $_GET['id'];
}
Error
Pass it inside value value='".$row['It_code']."'
echo "<button type='submit' value='".$row['It_code']."' name='id' id='".$row['It_code']."'>Buy</button>";
Try to var_dump($result), the error message tells us it can't find the key "id". So var_dump could give us more information about what is missing.
It could be because the form method is post, that data will be stored in the $_POST['id'] and not $_GET['id']

Why does my submit button act as a pagerefresher?

This code is supposed to update my table, but it just refreshes the page. The query works, i tested it. its the submit button but i dont know why>
if(isset($_POST['nameupdate']))
{
echo('<hr>');
echo('Vul nieuwe waarde in');
$did = $jnm;
echo "<form method='post' data-ajax='false' action=''>";
echo "<input type='text' name='nmbox' value='".$did."'>";
echo "<input type='submit' name='nmupdate' value='Update'>";
echo "</form>";
if(isset($_POST['nmupdate']))
{
$opm = $_POST['nmbox'];
$query = "UPDATE users SET name = '$opm' WHERE username = '$jus'";
$stm = $con->prepare($query);
$stm->execute();
header("location:decdprofileedit.php");
}
}
You have to put nested if statement outside the first if statement

foreach loop submit button issue

First of all i start writing php this week and there may be unnecessary lines:)
I'm just trying figuring out the logic. For now everything went fine(thx to stackoverflow). Until,
In my foreach loop statement i put submit button, I added the db id after button name. So i put the id after $_POST too. But the problem is only the first submit button works. When i click the others nothing happens.
Thanks for your help. (btw i tried all other answers for foreach button issues. didn't help)
if (isset($_POST['arama'])) {
$ara = trim(strip_tags($_POST["ara"]));
$duzelt = trim(strip_tags($_POST["duzelt"]));
$id = $_SESSION["id"];
if (!empty($ara)) {
echo '<div class="form-style-10">';
echo '<table><tr>';
echo "<th>İsim</th><th>Cep Telefonu</th><th>Sabit Telefonu</th> </tr>";
$ara1 = '%'.$ara.'%';
$sql = $db -> query("SELECT * FROM rehber WHERE k_id='".$id."' AND isim LIKE '%$ara%'");
$yok = $sql->rowCount();;
if ($yok != 0) {
echo "<form action='' method='POST'>";
foreach ($sql as $dizi) {
$iden=$dizi[id];
echo "<tr><td><input type='text' name='isim1' value='$dizi[isim]'></td>";
echo "<td><input type='text' name='cep1' value='$dizi[cepno]'></td>";
echo "<td><input type='text' name='ev1' value='$dizi[evno]'></td>";
echo "<input type='hidden' name='id2' value='$iden'>";
echo "<td><input type='submit' name='duzelt".$iden."' value='duzelt'></td></form></tr>";
}
echo "</table>";
echo "</div>";
}else{
echo '<div class="form-style-10" style="background-color:#f04"><div class="section" style="color:#FFFC00">'.$ara.' adında bir kullanıcı kayıtlı değildir.</div></div>';
header("refresh:3;rehber.php?mr=arama");
}
}
else{
echo '<div class="form-style-10" style="background-color:#f04"><div class="section" style="color:#FFFC00">Arama kutusu boş. Lütfen aramak istediğiniz kişinin adını yazınız.</div></div>';
header("refresh:3;rehber.php?mr=arama");
}
}
$buton = "duzelt".$_POST["id2"];
if (isset($_POST[$buton]) && $_POST[$buton]) {
$duz = $_POST[$buton];
if (!empty($duz)) {
echo $_POST["isim1"];
echo $_POST["cep1"];
echo $_POST["ev1"];
echo $_POST["id2"];
echo $buton;
$sql1 = $db -> prepare("UPDATE rehber SET isim = ?, cepno = ?, evno = ? WHERE id = ?");
$sql1 -> execute(array($_POST["isim1"], $_POST["cep1"], $_POST["ev1"], $_POST["id2"]));
echo "Kayıt başarıyla tamamlanmıştır.";
header("refresh:3;rehber.php?mr=duzen");
}else{
echo "kaydedilecek veri yok";
}
}
The only real issue that I can see if that the initial form constructor appears outside of the form element, whilst the form element is closed in the foreach loop. I would move the form constructor into the foreach loop. Also, as a secondary, you are using id as a constant value in your $iden constructor. This is easily resolved, but it seems you really want the index, which you can get from the foreach loop.
Please observe:
foreach ($sql as $iden => $dizi) { // <-- $iden is now the index
//$iden=$dizi[id]; <- no longer required
echo "<form action='' method='POST'>"; // <--form created inside loop
echo "<tr><td><input type='text' name='isim1' value='$dizi[isim]'></td>";
echo "<td><input type='text' name='cep1' value='$dizi[cepno]'></td>";
echo "<td><input type='text' name='ev1' value='$dizi[evno]'></td>";
echo "<input type='hidden' name='id2' value='$iden'>";
echo "<td><input type='submit' name='duzelt".$iden."' value='duzelt'></td></form></tr>";
}
Now you have the form being constructed within the loop, and the index is properly being passed along.

Get variable from another table in a WHILE loop

<?php
$id = $_SESSION['user_id'] ;
echo "<form method='post' action='#'>";
echo "</select>
<p>Which Hospital Would You Like to Submit To?</p>";
$queryitem = "SELECT * FROM vendor_hospital WHERE vendor_hospital.user_id = '$id' AND vendor_hospital.approval_status = '1'" or die('MYSQL error: ' . mysql_error());
if ($result = mysql_query($queryitem)) {
if ($success = mysql_num_rows($result) > 0) {
echo "<select name='hospital_name'>";
echo "<option>-- Select A Facility --</option>";
while ($row = mysql_fetch_array($result))
echo "<option value='$row[manufacturer_id]'>$row[manufacturer_id]</option>";
echo "</select><br><br>";
} else {
echo "No results found.";
}
} else {
echo "Failed to connect to database.";
}
echo "<input type='submit' value='Submit' name='submit' class='button' /></form>";
?>
For some reason I'm stuck here. I'm just trying to get the manufacturer name to show in my options instead of the manufacturer_id. The manufacturer name is a foreign key in another table so I can't simply call $row[manufacturer_id] in my option tag. What should I do here? My only thought is to run a query inside the option tag for every manufacturer_id listed as a value but I'm sure that is overkill. Can someone point me in the right direction of a more elegant solution than that?
Not really sure what you are trying to do...but try this.
Replace this:
while ($row = mysql_fetch_array($result))
echo "<option value='$row[manufacturer_id]'>$row[manufacturer_id]</option>";
echo "</select><br><br>";
With this:
while ($row = mysql_fetch_array($result)){
echo "<option value='".$row['manufacturer_id']."'>".$row['manufacturer_id']."</option>";
}
echo "</select><br><br>";
Also be sure to double check and make sure that you are pulling from the right database, that it is populated, you are calling the right table names, etc...

How can I send over multiple check box checks in POST to be deleted from a database?

I've been trying think of a way to do this. I want it to where users can check off items, hit submit and it goes to the code on the next page and deletes all of the checked items from the database. Problem one is that in the post its only sending over the last checked item. Here is how I have it set up right now.
echo "<form name='fm1' METHOD ='POST' ACTION ='displaydelete.php' > ";
//Draws up the table headers
echo "";
echo "";
echo "Fund Number ";
echo "Hours ";
echo "Percentage";
echo "Delete";
echo "";
//While there are query results data is pushed into table cells
while ($row = mysql_fetch_array($queryResult2))
{
$hours = $row['hours'];
$percentage = $hours / 160 * 100;
echo "<tr>";
echo "<td>";
echo $row['funnumber'];
echo "</td>";
echo "<td>";
echo $hours;
echo "</td>";
echo "<td>";
echo $percentage ."%";
echo "</td>";
echo "<td>";
echo "<input type='checkbox' name='id' value='$row[id]'/>";
echo "</td>";
echo "</tr>";
}
//End of tabel
echo "</table>";
echo" ";
echo "";
What I would like to do is push all of the items into a variable and maybe delete them that way. I'm not really sure how you would handle multiple deletes. I'm doing my delete like this for something else if this helps any.
$query = "DELETE FROM users
WHERE ninenumber = '$ninenumber'";
$result = mysql_query($query)
or die("Query Failed: " .mysql_error());
mysql_close($conn);
In your form:
<input type='checkbox' name='id[]' value='$row[id]'/>
Then, in the file you post to:
if(is_array($_POST['id'])){
foreach($_POST['id'] as $id){
...do something to $id;
}
}
Instead of this:
echo "<input type='checkbox' name='id' value='$row[id]'/>";
You need this:
echo "<input type='checkbox' name='id[]' value='$row[id]'/>";
Note the difference. I added [] after the input name. This tells the client and server that there are multiple inputs with that name. $_POST['id'] will be an array you can loop through on the next page.
foreach ($_POST['id'] as $checkbox) {
// DELETE FROM users WHERE ninenumber = $checkbox
}
isset, is_array, and mysql_real_escape_string omitted for brevity.
In the form-generating code, make the name in the html have" []" after it:
...
echo "<input type='checkbox' name='id[]' value='$row[id]'/>";
...
Then, in the form-reading code, your post'ed id will be an array.
$id_array = isset($_POST['id']) && is_array($_POST['id']) ? $_POST['id'] : array();
foreach( $id_array as $id ) {
$query = "DELETE FROM users WHERE ninenumber = '" . mysql_real_escape_string($id) . "'";
// execute the delete query
}
Putting [] after the name of a control will turn it into an array in the superglobal that you can then iterate over to get all the values from.
You need to have the same name for all of your checkboxes, then all values are passed as array POST variable.
<input type='checkbox' name='id[]' value='$row[id]'/>
Change
name=id
to
name=id[]
this will then give you an array.

Categories