Checked CheckBoxes - php

I need to store the ID of only the checked check boxes from the table of displaying products to use them in other things this is my code
while($row2 = mysql_fetch_array($result2)){
$pID= $row2[0];
$pName = $row2[1];
$pDes = $row2[2];
$pSale = $row2[5];
$pPrice = $row2[4];
$pPhoto = $row2[6];
if($counter % 4 == 0)echo "<tr> ";
echo "
<td> Name: '".$pName."' <br> ID: '".$pID."' <br> Price: '".$pPrice."' <br> <div id='parent'>
<img src='".$pPhoto."' width = '180' height = '180'/>
<br><input type='checkbox' name='item[]' value='".$pID."'" ." >
<div id='popup' >Description: ".$pDes." <br> Sale Percent: ".$pSale."
</div></div></td> ";
any help to mange how to store only the id of checked ckeckboxes (item[]) in array

If you are using form and want to get array of stored id when checkbox is checked after submitting the form. them no need to change the code it will select only checked checkbox values in array.
Without form we have to use jquery that answered by "Khaled Ouertani".

Related

Independent radiobuttons for each row read from server

I'm currently trying to generate independent radio buttons for each row read from my server. They are supposed to symbolize ON and OFF Switches. My current issue is that I manage to generate buttons for each row but these are not independent. I can only turn one off or on at a time.
I know that radio buttons become truly "independent" when the name of each is different. But I can't seem to figure out a way to create a new name for each row generated.
Currently my code looks like this
res = $db->query($query);
if ($res->num_rows > 0) {
while ($row = $res->fetch_object()) {
$query = "SELECT * FROM device_status
WHERE device = ($row->id)";
$status = $db->query($query);
$device_status = $status->fetch_object();
$content .= <<<END
<tr>
<td>{$row->devices}</td>
<td>{$row->description}</td>
<td>{$row->room}</td>
<td><input type='radio' name='radiobutton' id='myCheck'></td>
<td><input type='radio' name='radiobutton' id='myCheck' checked='checked'></td>
<!-- <td>{$device_status->status}</td> -->
<td>Delete
Edit</td>
</tr>
END;
}
}
echo $content;
I've been trying different methods such as using <td><input type='radio' name='$row->id' id='myCheck'></td>
But have not gotten it to work. Any help on how to solve this issue is greatly appreciated.
Thank you!
If you want the unique names for all the checkboxes generated you can have them by just incrementing $i for each row.
res = $db->query($query);
if ($res->num_rows > 0) {
$i = 0;
while ($row = $res->fetch_object()) {
$query = "SELECT * FROM device_status
WHERE device = ($row->id)";
$status = $db->query($query);
$device_status = $status->fetch_object();
$content .= <<<END
<tr>
<td>{$row->devices}</td>
<td>{$row->description}</td>
<td>{$row->room}</td>
<td><input type='radio' name='radiobutton<?php echo $i?>' id='myCheck'></td>
<td><input type='radio' name='radiobutton<?php echo $i?>' id='myCheck' checked='checked'></td>
<!-- <td>{$device_status->status}</td> -->
<td>Delete
Edit</td>
</tr>
END;
$i++;
}
}
echo $content;
If you do not care about the name of the radio button, you could use a "php random number generator", each row you asign a new random number to your radio button name:
<?php $x = rand(5, 100000); ?> <input type='radio' name='<?php echo $x; ?>' id='myCheck'>

How to select data from database and sum the column of the row selected also display in page using php?

I am trying to sum up the column of the row selected from the database and displays the result under the table display in my website. I am using new to PHP coding. Please help me. Below is my code:
Below the submit button, is a table where it will display the result of the search.
<form action="ViewAcc.php" method="get" >
Invoice/Check No.:<input type="text" name="rcchk">
<br>
OR
<br>
Retailer Name :<input type="text" name="rtsr">
<br>
<button class="button-special" value="Submit">SUBMIT</button>
</form>
<br>
<div class="9u 12u(mobile) important(mobile)">
<section align="left">
<table cellpadding="2px" cellspacing="2px" width="50%">
<tr><th>Invoice/Check No.</th><th>Retailer</th><th>Credit/Debit</th>
<th>Purpose</th></tr>
<?php
while($row = mysql_fetch_array($result)){
echo "<tr><td>" . $row['rcchk'] . "</td><td>" . $row['rtsr'] . "</td><td>"
. $row['crdbt'] . "</td><td>" . $row['purpose'] . "</td></tr>";
//$row['index'] the index here is a field name
}
?>
</table>
<table>
<tr><th></th><th>Total</th><th><?php echo $sum?></th><th></th></tr>
</table>
Below here is my PHP code:
<?php
include ('dbase.php');
$rcchk = $_GET['rcchk'];
$rtsr= $_GET['rtsr'];
$query = "SELECT * , sum(crdbt) as total FROM account WHERE rcchk='$rcchk' OR rtsr='$rtsr'";
$result = mysql_query($query);
echo "<table>"; // start a table tag in the HTML
include('ViewAccount.php');
include('ViewAccount_2.php');
mysql_close();
?>
How can I calculate the sum of the Credit/Debit column especially when I have selected only specific rows(based on the Invoice No. or Retailer Info) and where can I place the codes? Please help me.
<?php
$conn = mysqli_connect("localhost","root","","dbname");
$query = "SELECT * FROM `tablename` WHERE WHERE rcchk='$rcchk' OR rtsr='$rtsr'";
$sql = mysqli_query($conn,$query);
$sum = 0;
//echo $sum before the loop and give it value 0.
while($row = mysqli_fetch_array($sql)){
$sum += $row['crdbt'];
}
echo $sum;
?>

Selection box insert multiple times in database

This is what the page looks like:
And this is what the database looks like:
Now, I had this all working with textfields. (When you press save, the text fields get inserted in the bogie_nr.
Now, I don't want to have text fields but checkboxes.
So, if I select the first 2 checkboxes, and press save. I want the database to insert the number 1 by the axle_nr 1 and 2.
Now, I want the first 2 boxes to be disabled (So you can't check them again).
Now when you select the 3rd and 4th box, and press save. I want the database to insert the number 2 by the 3rd and 4th axle_nr.
When everything is filled in, I want a button that redirects me to a new page.
How do I do this?
Code (for the checkboxes only):
<tr>
<?php
$show_axle = $database->bogies($_GET['train_id']);
foreach($show_axle as $bogiebox){ ?>
<input type='hidden' name='bogie_id[<?php echo $bogiebox['bogie_id']?>]' value='<?php echo $bogiebox['bogie_id']?>'>
<td>
<input type='checkbox' id="bogie_axle_fields" name='bogie_nr[<?php echo $bogiebox['bogie_id']?>]' placeholder = "enter bogie number">
</td>
<?php
}
?>
</tr>
Function:
function bogies($id){
$sql = "SELECT * FROM bogie WHERE train_id = :id2";
$sth = $this->pdo->prepare($sql);
$sth->bindParam(":id2", $id, PDO::PARAM_STR);
$sth->execute();
return $sth->fetchAll();
}
EDIT:
Behind my save button is right now a page: end_result.php . Right there I have a function:
function update_bogie($id) {
$sql = "UPDATE bogie SET bogie_nr = :bogie_nr WHERE bogie_id = :bogie_id";
$sth = $this->pdo->prepare($sql);
$sth->bindParam(':bogie_id', $id, PDO::PARAM_INT);
$sth->bindParam(":bogie_nr", $_POST['bogie_nr'][$id], PDO::PARAM_STR);
$sth->execute();
}
This updates the bogie table (Works when I change the checkboxes to textfields)
What i want now:
Checkboxes. When I check the first 2 boxes, and press save. I want the number 1 to be inserted 2 times for axle 1 and 2 in the database.
After that, I want the first 2 boxes to be disabled selected. So you can't select them once again.
EDIT:
What the ids look like:
THE ALMOST WORKING EDIT:
Okay, so the checkboxes now insert in the database. Also they are disabled when they are inserted in the database.Only a few problems now:
When i insert them for the first time. The value = 1. But on the
2nd insert it also is 1. while it should be 2.
I need to refresh the page in order to see wich select boxes are
disabled. I want this to happen immediately.
When i insert new values. the old (Disabled one) go back to NULL. But it should keep the old value.
Code i have now:
<form method='POST'>
<input type="hidden" value="true" id="y" name="y">
<div id="axle_bogie_border">
<div id="train_adjusted">
<h2>
Train
</h2>
</div>
<table id="distance_margin">
<div id="bogiebox">
<tr>
<?php
$x = 1;
foreach($show_axle as $bogiebox){ ?>
<input type='hidden' name='bogie_id[<?php echo $bogiebox['bogie_id']?>]' value='<?php echo $bogiebox['bogie_id']?>'>
<td>
<?php
if($bogiebox['bogie_nr'] == ''){
?>
<input type='checkbox' id="bogie_axle_fields" value="<?= $x ?>" name='bogie_nr[<?php echo $bogiebox['bogie_id']?>]' placeholder = "enter bogie number"></td>
<?php
}
else{
?>
<input type='checkbox' id="bogie_axle_fields" checked disabled value="<?= $x ?>" name='bogie_nr[<?php echo $bogiebox['bogie_id']?>]' placeholder = "enter bogie number"></td><?php } }
?>
</tr>
</div>
</table>
<input type='submit' id="add_train_button1" value='Save'>
<?php
if(isset($_POST['y'])){
$validbogies = false;
//validate
if(($_POST['bogie_id']) >0){
if($_POST['bogie_id'] >0){
$validbogies = true;
}elseif($_POST['bogie_id'] <= 0){
echo "Error!";
}
else{
echo "Error!." . "<br>";
}
}else{
echo "Error!" . "<br>";
}
//If valid, then insert.
if($validbogies){
foreach($_POST['bogie_id'] as $id) {
$update_axle = $database->update_bogie($id);
}
$x++;
unset($_POST['y']);
echo "Yea! Things have been moved to the database :)";
}
}
?>
</div>
</form>
And the function is still the same as the old one.
EDIT:
Here a example:
<?php
$show_axle = $database->bogies($_GET['train_id']);
// First question : When everything is filled in,
// i want a button that redirects me to a new page.
if(count($show_axle) == 4)
echo "<button type=\"button\" onClick=location.href=''>Click Me!</button>";
// Second question :
// WE display the missing checkboxes
// We will display until we found the first value axle_nr
// (i.e. the checkbox the user click last time)
// when we found we need to move to the next value of axle_nr
else
{
$j = 0;
for($i = 0; $i < 4; ++$i)
{
if($show_axle[$j]['axle_nr'] != ($i + 1))
{
echo "<input type='hidden' name='bogie_id[" .
$bogiebox['bogie_id']. "]' value='" .
$bogiebox['bogie_id'] . "'><td>";
echo "<input type='checkbox' id='bogie_axle_fields'
name='bogie_nr[" . $bogiebox['bogie_id'] .
"]' placeholder='enter bogie number'></td>";
}
else
++$j;
}
?>
That should do it (mb some mistakes on echo but algorithm is ok).
In the code behind your save button try this: (I am assuming the id's for your checkboxes are like this: bogie_nr[455]
function update_bogie($id) {
$sql = "UPDATE bogie SET bogie_nr = :bogie_nr WHERE bogie_id = :bogie_id";
$sth = $this->pdo->prepare($sql);
$sth->bindParam(':bogie_id', $id, PDO::PARAM_INT);
if(isset($_POST['bogie_nr' . '[' . $id .']' ]){
$sth->bindParam(":bogie_nr", $_POST['bogie_nr' . '[' . $id .']' ], PDO::PARAM_STR);
}
else {
$sth->bindParam(":bogie_nr", 'NULL', PDO::PARAM_STR);
}
$sth->execute();
}
EDIT FOR CORRECT NUMBER:
Mitch to get your number try doing a query like this:
SELECT COUNT(*)
FROM bogie
WHERE train_id = #youridhere;
This will return you the amount of bogies you already have for that train, just do +1 or +2 depending on how many elements you are adding (use a counter in your for loop) and you have your correct number to insert

php modify database from html table select by checkbox

Good morning everybody
I made a table in html that contains users and the select box contains profiles.
I want to assign every users profile in database according to the profile selected in html.
My table in html contains checkbox next to every user. I want every user that is checked to be assigned.
<form action="PHP/modifier.php" method="POSt">
<table>
<thead>
<tr>
<th><input type="checkbox" id="checker" name="all"></th>
<th>Username</th>
<th>Nom</th>
<th>Prenom</th>
</tr>
</thead>
<?php
$query="SELECT Username,Nom,Prenom from user";
$result = mysql_query($query);
$num = mysql_num_rows($result);
for ($i = 0; $i < $num; $i++){
$row =mysql_fetch_array($result);
$Username = $row['Username'];
$Nom = $row['Nom'];
$Prenom = $row['Prenom'];
echo "<tr id='row'>";
echo "<td><input type='checkbox' id='check' name='check'".$Username."></td>";
echo"<td>".$Username."</td>";
echo "<td>".$Nom."</td>";
echo "<td>".$Prenom."</td>";
echo "<td><div id='MAJ'>";
echo "</div></td>";
echo "</tr>";
}
?>
<h2>Selectionner l'utilisateur et le profile</h2>
<select name="profile" id="profilez" required>
<option>Injecteur</option>
<option>Utilisateur</option>
<option>Administrateur</option>
<option>Utilisateur superieur</option>
<input type="submit" value="Associer">
</form>
In the modifer.php
I want to make update function to update users but how to get information from checked cases in the html table?
I already wrote this
<?php
include "functions.php";
$profile=$_POST['profile'];
$Username=$_POST['Username'];
$query="UPDATE user SET profile = '$profile' WHERE Username = '$Username' " ;
?>
I don't know how to do it.
thank you so much and sorry for my bad english.
there are different ways to do it. but lets go with your way
on you modifer.php page make another query to get all user names
$row =mysql_fetch_array($result);
foreach ($row as $value)
{
if (isset($_POST['check'.$value['username']]))
{
$profile = $_POST['profile'];
$Username = $POST['check'.$value['username'];
$query="UPDATE user SET profile = '$profile' WHERE Username = $value['username'] " ;
}
}

Change price variable based on a dropdown selection with php and jquery

Problem: How can i get the selected price from a dropdown menu and use it instead of the original price of the current product stored in the database?
My approach: I've been able to update a label with the selected price, but I still need to override the current price of the product. I'm pretty clueless right now.
Additional information: The current price saved in the database is $price which need to be overridden by either $prijshalf or $prijsheel that are both also stored in the database.
The JQuery Code for updating the label:
<script type="text/javascript">
$(document).ready(function() {
$('.dropdown').change(function() {
var price = 0;
$('.dropdown').each(function() {
if($(this).val() != 0) {
price = parseFloat($(this).val());
}
});
$('#costLabel').text('€ ' + price.toFixed(2));
});
});
</script>
This code block gets the value of the selected dropdown menu item and puts it in the label #costLabel
The PHP Code for rendering the products:
$product_list = "";
while($row = mysql_fetch_array($results)){
$id = $row["id"];
$product_name = substr($row["product_name"],0,25);
$price = $row["price"];
$category = $row["category"];
$subcategory = $row["subcategory"];
$beschrijving = substr($row["details"],0,25);
$afbeelding = '<img src="inventory_images/' . $id . '.jpg" alt="' . $product_name . '" width="50" height="50" />';
$dropdown = $row["dropdown"];
$dropdown2 = $row["dropdown2"];
$prijshalf = $row["prijshalf"];
$prijsheel = $row["prijsheel"];
if($dropdown != "" || $dropdown2 != ""){
$dropdownshow = "<select name='dropdown' id='dropdown' class='dropdown'>
<option name='prijshalf' value='$prijshalf'>$dropdown</option>
<option name='prijsheel' value='$prijsheel'>$dropdown2</option>
</select>";
}
else{
$dropdownshow = "";
}
$product_list .= "<div class='produkt'>
<div class='hardlopers'>
$afbeelding
<div class='subinfo'>
<span class='prijs-info'>Prijs:</span><span class='prijs'><label id='costLabel' name='costLabel'>$price</label> </span>
<span class='productnaam'>$product_name</span>
<span class='dropdown'>
$dropdownshow
</span>
<form id='form1' name='form1' method='post' action='homepage.php#redirect'>
<input type='hidden' name='pid' id='pid' value='$id' />
<input type='submit' name='button' id='button' value='' />
</form>
<span class='info'></span>
</div>
</div>
</div>
";
}
// Prints out the products to screen
echo $product_list;
I can't see how is your process of adding an item to the cart, so i can't tell you how. But you can try to move the dropdown into the <form> tag, later with php you get the value and if it is prijshalf or prijsheel do the math. The same with js, put the selected value of the dropdown in a hidden input within the <form> if you doesn't want the dropdown into the <form>, but i don't see why it shouldn't, send it to the server and do the math there. All is up to you.
Always use js just to show the info, always do the calculation and validation with php in the server for security reasons.
Happy coding

Categories