Let me present my code first:
<?php include ('header.php'); ?>
<h3>Extra menu items , van eigen pagina's</h3>
<!-- zet menu onderdelen aan of uit -->
<?php
if ($_POST['submit'] == 'Verzenden') {
$checkbox_vals = $_POST['np_menu_active_post']; // This will pass the selected checkbox values as an array
//if(count($checkbox_vals) > 0) {
// Loop it and update the values in DB
foreach( $checkbox_vals as $key ){
$updatequery = "UPDATE custompage set np_menu_active = '$key'";
mysql_query($updatequery) or die("Couldn't get file list");
}
//}
?>
<meta HTTP-EQUIV="Refresh" CONTENT="0"; URL="<?php echo $_SERVER['PHP_SELF'];?>">
<?php
}
?>
<?php
$dbQuery_custom_toggle = "SELECT * ";
$dbQuery_custom_toggle .= "FROM custompage";
$result_custom_toggle = mysql_query($dbQuery_custom_toggle) or die("Couldn't get file list");
while($row = mysql_fetch_array($result_custom_toggle)) {
// $nptitel = $row['np_titel'];
// $nptekst = $row['np_tekst'];
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<input type="hidden" name="np_menu_active_post[]" value="0" />
<?php echo $row['np_menu_titel'];?> <input type="checkbox" name="np_menu_active_post[]" value="1" <?php if($row['np_menu_active'] == "1"){echo 'checked="checked"';}?> /> <br />
<?php
}
?>
<input type="Submit" name="submit" value="Verzenden" class="btn-primary">
</form>
<!-- einde menu toggles -->
<br />
<br />
So im trying to make this form write the 1 value or 0 value based upon the checkboxed to the mysql db.
Its partly working, when i select the last checkbox, it checks all, and writes that to the db.
With the foreach loop you update your db in the same field with each checkbox, so the last checkbox is the only thing that is left.
Depending on the desired result, you need to differ the column (so np_menu_active) for each checkbox, or need to add a WHERE condition (as Rick said) to differ the row.
E.g. If you would like to save the checkbox settings for multiple users, you would create a column for each checkbox and a row for each user.
Related
im triyng to figure out a problem for days and have some progress but im stuck with some checkbox page.
So the "project" is some kind of "online car stand" and im stuck in the insert car part.
I got the html and php for insert a car into the sql table.
Then after the car i have a link to insert extras of the car, like abs,cruise control, gps ...etc...
The Html is something like this:
<?php
include "verifica.php";
?>
<html>
<head>
<link rel="stylesheet" href="styles.css">
<title> Stand Automovel
</title>
</head>
<body>
<form action="extras.php" method="POST">
<P class="style2"style2"> Extras:
<div class="style2">
<input type="checkbox" name="chk" value="1">GPS<br>
<input type="checkbox" name="chk" value="2">ABS<br>
<input type="checkbox" name="chk" value="3">Computador De Bordo<br>
<input type="checkbox" name="chk" value="4">Ar Condicionado<br>
</div>
<P> </P>
<P><INPUT TYPE=submit VALUE="Submeter"> <INPUT TYPE=reset VALUE="Limpar"> </P>
<P> </P>
</form>
</body>
The php page code is this one:
<html>
<head>
<meta charset="UTF-8">
<title>Inserir Automoveis</title>
</head>
<body>
<?php
include "connect.php";
$sql = "INSERT INTO extra (extra.id_carro,extra.id_lista_extra) SELECT carro.id_extras , ? FROM carro,lista_extra,extra ORDER BY carro.id_carro DESC LIMIT 1";
if($teste= $mysqli->prepare($sql)) {
$teste->bind_param("s",$_REQUEST["extra.id_lista_extra"]);
$teste->execute();
if ($teste>affected_rows == -1) {
echo $print;
echo "<p>". $mysqli->error. "</p>";
}
else {
echo "<sp>Carro inserido com sucesso!</p>";
}
}
?>
The goal with that $sql is to get the last id from last car inserted on row cars and add 1 extra to him passed by the check box.
i have tried just with 1 box because i read that if a checkbox was unchecked pass "null"argument.
I tried already with diferent aproaches. My final goal is create a for cicle that creates the number of rows in table extra for each number of extra checked in my checkbox.
(i tried something like this but with no sucess)
$checkbox1 = $_POST['chk'];
if($_POST["Submit"]=="Submit"){
for ($i=0;$i<sizeof ($checkbox1)$i++){
$sql = "INSERT INTO extra (id_lista_extra) values('".$checkbox1[$i]."')";
mysql_query($sql) or die(mysql_error());
}
}
i got some php errors on that $i .
If someone can give me a hint i would appreciate.
Thanks
Here is an example all you would have to do is change the names inside these $_POST variables as well as change your HTML checkbox names to have a [] after them. e.g
<input type="checkbox" name="chk[]" value="1">GPS<br>
<input type="checkbox" name="chk[]" value="2">ABS<br>
$cat_array = array();
if(isset($_POST['chk'])){
if(is_array($_POST['chk'])) {
foreach($_POST['chk'] as $value){
array_push($cat_array, $value);
}
}else{
$value = $_POST['chk'];
array_push($cat_array, $value);
}
}
Now all these values are in an ARRAY. Do as you please with them, loop through them, call them by there indexes, etc..
Here's my case (relatively new on php): I got a page "zoek_form.php" where you can enter 2 search values in a form (naam and categorie). When submitted, page "zoek.php" is loaded and a search will be performed (mysql 5.6). To perform the search the 2 values are obtained from the 2 session variables. So far so good, the search works and the rows are retrieved.
But now I want the user to be able to make a sequence (via ORDER BY) in zoek.php, based on a dropdown list. The selected value will be stored in a 3rd session variable. But now the problem: when selecting a sequence and submit the form, the first 2 session values are lost. I'm puzzled why. The essence of session variables is just storing the values and to be able to use them over and over again? (till they are overwritten or killed).
Of course I use session_start(); at the beginning of the php-script (otherwise it would not have worked at all ;-). Any ideas?
Here's zoek_form.php:
<html>
<head>
<title>Zoeken</title>
</head>
<body>
<?php session_start(); ?>
<form name="form1" method="POST" action="zoek.php">
<table border="0">
<tr><td>Naam product:</td>
<td><input type="text" size="50" name="form_naam"></td></tr>
<tr><td>Categorie:</td>
<td><input type="text" size="50" name="form_cat"></td></tr>
<tr><td></td>
<td align = "right"><input type="submit" name="B1" value="Zoeken">
</td></tr>
</table>
</form>
</body>
</html>
Here's zoek.php:
<html>
<head>
<title>Zoeken</title>
</head>
<body>
<form name="form1" method="POST" action="">
<table border="0">
<tr><td>Sorteer op:</td>
<td><select name="form_sort">
<option value="Naam">Naam</option>
<option value="Categorie">Categorie</option>
</select></td>
<td><input type="submit" name="B1" value="Sorteer"></td></tr>
</table>
</form>
<?php
session_start();
require_once 'test_connect.php';
$_SESSION['form_naam'] = $_POST['form_naam'];
$_SESSION['form_cat'] = $_POST['form_cat'];
$_SESSION['form_sort'] = $_POST['form_sort'];
// The 3 lines below were used to check whether session vars were set
// echo $_SESSION['form_naam'];
// echo $_SESSION['form_cat'];
// echo $_SESSION['form_sort'];
function sorteren() {
global $sorteer;
$sorteer = $_SESSION['form_sort'];
if ($sorteer == "Naam") {
$sorteer = "ORDER BY naam";
}
else {
$sorteer = "ORDER BY categorie";
}
}
// Put values from zoek_form.php in vars.
$naam = $_SESSION['form_naam'];
$cat = $_SESSION['form_cat'];
// Check if user has set a sequence. If yes: call function sorteren(),
// if no: leave var $sorteer empty.
if (isset($_SESSION['form_sort'])) {
sorteren();
}
else {
$sorteer = "";
}
// Get rows from table product
$sql = "SELECT * FROM product WHERE naam LIKE '$naam%' OR categorie
LIKE '$cat%' $sorteer";
$result = $conn -> query($sql);
if ($result->num_rows > 0) {
// here code to retrieve rows etc.
}
// Give result free
$result -> free();
// Close connection
$conn -> close();
?>
</body>
</html>
Your form in zoek.php doesn't contain form_naam and form_cat so when you run
$_SESSION['form_naam'] = $_POST['form_naam'];
$_SESSION['form_cat'] = $_POST['form_cat'];
It sets those values to null. If you want to retain those values you could try passing them back again in the form with hidden input fields
<input type="hidden" name="form_naam" value="<?= $_SESSION['form_naam'] ?>">
<input type="hidden" name="form_cat" value="<?= $_SESSION['form_cat'] ?>">
Another way to prevent overwriting the session values is to only change them if the $_POST values are set
if(isset($_POST['form_naam']) && isset($_POST['form_cat'])) {
$_SESSION['form_naam'] = $_POST['form_naam'];
$_SESSION['form_cat'] = $_POST['form_cat'];
}
I'm working on a PHP dynamic form based on the tutorial found here:
http://blog.calendarscripts.info/dynamically-adding-input-form-fields-with-jquery/
Here is the table layout:
ID | depratecat | MinBalance | InterestRate | APY | suborder
inputted rows
ID is auto-increment.
The form fields for depratecat are visible in my code only for testing; normally the user would not be able to change this value. The value of depratecat would come from a POST value from a previous page and should be the same for all rows inputted or edited in this instance. For testing I'm declaring the value as 14.
My test page is here:
http://www.bentleg.com/fcsbadmin/dynamictest4.php
The problems:
The "Add row" script function does not work and the code won't insert new data thru form; nothing happens. No errors are shown in the Chrome console
Editing or deleting pre-existing rows seems to work.
Below is my complete test code minus the connection, Some print_r added to show the array.:
<?php
error_reporting(E_ALL);
// Connect to the DB
$link = myconnection stuff
$new_depratecat='14'; //for testing
// store in the DB
if(!empty($_POST['ok'])) {
//first delete the records marked for deletion. Why? Because we don't want to process them in the code below
if( !empty($_POST['delete_ids']) and is_array($_POST['delete_ids'])) {
// you can optimize below into a single query, but let's keep it simple and clear for now:
foreach($_POST['delete_ids'] as $id) {
$sql = "DELETE FROM tblRates_balance WHERE id=$id";
$link->query($sql);
}
}
// now, to edit the existing data, we have to select all the records in a variable.
$sql="SELECT * FROM tblRates_balance WHERE depratecat='$new_depratecat' ORDER BY suborder";
$result = $link->query($sql);
// now edit them
while($rates = mysqli_fetch_array($result)) {
// remember how we constructed the field names above? This was with the idea to access the values easy now
$sql = "UPDATE tblRates_balance SET
MinBalance='".$_POST['MinBalance'.$rates['id']]."',
InterestRate='".$_POST['InterestRate'.$rates['id']]."',
APY='".$_POST['APY'.$rates['id']]."',
suborder='".$_POST['suborder'.$rates['id']]."'
WHERE id='$rates[id]'";
$link->query($sql);
}
// (feel free to optimize this so query is executed only when a rate is actually changed)
// adding new
if($_POST['add_MinBalance']!= "") {
//echo ("OKAY");
$sql = "INSERT INTO tblRates_balance (depratecat, MinBalance, InterestRate, APY, suborder) VALUES ('$new_depratecat','".$_POST['add_MinBalance']."', '".$_POST['add_InterestRate']."', '".$_POST['add_APY']."','".$_POST['add_suborder']."' );";
$link->query($sql);
}
}
// select existing rates here
$sql="SELECT * FROM tblRates_balance where depratecat='$new_depratecat' ORDER BY suborder";
$result = $link->query($sql);
?>
<html>
<head>
<title>Example of dynamically adding row and inserting into mySql with jQuery</title>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
</head>
<body>
<div style="width:90%;margin:auto;">
<h1>Example of dynamically adding row and inserting into mySql with jQuery </h1>
<form method="POST" id="newrate">
<div id="itemRows">
Minimum Balance: <input type="text" name="add_MinBalance" size="30" />
Interest Rate: <input type="text" name="add_InterestRate" />
APY: <input type="text" name="add_APY" />
Order: <input type="text" name="add_suborder" size="2"/>
<< Add data and click on "Save Changes" to insert into db. <br>
You can add a new row and make changes to existing rows all at one time and click on "Save Changes."
New entry row will appear above after saving.
<?php
// Next section does updating. let's assume you have the rate data from the DB in variable called $rates
while($rates = mysqli_fetch_array($result)): ?>
<p id="oldRow<?=$rates['id']?>">
<?php //echo $rates['id']; ?>
Minimum Balance: <input type="text" name="MinBalance<?=$rates['id']?>" value="<?=$rates['MinBalance']?>" />
Interest Rate: <input type="text" name="InterestRate<?=$rates['id']?>" value="<?=$rates['InterestRate']?>" />
APY: <input type="text" name="APY<?=$rates['id']?>" value="<?=$rates['APY']?>" />
Order: <input type="text" name="suborder<?=$rates['id']?>" value="<?=$rates['suborder']?>" />
<input type="checkbox" name="delete_ids[]" value="<?=$rates['id']?>"> Mark to delete</p>
<?php endwhile;?>
</div>
<p><input type="submit" name="ok" value="Save Changes"></p>
</form>
</div>
<script language="Javascript" type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'">Minimum Balance:<input type="text" name="add_MinBalance[]" value="'+frm['add_MinBalance[]'].value+'">Interest Rate:<input type="text" name="add_InterestRate[]" value="'+ frm['add_InterestRate[]'].value +'">APY:<input type="text" name="add_APY[]" value="'+frm['add_APY[]'].value+'">Order:<input type="text" name="add_suborder[]"value="'+ frm['add_suborder[]'].value+'"><input type="button" value="Remove" onclick="removeRow('+rowNum+')(this);"></p>';
jQuery('#itemRows').append(row);
frm['add_MinBalance[]'].value = '';
frm['add_InterestRate[]'].value = '';
frm['add_APY[]'].value = '';
frm['add_suborder[]'].value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
//}
</script>
</body>
</html>
The inputs in the initial form have names add_depratecat, add_MinBalance, add_InterestRate, add_APY, and add_suborder. When you add new rows, they have the same names, but with [] appended. So the original row creates single inputs, the added rows create array inputs, but they have the same names, and they conflict.
You should use the array form for the original inputs as well:
<form method="POST" id="newrate">
<div id="itemRows">
Dep_rate_cat:<input type="text" name="add_depratecat[]" size="30"/>
Minimum Balance: <input type="text" name="add_MinBalance[]" size="30" />
Interest Rate: <input type="text" name="add_InterestRate[]" />
APY: <input type="text" name="add_APY[]" />
Order: <input type="text" name="add_suborder[]" size="2"/>
so that they're consistent with the added rows.
Initially you are not adding [] in the form fields,
change <input type="text" name="add_depratecat" size="30"> to <input type="text" name="add_depratecat[]" size="30">, do the same for other fields as well.
And in foreach where you are inserting data to database use array $depratecat[] instead of string $depratecat
if(isset($_POST['add_depratecat'])) {
$depratecat = $_POST['add_depratecat']; ........
For debugging purpose write echo '<pre>'; print_r($_POST); OR var_dump($_POST); Instead of
echo '<pre>',print_r($_POST,true),'</pre>';.
Using WordPress, so PHP, HTML, CSS, JavaScript what is the best method of populating the results of a form upon submission? I could have a form with ddl, radio buttons, etc.
<form>
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
<input type="submit" value="Submit">
</form>
What is the best way of populating the results i.e. "67% of users are Female" and "30% ride bikes" on the same page once the submit button is triggered?
Try something along these lines:
script.php
----------
<html>
<body>
<form method=post action=script.php>
your form here...
</form>
<? if($_SERVER["CONTENT_LENGTH"]>0) {
//form was submitted to script, so process form inputs here and display results...
}
?>
</body>
</html>
<form action="phpfile.php" method="Post">
...form here
</form>
phpfile.php:
<?php
if(isset($_POST['sex'])){
$sex = $_POST['sex'];
}//etc..
//To show the result, simply echo it:
echo $sex;
You'll need some sort of storage system to be able to calculate the amount of each.
So what you would need to do is write a simple query where the value of the field is male or female. Then you can easily calculate it.
What you will need to do is add the form results to the database, then find the total number of results for both categories, then calculate the percent female and the percent bike.
The form page:
<html>
<?php
if(isset($_GET['status']) && $_GET['status'] == "values") {
//connect to DB and select table
$male = count( mysql_query("SELECT gender FROM Table WHERE gender='male'"));
$female = count (mysql_query("SELECT gender FROM Table WHERE gender='female'"));
$car = count (mysql_query("SELECT vehicle FROM Table WEHRE vehicle='car'"));
$bike = count (mysql_query("SELECT vehicle FROM Table WEHRE vehicle='bike'"));
$totalResults = $male + $female;
$totalVehicles = $car + $bike;
$percentFemale = 100 * ($female / $totalResults);
$percentFemale = number_format($percentFemale, 0);
$percentBike = 100 * ($bike / $totalVehicals);
$percentBike = number_format($totalBike, 0);
echo "<p>" . $percentFemale . "% of users are female. </p>";
echo "<p>" . $percentBike . "% of users use bikes. </p>";
} else { ?>
<form action="formProcessor.php" method="POST"><!-- You could also use GET -->
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
<input type="submit" value="Submit">
</form>
<?php } ?>
</html>
The formProcessor.php Page:
<?php
if(isset($_POST["sex"]) && isset($_POST['vehicle'])) {
//Connect to MySQL DB and select table here
$sex = $_POST['sex'];
$vehicle = $_POST['vehicle'];
mysql_query("INSERT INTO Table(sex, vehicle) VALUES($sex, $vehicle)"); //You may also want to add an id column, but...
//Close mysql connection
header("Location: /form.php?status=values");
die();
} else {
die("There was an error in your submission.");
}
?>
I think this answers your question, you've got a way to find the percent of female users and users on bikes. If you need that to be dynamic and show only the greater amount (or show both or something) just add a comment. This also assumes you are not using PDO, if you are, I can adjust the code. I just wrote the code, so I don't know for sure if it works, but here you go!
I am trying to create a "report" that can be filtered using a form on the top of the page. The options to filter the results is the Fiscal Year which is the current FY by default and multiple categories (check boxes) which are all checked by default. The page generates properly with the default data but when the form is submitted the page will "refresh" but there is no POST data generated. I tried creating a copy of the page and setting it as the action URL but it still did not have any POST data and used the defaults. I will include my code below and will try to narrow it down to just the necessary parts to make it easier but can share all of it if need be. Thank you in advance for any help offered.
<body>
<?php
if(isset($_POST['submit'])){echo"SET";} else{echo"NOT SET";}
// Establish Connection and Variables
// Connection
include "./include/class/DBConnection.php";
DBConnection::$dsn;
DBConnection::$user;
DBConnection::$pass;
DBConnection::getDBConnection();
// The Current Fiscal Year
$today = getdate();
$month = $today['month'];
// seperate first and second half of fiscal year
$old = array('January','February','March','April','May','June');
if (in_array($month,$old)) {
$year = $today['year'] + 1;
}
else {
$year = $today['year'];
}
// Create SQL Query Variables - Removed for post
// Set filter criteria
// Retrieve array of possible categories and create SQL WHERE statment
$catAllCxn = DBConnection::$cxn->prepare($SQL_Categories);
$catAllCxn->execute();
$catAllCxn->setFetchMode(PDO::FETCH_ASSOC);
$catAllArray = array();
while($catAllRow = $catAllCxn->fetch()) {
$cat = $catAllRow['Category'];
array_push($catAllArray, $cat);
}
$catAllInQuery = implode(',',array_fill(0,count($catAllArray),'?'));
// Create array for category filter IF form was submitted to itself
if (isset($_POST['submit'])){ // if page is submitted to itself
$catFilterArray = $_POST['Category'];
$catFilterInQuery = implode(',',array_fill(0,count($catFilterArray),'?'));
}
// Switch for ALL or Filtered report
if(!isset($_POST['submit'])) { // if page is not submitted to itself
$FiscalYear = $year;
// $DiscludedDepartmentNumbers = "21117";
$catArray = $catAllArray;
$IncludedCategories = $catAllInQuery;
}
else {
$FiscalYear = $_POST["FiscalYear"];
// $DiscludedDepartmentNumbers = "21117";
$catArray = $catFilterArray;
$IncludedCategories = $catFilterInQuery;
}
?>
<!-- Filter Form -->
<div id="filters" style="border: 1px solid;">
<form name="filter" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="POST">
Fiscal Year: <input type="text" name="FiscalYear" value="<?php echo $FiscalYear; ?>" /> <?php if(isset($_POST['submit'])){echo"SET";} else{echo"NOT SET";}?>
<br />
<fieldset>
<legend>Select Categories</legend>
<?php
foreach($catAllArray as $catAllRow) {
if (!isset($_POST['submit'])) {
echo "<input type=\"checkbox\" name=\"Category\" value=\"".$catAllRow."\" checked=\"checked\" />".$catAllRow." \n";
}
else if(in_array($catAllRow,$catArray)) {
echo "<input type=\"checkbox\" name=\"Category\" value=\"".$catAllRow."\" checked=\"checked\" />".$catAllRow." \n";
}
else {
echo "<input type=\"checkbox\" name=\"Category\" value=\"".$catAllRow."\" />".$catAllRow." \n";
}
}
?>
</fieldset> <br />
<input type="submit" value="submit" />
</form> <!-- End: filter -->
</div> <!-- End: filters -->
From here the original code continues to output results into a table but this works properly and I don't think it is the problem. I can share more if asked.
You need to give the submit button a name, if that's what you're using to check if the form is submitted...
<input type="submit" value="submit" name="submit" />
Or if you dont want to change the submit button, you can check isset on the category input instead
if(isset($_POST['Category'])){echo"SET";} else{echo"NOT SET";}
I think that your check if there is a _POST value is wrong. try this:
if(isset($_POST['FiscalYear']))
And see if that works
you need to name your submit button if you want to check for it
<input type="submit" value="submit" name="submit" />
otherwise php will not place it in the $_POST array