I have a form with multiple fields: Textinputs, Checkboxes, Radios.. and I want to submit it to a MySQL database. When I comment the checkboxes HTML, and the corresponding php code, everything is working fine, and everything is submitted and saved in the DB. If I try to submit the checkbox-form and I uncomment it, nothing get submitted, and clicking on the submit-button doesn't make any effect.
How can I submit the value of the checkbox-field to the MySQL-Database as a string, with the values separated with a semi-colon? For ex. if the checkbox fields are: Ab, Cd, De, Fg - and "Ab" and "De" are checked, the following string gets submitted: "Ab;Cd"
Here is a part of my HTML-form:
<div class="row">
<div class="col-sm-4">
<fieldset class="form-group">
<label for="plattform">Platform</label>
<form id="formId">
<input type="checkbox" name="check_list[]" value="Android">Android
<input type="checkbox" name="check_list[]" value="iPhone">iPhone
<input type="checkbox" name="check_list[]" value="iPad">iPad
<input type="checkbox" name="check_list[]" value="Windows Phone">Windows Phone
</form>
<!-- <input type="checkbox" name="check_list[]" value="Android">
<input type="checkbox" name="check_list[]" value="iPhone">
<input type="checkbox" name="check_list[]" value="iPad">
<input type="checkbox" name="check_list[]" value="Windows Phone"> -->
</fieldset>
</div>
<div class="col-sm-4">
<fieldset class="form-group">
<label for="featured">Featured</label>
<div>
<input type="radio" name="featured" required>True</input>
</div>
<div>
<input type="radio" name="featured" required checked>False</input>
</div>
</fieldset>
</div>
here is a sample of my php-file:
<?php /* Attempt MySQL server connection. Assuming you are running
MySQL server with default setting (user 'root' with no password) */
/* Database connection start */
$servername = "localhost";
$username = "serverName_Here";
$password = "password_Here";
$dbname = "dbName_Here";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
// Check connection
if($conn === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$stName = mysqli_real_escape_string($conn, $_POST['sName']);
$lgName = mysqli_real_escape_string($conn, $_POST['lName']);
$desc = mysqli_real_escape_string($conn, $_POST['desc']);
$Platform = '';
if(!empty($_POST['check_list'])) {
$counter = 0;
foreach($_POST['check_list'] as $check) {
if ($counter < 1) {
$Platform = $check;
} else {
$Platform = $excludePlatform + ';' + $check;
}
counter++;
}
}
$Platform = mysqli_real_escape_string($conn, $_POST['check_list']);
$sql = "INSERT INTO tableName_Here (stName, lgName, details_description, Platform) VALUES ('$stName', '$lgName', '$desc', '$Platform')";
if(mysqli_query($conn, $sql)){
echo "Records added successfully.";
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
} // close connection
mysqli_close($conn); ?>
You need to have the checkboxes within the form tags.
The easiest way is to put the form opening and closing tabs above and below the rest of the field code. The submit buttons should be within the form as well.
On the backend checkbox values will come through as an array. You can then do something like this if you want to save them comma separated.
$values = implode(', ', $_POST['check_list']);
First of all,Why you haven't used POST as method in form tag also you haven't used submit button.In that way you can access value of checkboxes in php like
$value=$_POST['check_list[]'];
Try this whole example,
Table Structure
CREATE TABLE IF NOT EXISTS `games` (
`id` int(12) NOT NULL AUTO_INCREMENT,
`game_name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
<?php
include_once("yourconfig.php"); //include your db config file
extract($_POST);
$check_exist_qry="select * from games";
$run_qry=mysql_query($check_exist_qry);
$total_found=mysql_num_rows($run_qry);
if($total_found >0)
{
$my_value=mysql_fetch_assoc($run_qry);
$my_stored_game=explode(',',$my_value['game_name']);
}
if(isset($submit))
{
$all_game_value = implode(",",$_POST['games']);
if($total_found >0)
{
//update
$upd_qry="UPDATE games SET game_name='".$all_game_value."'";
mysql_query($upd_qry);
}
else
{
//insert
$ins_qry="INSERT INTO games(game_name) VALUES('".$all_game_value."')";
mysql_query($ins_qry);
}
}
?>
<form method="post" action="">
Games You Like: <br/>
<input type="checkbox" name="games[]" value="1" <?php if(in_array(1,$my_stored_game)){echo "checked";}?>><label>Football</label><br>
<input type="checkbox" name="games[]" value="2" <?php if(in_array(2,$my_stored_game)){echo "checked";}?>><label>Basket Ball</label><br>
<input type="checkbox" name="games[]" value="3" <?php if(in_array(3,$my_stored_game)){echo "checked";}?>><label>Pool</label><br>
<input type="checkbox" name="games[]" value="4" <?php if(in_array(4,$my_stored_game)){echo "checked";}?>><label>Rugby</label><br>
<input type="checkbox" name="games[]" value="5" <?php if(in_array(5,$my_stored_game)){echo "checked";}?>><label>Tennis</label><br>
<input type="checkbox" name="games[]" value="6" <?php if(in_array(6,$my_stored_game)){echo "checked";}?>><label>Cricket</label><br>
<input type="checkbox" name="games[]" value="7" <?php if(in_array(7,$my_stored_game)){echo "checked";}?>><label>Table Tennis</label><br>
<input type="checkbox" name="games[]" value="8" <?php if(in_array(8,$my_stored_game)){echo "checked";}?>><label>Hockey</label><br>
<input type="submit" name="submit" value="submit">
</form>
this is just basic example and query i have added in this example, you can learn from this basic example and i think this is very useful for you... if useful than give correct answer for this solution
Related
When my insert runs it will write the text in the text box but if I choose a radio button selection other than "other" nothing is inserted into the table.
If I remove the "other"code the radio button selected is written to the table.
here is the code
<input type="radio" name="job" value="PHP Programmer">PHP Programmer
<input type="radio" name="job" value="SQL Programmer">SQL Programmer<br>
<input type="radio" name="job">Other <input type="text" name="job" >
<h3>* If yes, check which ISO standard(s) you are accredited?</h3>
<input type="radio" name="iso_standard" value="17020">17020
<input type="radio" name="iso_standard" value="17025">17025
<br />
<input action="submit" type="submit" name="submit" value="Submit">
</form>
<?php
if(isset($_POST['job']) && isset($_POST['iso_standard']))
{
$job = mysqli_real_escape_string($db, $_POST['job']);
$iso_standard =mysqli_real_escape_string($db, $_POST['iso_standard']);
$sql="insert into tbl_test_insert(iso_cert, iso_standard)
values ('$job', '$iso_standard')";
if(!mysqli_query($db, $sql))
{
die('Error: ' .mysqli_error($db));
}
echo "1 record added";
}
else
{
echo "You didn't choose all the options!
}
?>
You are overwriting the value of job with the text input field. It does not mather if it has any value or not.
Please rename your <input type="text" name="job" > to for example otherJob and you should be fine
edit:
change <input type="radio" name="job">Other <input type="text" name="job" >
to <input type="radio" name="job" value="other">Other <input type="text" name="otherJob">
change $job = mysqli_real_escape_string($db, $_POST['job']);
to
$job = mysqli_real_escape_string($db, $_POST['job']);
$otherJob = mysqli_real_escape_string($db, $_POST['otherJob']);
if ($job == 'other') {
$jobField = $otherJob;
} else {
$jobField = $job;
}
and change $sql="insert into tbl_test_insert(iso_cert, iso_standard)
values ('$job', '$iso_standard')";
to $sql="insert into tbl_test_insert(iso_cert, iso_standard)
values ('$jobField', '$iso_standard')";
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']);
I am trying to have my form data stored in a mysql database. I want everything that the user types or clicks to be stored there. I am able to have my text fields stored in mysql successfully. I am having trouble figuring out how to send multiple check boxes, radio buttons, and drop down lists to mysql and have it stored there. I don't even know where to begin. Please help.
Also refer to this too.
php and mysql - Send checkbox, radio button, and drop down menu results from user to mysql database and store it there
session_start();
function logged_in() {
return isset($_SESSION['user_id']);
}
function confirm_logged_in() {
if (!logged_in()) {
redirect_to("contact info.php");
}
}
// Database Constants
define('DB_SERVER', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'wer_application');
function check_required_fields($required_array) {
$field_errors = array();
foreach($required_array as $fieldname) {
if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && !is_numeric($_POST[$fieldname]))) {
$field_errors[] = $fieldname;
}
}
return $field_errors;
}
function check_max_field_lengths($field_length_array) {
$field_errors = array();
foreach($field_length_array as $fieldname => $maxlength ) {
if (strlen(trim(mysql_prep($_POST[$fieldname]))) > $maxlength) { $field_errors[] = $fieldname; }
}
return $field_errors;
}
function display_errors($error_array) {
echo "<p class=\"errors\">";
echo "Please review the following fields:<br />";
foreach($error_array as $error) {
echo " - " . $error . "<br />";
}
echo "</p>";
}
// START FORM PROCESSING
if (isset($_POST['submit'])) { // Form has been submitted.
$errors = array();
// perform validations on the form data
$required_fields = array('id','student_gender', 'student_session_one_preference', 'student_session_two_preference',
'waldron_scholarship', 'jesse_van_anterp_huyck_scholarship', 'edward_raney_scholarship', 'school_type',
'student_statemenet_consent_check_box', 'guardian_statemenet_consent_check_box', 'waiver');
$errors = array_merge($errors, check_required_fields($required_fields, $_POST));
$errors = array_merge($errors, check_max_field_lengths($fields_with_lengths, $_POST));
//Captures what is typed by the user
if(!empty($_POST) && isset($_POST["submit-btn"])){
$student_gender = isset($_POST["student_gender"]) ? $_POST["student_gender"] : "";
$student_session_one_preference = isset($_POST["student_session_one_preference"]) ? $_POST["student_session_one_preference"] : "";
$student_session_two_preference = isset($_POST["student_session_two_preference"]) ? $_POST["student_session_two_preference"] : "";
$waldron_scholarship = isset($_POST["waldron_scholarship"]) ? $_POST["waldron_scholarship"] : "";
$jesse_van_anterp_huyck_scholarship = isset($_POST["jesse_van_anterp_huyck_scholarship"]) ? $_POST["jesse_van_anterp_huyck_scholarship"] : "";
$edward_raney_scholarship = isset($_POST["edward_raney_scholarship"]) ? $_POST["edward_raney_scholarship"] : "";
$school_type = isset($_POST["school_type"]) ? $_POST["school_type"] : "";
$student_statemenet_consent_check_box = isset($_POST["student_statemenet_consent_check_box"]) ? $_POST["student_statemenet_consent_check_box"] : "";
$guardian_statemenet_consent_check_box = isset($_POST["guardian_statemenet_consent_check_box"]) ? $_POST["guardian_statemenet_consent_check_box"] : "";
$waiver = isset($_POST["waiver"]) ? $_POST["waiver"] : "";
//sends the data from the form into our database we made with mysql.
$sql = "INSERT INTO nature VALUES ('id','$student_gender', '$student_session_one_preference', '$student_session_two_preference',
'$waldron_scholarship', '$jesse_van_anterp_huyck_scholarship', '$edward_raney_scholarship', '$school_type',
'$student_statemenet_consent_check_box', '$guardian_statemenet_consent_check_box', '$waiver')";
if(!mysql_query($sql)){
die('Error: ' . mysql_error());
}
}
<html>
<head>
<title>WER Application Packet</title>
<link href="stylesheets/public.css" media="all" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header">
<h1>WER Application Packet</h1>
</div>
<div id="main">
<table id="structure">
<tr>
<td id="page">
<?php if (!empty($message)) {echo "<p class=\"message\">" . $message . "</p>";} ?>
<?php if (!empty($errors)) { display_errors($errors); } ?>
<form action="contact info.php" method="post">
<form method="POST">
<input type="radio" name="student_gender" value="Male">Male<br>
<input type="radio" name="student_gender" value="Female">Female<br>
<select name="student_session_one_preference">
<option value="Session 1">Session 1: June 30 - July 21</option>
<option value="Session 2">Session 2: July 28 - August 18</option>
</select> <br/>
Preference 2:
<select name="student_session_two_preference">
<option value="Session 1">Session 1: June 30 - July 21</option>
<option value="Session 2">Session 2: July 28 - August 18</option>
</select>
<input type="checkbox" name="waldron_scholarship" value="Waldron Scholarship">Waldron Scholarship<br/>
<input type="checkbox" name="jesse_van_anterp_huyck_scholarship" value="Jesse Van Anterp Huyck Scholarship">Jesse Van Anterp Huyck Scholarship<br/>
<input type="checkbox" name="edward_raney_scholarship" value="Edward Raney Scholarship">Edward Raney Scholarship<br/>
<select name="school_type">
<option value="Public">Public</option>
<option value="Private">Private Parochial</option>
<option value="Other">Other</option>
</select>
<input type="radio" name="waiver" value="">I waive any right of access that I may have to information submitted by my referee<br>
<input type="radio" name="waiver" value="">I do not waive any right of access that I may have to information submitted by my referee<br>
<input type="checkbox" name="student_statement_consent_check_box" value="Agree">By checking this box, the student acknowledges <br/> that they have read the statement <br/> of consent and agrees with it.<br>
<input type="checkbox" name="guardian_statement_consent_check_box" value="Agree">By checking this box, the guardian acknowledges <br/> that they have read the statement <br/> of consent and agrees with it.<br>
<input type="submit" value="Submit" name="submit-btn">
</form>
</td>
</tr>
</table>
</div>
<div id="footer"></div>
</body>
</html>
<?php
// 5. Close connection
mysql_close($connection);
?>
CREATE TABLE nature(
ID int NOT NULL auto_increment,
student_gender varchar(6),
student_session_one_preference varchar(30),
student_session_two_preference varchar(30),
waldron_scholarship tinyint,
jesse_van_anterp_huyck_scholarship tinyint,
edward_raney_scholarship tinyint,
school_type varchar(25),
student_statemenet_consent_check_box tinyint,
guardian_statemenet_consent_check_box tinyint,
waiver tinyint,
PRIMARY KEY(ID)
);
Try playing with the following PHP script to discover what gets sent (and what doesn't) when you select and omit certain form elements.
<?php
if (sizeOf($_POST) > 0) print_r($_POST);
?>
<form method="POST" action=".">
<input type="checkbox" name="checkbox" id="checkbox" /> <label for="checkbox">Checkbox</label>
<input type="radio" name="radio" value="1" id="radio_1" /> <label for="radio_1">Radio 1</label>
<input type="radio" name="radio" value="2" id="radio_2" /> <label for="radio_2">Radio 2</label>
<select name="select">
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="submit" />
</form>
You'll see that if a checkbox is checked, the corresponding form POST value will be set to "on". A radio button will be set to its value, as will a select.
Note that all form elements when sent to the action page are keyed by their name.
Your waiver radio inputs are both missing values, so $_POST['waiver'] will always be empty. Fix like this:
<input type="radio" name="waiver" value="yes">
<input type="radio" name="waiver" value="no">
Your checkbox fields can set the variables like this (just check if set):
$jesse_van_anterp_huyck_scholarship = isset($_POST["jesse_van_anterp_huyck_scholarship"]) ? 1 : 0;
FYI: Your varchar(30) fields may not be long enough to store strings like "Jesse Van Anterp Huyck Scholarship"
I'm unable to insert a record here. Not sure why. My login works. My two echo statements work. But no record gets recorded. All the variables that begin with 'type' or 'subj' are checkbox form elements, so I set those columns to 'Null' in the db (using phpMyAdmin). Not sure if that's correct - the idea is they're not required. Also, the first column in my db is not an entry from this form, it's supposed to be an id for the entry, set as primary key, not-null, and set to auto-increment. This is my first time doing this. How can I test what's happening? Thank you! - and what the heck happened to my codeblock!!!
<!DOCTYPE html>
<head>
<title>Submit entry to database </title>
</head>
<body> <?php
//when Submit clicked
if ( isset($_POST['submit']) ){
$data_source = 'mysql:host=myHost;dbname=myDatabase';
$db_user = 'myUserName';
$db_password = 'myPassword';
$db = new PDO($data_source, $db_user, $db_password);
//load the form data into variables
$reviewer = $_POST['reviewer'];
$osj = $_POST['osj'];
$touchDate = $_POST['touchDate'];
$typeAction = $_POST['typeAction'];
$typeTech = $_POST['typeTech'];
$typeReg = $_POST['typeReg'];
$subjSuit = $_POST['subjSuit'];
$subjMFtran = $_POST['subjMFtran'];
$subjConcen = $_POST['subjConcen'];
$subjOption = $_POST['subjOption'];
$subjTrade = $_POST['subjTrade'];
$subjMuni = $_POST['subjMuni'];
$subjUIT = $_POST['subjUIT'];
$subjBkRecMFdir = $_POST['subjBkRecMFdir'];
$subjOBA = $_POST['subjOBA'];
$subjOther = $_POST['subjOther'];
$flavor = $_POST['flavor'];
$notes = $_POST['notes'];
echo $reviewer;
//prepare SQL statement
$statement = "INSERT INTO tblBranchTouches
(reviewer, osj, touchDate, typeAction, typeTech, typeReg, subjSuit,
subjMFtran, subjConcen, subjOption, subjTrade, subjMuni, subjUIT, subjBkRecMFdir,
subjOBA, subjOther, flavor, notes)
VALUES ('$reviewer', '$osj', '$touchDate', '$typeAction', '$typeTech', '$typeReg', '$subjSuit',
'$subjMFtran', '$subjConcen', '$subjOption', '$subjTrade', '$subjMuni', '$subjUIT', '$subjBkRecMFdir',
'$subjOBA', '$subjOther', '$flavor', '$notes') ";
$db->query($statement);
//confirm
echo "<h1>Thank You</h1>";
}
?>
<form method="post">
<p>
<label>
Reviewer:
<input type="text" name="reviewer" list="ARTies">
<datalist id="ARTies">
<option value = "MWeber">
<option value = "JBurchill">
<option value = "DGlazer">
<option value = "EKiburz">
<option value = "CSupak">
<option value = "MVallery">
<option value = "CHo">
<option value = "HPatil">
<option value = "NVanDoorn">
</datalist>
</label>
<label>
OSJ:
<input type="text" name="osj" maxlength=3 size=3>
</label>
<input type="date" name="touchDate" value="<?php echo date('Y-m-d', strtotime(date('Y/m/d'))); ?>">
</p>
<fieldset>
<legend>Type: </legend>
<p><label><input type="checkbox" name="typeAction"> Action </label>
<label><input type="checkbox" name="typeTech"> Tech. </label>
<label><input type="checkbox" name="typeReg"> Reg.</label></p>
</fieldset>
<fieldset>
<legend>Subject: </legend>
<p>
<label><input type="checkbox" name="subjSuit"> Suitability </label>
<label><input type="checkbox" name="subjMFtrans"> MF Transactions </label>
<label><input type="checkbox" name="subjConcen"> Concentrations </label>
<label><input type="checkbox" name="subjOption"> Options </label>
<label><input type="checkbox" name="subjTrade"> Trade Review </label>
<label><input type="checkbox" name="subjMuni"> Munis </label>
<label><input type="checkbox" name="subjUIT"> UITs </label>
<label><input type="checkbox" name="subjBkRecMFdir"> Bks-Recs-MFDirect </label>
<label><input type="checkbox" name="subjOBA"> OBAs </label>
<label><input type="checkbox" name="subjOther"> Other </label>
</p>
</fieldset>
<p>
<label>
Flavor:
<input type="number" name="flavor" min=1 max=5 value=3>
</label>
<label>Notes: <textarea name="notes"></textarea></label>
</p>
<p>
<input type="submit" name="submit" value="ENTER">
</p>
</form>
</body>
</html>
for INSERT, you need to use pdo::exec, this will return the no. of rows inserted. http://us.php.net/manual/en/pdo.exec.php pdo::query is used for SELECT queries.
so your statement would be,
$statement = "INSERT INTO tblBranchTouches
(reviewer, osj, touchDate, typeAction, typeTech, typeReg, subjSuit,
subjMFtran, subjConcen, subjOption, subjTrade, subjMuni, subjUIT, subjBkRecMFdir,
subjOBA, subjOther, flavor, notes)
VALUES ('$reviewer', '$osj', '$touchDate', '$typeAction', '$typeTech', '$typeReg', '$subjSuit',
'$subjMFtran', '$subjConcen', '$subjOption', '$subjTrade', '$subjMuni', '$subjUIT', '$subjBkRecMFdir',
'$subjOBA', '$subjOther', '$flavor', '$notes') ";
$count = $db->exec($statement);
if($count > 0)
echo "<h1>Thank You</h1>";
else //else statement if you need it
echo "<h1>No records were inserted.</h1>";
You can check the error with the following:
if ($db->error)
echo $db->error;
Very useful! Never assume that a query was successful; you always want to check for errors.
Here's what is now working for me. I just wish I didn't have to write my form variables about 7 different times. Thanks again...
<?php
//when Submit clicked
if ( isset($_POST['submit']) ){
$data_source = 'mysql:host=myHost;dbname=myDB';
$db_user = 'myUsername';
$db_password = 'myPass';
//create a new PDO object - constructor takes at most 4 parameters, DSN, username, password,
//and an array of driver options
//a DSN is basically a string of options that tell PDO which driver to use, and the connection details
$conn = new PDO($data_source, $db_user, $db_password,
array(PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
//first driver option turns off prepare emulation which is enabled in MySQL driver by default, but really should be turned off to use PDO safely
//second driver option puts PDO into exception mode
//
//load the form data into variables
$reviewer = $_POST['reviewer'];
//(more)
//prepare SQL statement
$sql="INSERT INTO tblBranchTouches
(reviewer, osj, touchDate, typeAction, typeTech, typeReg, subjSuit,
subjMFtrans, subjConcen, subjOption, subjTrade, subjMuni, subjUIT, subjBkRecMFdir,
subjOBA, subjOther, flavor, notes)
VALUES (:reviewer, :osj, :touchDate, :typeAction, :typeTech, :typeReg, :subjSuit,
:subjMFtrans, :subjConcen, :subjOption, :subjTrade, :subjMuni, :subjUIT, :subjBkRecMFdir,
:subjOBA, :subjOther, :flavor, :notes)";
$q = $conn->prepare($sql);
$q->execute(array(':reviewer'=>$reviewer, ':osj'=>$osj, ':touchDate'=>$touchDate, ':typeAction'=>$typeAction, ':typeTech'=>$typeTech,
':typeReg'=>$typeReg, ':subjSuit'=>$subjSuit, ':subjMFtrans'=>$subjMFtrans, ':subjConcen'=>$subjConcen, ':subjOption'=>$subjOption,
':subjTrade'=>$subjTrade, ':subjMuni'=>$subjMuni, ':subjUIT'=>$subjUIT, ':subjBkRecMFdir'=>$subjBkRecMFdir, ':subjOBA'=>$subjOBA,
':subjOther'=>$subjOther, ':flavor'=>$flavor, ':notes'=>$notes));
}
?>
Front-end designer here, not a PHP developer and I really need the help. Need to make a system that will allow the client to log into their own area to update a table. The table will have about 20 records and each row will be edited with radio buttons (4 choices). Only 2 columns, one for ID and one called status (the editable data).
The viewer will only see the changes made by the client and a background color change to that row depending on the status, which means the editable part will have to hold 2 pieces of data (integer value to change color and the name of the status, e.g. value of the radio button to change color, and label of button to echo the text into the cell). Will deal about login system later...
Database set-up:
Database: test
Table: fire_alert
Structure:
id (INT, PRIMARY); color(INT); warning(VACHAR);
connect.php:
<?php
// Database Variables (edit with your own server information)
$server = 'localhost';
$user = 'root';
$pass = 'root';
$db = 'test';
// Connect to Database
$connection = mysql_connect($server, $user, $pass)
or die("Could not connect to server ... \n" . mysql_error());
mysql_select_db($db)
or die("Could not connect to database ... \n" . mysql_error());
?>
view.php:
<div id="container">
<?php
// connect to the database
include('connect.php');
include("header.php");
// get results from database
$result = mysql_query("SELECT * FROM fire_alert")
or die(mysql_error());
echo "Current date - " . date("Y/m/d") . "<br /><br />";
// display data in table
echo "<table>";
echo "<tr> <th>Area</th> <th>Status</th></tr>";
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array($result)) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['warning'] . '</td>';
echo "</tr>";
}
// close table>
echo "</table>";
echo '<td>Change Area Status</td>';
?>
</div>
<body>
</body>
</html>
edit.php (client access only) no dynamic data changes yet, hardcoded HTML so far:
<?php include("header.php"); ?>
<?php include("connect.php"); ?>
<div id="container" class="edit">
<div id="radio1">
<?
$result = mysql_query("SELECT * FROM fire_alert")
or die(mysql_error());
echo "Current date - " . date("Y/m/d") . "<br /><br />";
?>
<table class="edit">
<tr><th>Area</th><th>Status</th></tr>
<tr>
<td>1</td>
<td>
<form method="post" action="edit.php">
<input type="radio" id="radio1" name="radio" value="1" /><label for="radio1">Safe</label>
<input type="radio" id="radio2" name="radio" value="2" /><label for="radio2">Caution L1</label>
<input type="radio" id="radio3" name="radio" value="3" /><label for="radio3">Caution L2</label>
<input type="radio" id="radio4" name="radio" value="4" /><label for="radio4">Closed</label>
</form>
</td>
</tr>
</table>
</div>
<?php echo '<td>Update</td>'; ?>
</div>
The simplest way to run this update (or the way I use anyways) is by leveraging javascript. Have each section of radio blocks in its own form that submits automatically onChange, and include a hidden variable to indicate page submission. Then just write a function to update the database, based on the inputted user's id (or however you're validating) and their selection choice...
Something like:
if($_POST["submit"] == 1)
{
$id = $_POST["id"];
$radio = $_POST["radio"];
$query = "UPDATE fire_alert SET warning = '$radio' WHERE id = '$id'";
$result = mysql_query($query) or die(mysql_error());
}
You have a problem with how you formatted your view.php link, that line should be as follows:
'Update'; ?>'
Though the above won't quite work as you're intending since it's not submitting the form, so the radio button values won't be passed... instead you should do:
<form method="post" action="edit.php">
<input type="radio" id="radio1" name="radio" value="1" onChange="this.submit()"/><label for="radio1">Safe</label>
<input type="radio" id="radio2" name="radio" value="2" onChange="this.submit()"/><label for="radio2">Caution L1</label>
<input type="radio" id="radio3" name="radio" value="3" onChange="this.submit()" /><label for="radio3">Caution L2</label>
<input type="radio" id="radio4" name="radio" value="4" onChange="this.submit()"/><label for="radio4">Closed</label>
<input type="hidden" name="id" value="<?=$row["id"]?>" />
</form>
And you'll need to edit your php to reflect that difference as well