My goal:
To change my MySql table that looks like this:
role_permission:
role_id permissions_id
2 1
1 3
1 4
1 5
1 2
Based upon the HTML Code of this:
<div class="element">
<label for="permissions">Permissions:</label>
<input type="hidden" name="permissions[1]" value="false" checked="">
<label>
<input type="checkbox" name="permissions[1]" value="true" checked=""> canPushAPK</label>
<input type="hidden" name="permissions[2]" value="false">
<label>
<input type="checkbox" name="permissions[2]" value="true"> canBeCool</label>
<input type="hidden" name="permissions[3]" value="false" checked="">
<label>
<input type="checkbox" name="permissions[3]" value="true" checked=""> canEditSettings</label>
<input type="hidden" name="permissions[4]" value="false" checked="">
<label>
<input type="checkbox" name="permissions[4]" value="true" checked=""> canManageRoles</label>
<input type="hidden" name="permissions[5]" value="false" checked="">
<label>
<input type="checkbox" name="permissions[5]" value="true" checked=""> canAddUser</label>
<input type="hidden" name="permissions[6]" value="false">
<label>
<input type="checkbox" name="permissions[6]" value="true"> canFoo</label>
<input type="hidden" name="permissions[7]" value="false">
<label>
<input type="checkbox" name="permissions[7]" value="true"> canTalk</label>
<input type="hidden" name="permissions[8]" value="false">
<label>
<input type="checkbox" name="permissions[8]" value="true"> canTest</label>
<input type="hidden" name="permissions[9]" value="false">
<label>
<input type="checkbox" name="permissions[9]" value="true"> canPoo</label>
</div>
<input type="hidden" name="roleId" value="1">
View as JSFiddle.
Then based off what values are checked for "roleId" = 1, it inserts into the DB. for all unchecked, it deletes this row.
IE:
If all are checked, it will look like:
role_permission:
role_id permissions_id
2 1
1 1
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
What am I thinking:
Two queries:
DELETE FROM role_permissions
WHERE role_id = ?
Then:
$query = $this->mysqli->prepare("INSERT INTO role_permission(role_id,permission_id) VALUES (?,?)");
$query->bind_param("ii", $roleId, $permissionId);
$roleId = $_POST['roleId'];
foreach ($_POST['permissions'] as $permissionId=> $value){
if ($value){
$query->execute();
}
}
Your approach will work. you seem to like HTML.
If you use an array of 'permission names' and whether acive or not, then the code is just foreach loops as follows:
Tested code: PHP 5.3.18, mysqli on windows xp (Oi, stop laffin')
<?php // Q22950444
// program smarter not harder...
// arrays are your friend...
$allPermissions =
array('canPushAPK' => false, "canBeCool" => false, "canEditSettings" => false,
"canManageRoles" => false, "canAddUser" => false, "canFoo" => false,
"canTalk" => false, "canTest" => false, "canPoo" => false);
$mysqlhost = 'localhost';
$mysqluser = 'test';
$mysqlpass = 'test';
$myDBname = 'testmysql';
$mysqli = new mysqli($mysqlhost, $mysqluser, $mysqlpass, $myDBname);
if (!empty($_POST['goForIt'])) {
if (!empty($_POST['permissions'])) {
foreach($_POST['permissions'] as $permissionName) {
if (isset($allPermissions[$permissionName])) { // test is valid permission
$allPermissions[$permissionName] = true;
}
}
}
// process db...
$sql = "delete from `role_permissions` where `role_id` = ?";
$deleteQuery = $mysqli->prepare($sql);
if ($deleteQuery === false) { // drat
die('deleteQuery: '. $mysqli->error);
}
$deleteQuery->bind_param('s', $_POST['roleId']);
$allOk = $deleteQuery->execute();
if (!$allOk) { // drat
die('deleteQuery: '. $deleteQuery->error);
}
$sql = "insert into role_permissions (role_id, permission_id) values (?, ?)";
$insertQuery = $mysqli->prepare($sql);
if ($insertQuery === false) { // drat
die('insertQuery: '. $mysqli->error);
}
foreach($allPermissions as $permissionName => $active) {
if ($active) {
// bind the variables to the ALREADY PREPARED query
$insertQuery->bind_param('is', $_POST['roleId'], $permissionName);
$allOk = $insertQuery->execute();
if (!$allOk) { // drat
die("insertQuery: $permissionName : {$insertQuery->error}");
}
}
}
echo "<br />role: {$_POST['roleId']}: now has:<br />";
foreach($allPermissions as $permissionName => $active) {
echo $permissionName, ' : ', $active ? '<strong>Yippee!</strong>' : 'sadly, no', '<br />';
}
}
?>
<form action="" method="post">
<div class="element"><!-- easy peasy way of sending out the current permissions -->
<label for="permissions">Permissions:</label>
<?php foreach(array_keys($allPermissions) as $permissionName): ?>
<div>
<label>
<input type="checkbox" name="permissions[]"
value="<?= $permissionName ?>"
<?= $allPermissions[$permissionName] ? 'checked="checked"' : ''; ?>
> <?= $permissionName; ?></label>
</div>
<?php endforeach; ?>
</div>
<input type="hidden" name="roleId" value="1">
<input type="submit" name="goForIt" value="Go For It!">
</form>
Related
I have no idea how to calculate total price of this subjects using php.
help me with it.
<div id="mydiv" style="display:none">
<input type="checkbox" name="subject[]" value="biology">biology<br>
<input type="checkbox" name="subject[]" value="physics">physics<br>
<input type="submit" value="Calculate" name="submit" class="wpcf7-submit">
</div>
<div id="mydiv1" style="display:none">
<input type="checkbox" name="subject[]" value="maths">maths<br>
<input type="checkbox" name="subject[]" value="science">science<br>
<input type="submit" value="Calculate" name="submit" class="wpcf7-submit">
</div>
I want to calculate price total of this checkboxes and store it in database with its names using php
php part
if(isset($_POST['subject']))
{
$classes=$_POST['subject'];
$prices = array(
'biology' => 60,
'physics' => 200
);
$sum = array();
$getkeys = array_keys($_POST);
foreach($prices as $key => $value)
{
if(in_array($key, $getkeys)) $sum[] = $value;
}
$ar=array_sum($sum);
echo $ar;
if($classes)
{
$subject = implode(',', $ar);
$query="INSERT INTO feedetails (subjects,price) VALUES ('".$subject."','".$price."')";
if(mysqli_query($conn,$query))
{
echo ("<SCRIPT LANGUAGE='Javascript'>
window.alert('Your fee has been updated.Please proceed to pay.');
window.location.href='payment.php';
</SCRIPT>");
}
}
It appears that your summing strategy was not working, there were numerous issues there including this:
$getkeys = array_keys($_POST);
which appears as an attempt to get the subjects submitted, however they are in their own sub-array of $_POST, i.e. $_POST['subject']
This gets you the summing of the price information you require, however you will need to test your database INSERT code and debug this to ensure you are storing the data required correctly.
if (!empty($_POST['subject'])) {
$prices = [
'biology' => 60,
'physics' => 200,
'maths' => 300,
'science' => 400,
];
$sum = 0;
foreach ($_POST['subject'] as $subject) {
if (!empty($prices[$subject])) {
$sum += $prices[$subject];
}
}
echo '<pre>';
echo '$sum ' . print_r($sum, true);
echo '</pre>';
exit;
// process database inserts here
}
Additionally, when testing your code I notice you had hidden the checkboxes, to resolve this, use the following:
<div id="mydiv">
<input type="checkbox" name="subject[]" value="biology">biology<br>
<input type="checkbox" name="subject[]" value="physics">physics<br>
<input type="checkbox" name="subject[]" value="maths">maths<br>
<input type="checkbox" name="subject[]" value="science">science<br>
<input type="submit" value="Calculate" name="submit" class="wpcf7-submit">
</div>
Try This may be help:
I am not doing all code just you asked for sum part.
Rest you can do Ask if any confusion.
HTML
<form method='post'>
<div id="mydiv" >
<input type="checkbox" name="subject[]" value="biology">biology<br>
<input type="checkbox" name="subject[]" value="physics">physics<br>
<input type="checkbox" name="subject[]" value="maths">maths<br>
<input type="checkbox" name="subject[]" value="social">social<br>
<input type="checkbox" name="subject[]" value="ssc">ssc<br>
<input type="submit" value="Calculate" name="submit"
class="wpcf7-
submit">
</div>
PHP
<?php
$classes =$_POST['subject'];
$prices = array('biology' => 60,'physics' =>
200,'maths'=>100,'ssc'=>40,'social'=>150);
$sum = 0;
echo 'Subject::Price<hr/>';
foreach($classes as $key=>$sub){
if(array_key_exists($sub,$prices)){
echo $sub.'::'.$prices[$sub]."<br />";
$sum = $sum+$prices[$sub];
}
}
echo '<hr/>';
echo $sum;
?>
OUTPUT
I am trying to show specific data if two variables are set in a form.
$retired = "";
$stolen = "";
if(isset($_POST['submit'])){
$retired = $_GET['showretired'];
$stolen = $_GET['showstolen'];
}
I have tried the bellow:
<?php }elseif(isset($_GET['showretired']) && (isset($_GET['showstolen'])){ ?>
Which does not work
<?php }elseif(isset($retired, $stolen)){
Which works when not set
<?php }elseif(isset($_GET['showretired'], $_GET['showstolen'])) {
This one only shows the retired part.
I am unsure of the best way to do this.
Here is the form:
<form>
<label>Show Retired Column </label><input type="checkbox" name="showretired">
<label class="space">Show Stolen Column </label><input type="checkbox" name="showstolen">
<input class="space" type="submit" name="submit" value="Refine">
</form>
This is how I am using the variable in the same file.
<?php }elseif(isset($_GET['showretired'], $_GET['showstolen'])) {
?>
<tr>
<th>Retired</th>
<th>Stolen</th>
</tr>
<?php }else{ ?>
<?php
if(isset($_POST['submit'])){
if(isset($_POST['showretired'])) {
$retired = $_POST['showretired'];
}
if(isset($_POST['showstolen'])) {
$stolen = $_POST['showstolen'];
}
if(isset($retired)){
echo $retired;
}
if(isset($stolen)) {
echo $stolen;
}
}
?>
<form action="" method="POST">
<label>Show Retired Column </label><input type="checkbox" name="showretired" value="The retired field">
<label class="space">Show Stolen Column </label><input type="checkbox" name="showstolen" value="The showstolen field">
<input class="space" type="submit" name="submit" value="Refine">
</form>
No method on the form means it will default to GET. Change the conditional and check your checkboxes.
<?php
if(isset($_GET['submit'])){
$foo = isset($_GET['foo']) ? true : false;
$bar = isset($_GET['bar']) ? true : false;
var_dump($foo);
var_dump($bar);
}
?>
<form>
<input type="checkbox" name="foo">
<input type="checkbox" name="bar">
<input type="submit" name="submit">
</form>
if(isset($_GET['submit'])){
if(isset($_GET['showretired']) && $_GET['showretired'] !="" && isset($_GET['showstolen']) && $_GET['showstolen'] !="" )
{
echo $retired." ".$stolen;
}
}
and form
<form>
<label>Show Retired Column </label><input type="checkbox" name="showretired" value="showretired" checked="checked">
<label class="space">Show Stolen Column </label><input type="checkbox" name="showstolen" value="showstolen" checked="checked">
<input class="space" type="submit" name="submit" value="Refine">
</form>
Hope it will help
I'm having trouble with the array results in my php. My first problem is this :
It shows everything even if the checkbox isn't checked. My second problem is that it won't insert the values to the database even though it's connected to the database (as you can see in the previous screenshot, it says "connected successfully").
This is my html form:
<form method="POST">
<input type="hidden" name="item[]" value="cupcake">
<input type="text" name="items" value="cupcake" readonly><br>
<b>Price :</b> <span name="price" value="3.00">$17.00</span><br>
Quantity: <input tabindex="1" name="quantity[]" min="0" max="5" type="number" class="quantity" value="1" /><br>
<input tabindex="1" name="checkbox[]" type="checkbox" value="17" /><span>Add to Cart</span></label></div></div></td><br>
<input type="hidden" name="item[]" value="cake">
<input type="text" name="items" value="cake" readonly><br>
<b>Price :</b> <span name="price" value="20.00">$20.00</span><br>
Quantity: <input tabindex="1" name="quantity[]" min="0" max="5" type="number" class="quantity" value="1" /><br>
<input tabindex="1" name="checkbox[]" type="checkbox" value="20" /><span>Add to Cart</span></label></div></div></td><br>
<input type="submit" name="insertBT"><br>
</form>
PHP:
if(isset($_POST['insertBT']))
{
class db_conn
{
public function create_conn($servername, $username, $password, $db)
{
global $conn;
$conn = new mysqli ($servername, $username, $password, $db);
}
public function check_conn()
{
global $conn;
if($conn->connect_error)
{
die ("Connection Failed : " . $conn->connect_error);
}
else
{
echo ("Connected Successfully <br>");
}
}
public function insert()
{
if(isset($_POST['checkbox'])) {
foreach($_POST['checkbox'] as $check) {
$check = implode(',', $_POST['checkbox']);
$name = implode(',', $_POST['item']);
$quantity = implode(',', $_POST['quantity']);
}
echo $check . "<br>";
echo $name . "<br>";
echo $quantity . "<br>";
mysql_query("INSERT INTO purchases(Product, Quantity, Price) VALUES('$name', '$quantity','$check')");
}
}
}
$obj1 = new db_conn;
$obj1->create_conn("localhost","root","", "dbtest");
$obj1->check_conn();
$obj1->insert();
}
You shouldn't be using implode. That puts a comma-separated list of everything in the form into each row that you insert, and repeats this for every box that's checked. You should just insert one item in each row, by indexing the arrays.
However, when you have a checkbox in a form, it only submits the ones that are checked. The result of this is that the indexes of the $_POST['checkbox'] array won't match up with the corresponding $_POST['item'] and $_POST['quantity'] elements. You need to put explicit indexes into the checkbox names so you can relate them.
<form method = "POST">
<input type = "hidden" name = "item[]" value = "cupcake">
<input type = "text" name = "items" value = "cupcake" readonly><br>
<b>Price :</b> <span name = "price" value = "3.00">$17.00</span><br>
Quantity: <input tabindex="1" name="quantity[]" min="0" max="5" type="number" class="quantity" value="1" /><br>
<input tabindex="1" name="checkbox[0]" type="checkbox" value="17" /><span>Add to Cart</span></label></div></div></td><br>
<input type = "hidden" name = "item[]" value = "cake">
<input type = "text" name = "items" value = "cake" readonly><br>
<b>Price :</b> <span name = "price" value = "20.00">$20.00</span><br>
Quantity: <input tabindex="1" name="quantity[]" min="0" max="5" type="number" class="quantity" value="1" /><br>
<input tabindex="1" name="checkbox[1]" type="checkbox" value="20" /><span>Add to Cart</span></label></div></div></td><br>
<input type = "submit" name = "insertBT"><br>
</form>
Then your PHP code can be like this:
$stmt = $conn->prepare("INSERT INTO purchases (Product, Quantity, Price) VALUES (?, ?, ?)");
$stmt->bind_param("sis", $name, $quantity, $price);
foreach ($_POST['checkbox'] as $i => $price) {
$name = $_POST['name'][$i];
$quantity = $_POST['quantity'][$i];
$stmt->execute();
}
BTW, putting the prices in your HTML seems like a bad idea. Nothing stops the user from modifying HTML using the web inspector before they submit the form, so they could lower the price. You should get the prices from the database when processing the form.
Also, notice that in your original code you opened the database connection using MySQLi, but then you tried to do the insert using mysql_query instead of $conn->query(). You can't mix APIs like that; myql_query can only be used when you open the connection with mysql_connect.
I have an issue where I need to loop the number of check boxes on a form submit. Foreach check box that is looped I need to then insert data into the database.
How Would I go about looping over the amount of check boxes that have being passed via form submit?
My code is as follows:
Form:
<form action="createChallenge.php" method="post" name="chalCreate">
Challenge Name:<input type="text" name="chalName" />
<br />
Challenge Target:<input type="text" name="chalTarget"/>
<br />
End Date:<input type="text" name="chalDate">
<br />
<!-- Needs a jquery datepicker -->
Select Friends: <br />
<?php
$selFriend = $conn->prepare("SELECT * FROM Friends WHERE UserID = '$userID' AND Friend = 'y' ORDER BY FriendName ASC");
$selFriend->execute();
foreach($selFriend as $row){
?>
<input type="checkbox" name="test" value="<?php echo $row['FriendID'] ?>"><?php echo $row['FriendName'] ?><br>
<?php
}
?>
<br />
<button type="submit">Create Challenge</button>
</form>
PHP to handle the form:
<?php
if(isset($_POST['test']))
{
$i = 0;
foreach($_POST['test'] as $checked)
{
echo $friend = $checked;
$i++;
}
echo $name = $_POST['chalName'];
echo $target = $_POST['chalTarget'];
echo $date = $_POST['chalDate'];
echo $friend = $_POST['test'];
echo $setby = $_COOKIE['userID'];
$create = $conn->prepare("INSERT INTO Challenge ( chalSetBy, chalName, chalTarget, chalDate ) VALUES ('$setby', '$name', '$target', '$date') ");
$create->execute();
if($create)
{
echo "Challenge made successfully";
}
else
{
echo "There was a problem";
}
}
?>
I thought doing the following would echo out data, but it didn't, it only selected the last check box:
$i = 0;
foreach($_POST['test'] as $checked)
{
echo $friend = $checked;
$i++;
}
Make an array of your checkbox in HTML page like as below,
<form name="frm" method="post">
<input type="checkbox" value="1" name="test[]">
<input type="checkbox" value="2" name="test[]">
<input type="checkbox" value="3" name="test[]">
<input type="checkbox" value="4" name="test[]">
<input type="checkbox" value="5" name="test[]">
<input type="checkbox" value="6" name="test[]">
<input type="submit">
</form>
<?php
foreach($_POST['test'] as $key=>$value)
{
echo $value."<br>";
}
I have a comment BOX, which has 5 fields, one is name, email, RATE, comment, articleid.
Rate field is a radio type, which has 5 radio buttons with value 1,2,3,4,5. IF someone click on rate my product and it should save the rated value in databse. I'm using RATE as INT in database, It stores 0 in it, If i use RATE as TEXT in database, it stores "on" in database. It is not storing rating values like 1,2,3,4,5.
My form Code
<form action="manage_comments.php" method="post">
<span class="rating">
<input type="radio" class="rating-input" id="rate" name="rate" value="1">
<label for="rating-input-1-5" class="rating-star"></label>
<input type="radio" class="rating-input" id="rate" name="rate" value="2">
<label for="rating-input-1-4" class="rating-star"></label>
<input type="radio" class="rating-input" id="rate" name="rate" value="3">
<label for="rating-input-1-3" class="rating-star"></label>
<input type="radio" class="rating-input" id="rate" name="rate" value="4">
<label for="rating-input-1-2" class="rating-star"></label>
<input type="radio" class="rating-input" id="rate" name="rate" value="5">
<label for="rating-input-1-1" class="rating-star"></label>
</span>
<input type='hidden' name='articleid' id='articleid' value='<?php echo $_GET["id"]; ?>' />
<input type="submit" name="submit" value="Publish Now"></p>
</form>
My php Code
<?php
if( $_POST )
{
$con = mysql_connect("localhost","asfi","asfi");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("aw-tech", $con);
$post_rate = (isset($_POST['rate'])) ? $_POST['rate'] : '';
$articleid = (int)isset($_GET['id']);
if(!is_numeric($articleid))
die('invalid article id');
$sql="INSERT INTO `aw-tech`.`comment` (cid, name, email, website, comment, timestamp, rate, articleid) VALUES (NULL, '$_POST[name]', '$_POST[email]', '$_POST[website]', '$_POST[comment]', CURRENT_TIMESTAMP, '$post_rate', ".$articleid.")";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Comment Saved";
mysql_close($con);
}
?>
Secondly My articleid saves always 0.. my page id is .php?id=49 , it is 49 but if i made comment on that page, It saves my article ID always 0.
articleid & rate Both are INT in database, I have used them as TEXT too in database but didn't work
I think I found your problem. Change form declaration to:
<form action="manage_comments.php" method="post">
Remove row:
<input type='hidden' name='articleid' id='articleid' value='<?php echo $_GET["id"]; ?>' />
the Then PHP code from:
$post_rate = (isset($_POST['rate'])) ? $_POST['rate'] : '';
$articleid = (int)isset($_GET['id']);
to:
$post_rate = (isset($_POST['rate'])) ? $_POST['rate'] : 0;
$articleid = (int)isset($_GET['id']) ? $_GET['id'] : 0;
And for debug add this after the $sql variable and insert into a comment here:
print_r($_GET);
print_r($_POST);
echo $sql;
Hope it works.
when you post the form in action you put : manage_comments.php
so the "id" be lost!
in action you can put : manage_comments.php?id=<?php=$_GET[id]?>
or
after submit form
use $_POST[articleid] not $_GET['id']
i think it supposes to be
$post_rate = (isset($_POST['rate'])) ? $_POST['rate'] : '';
$articleid = (int)isset($_POST['articleid']);