Prossessing checkbox value in a php form connected to mysql database - php

Hi I am trying to create a form for the school I work so that staff can book when they want a projector setting up in the school hall. So far i have textbox fields for date, time, name but I also want a checkbox field so they can select if they want to loan a laptop and have sound.
My problem is I can't find how to put the value from the checkbox into the database. Thanks in advance for any help.
Here is what I have so far...
HTML
<form action="mysql-insert.php" method="post">
<p>Date: <input name="date" type="text" id="datepicker" /></p>
<p>Time : <input name="time" type="text" /></p>
<p>Name : <input name="name" type="text" /></p>
<p>Laptop <input name="chkbox[]" type="checkbox" value="Laptop" /></p>
<p>Sound <input name="chkbox[]" type="checkbox" value="Sound" /></p>
<p><input name="submit" type="submit" value="Save Hall Setup Request" /></p>
</form>
PHP
<?php
$dbserver = 'localhost';
$dbuser = 'root';
$dbpassword = '';
$dbdatabase = 'hall_setup';
$cn = mysql_connect($dbserver , $dbuser, $dbpassword);
if (!mysql_select_db($dbdatabase, $cn)) {
echo "Sorry, could not connect to $dbdatabase";
die();
}
if (!isset($_POST['submit'])) {
header("Location: mysql-insert-form.php");
die();
}
$date = $_POST['date'];
$time = $_POST['time'];
$name = htmlspecialchars(trim($_POST['name']));
$laptop = $_POST['chkbox'];
$name = mysql_real_escape_string($name);
$sql = "INSERT INTO laptoprequest
(date, time, name, laptop)
VALUES
('$date', '$time', '$name', '$laptop')";
if(!mysql_query($sql, $cn)) {
print "Error - data not submitted";
die();
};
header("Location: hall_setup.php");
?>

<?php
<input type="checkbox" name="check_list[]" value="English" required>
<label>English</label>
<input type="checkbox" name="check_list[]" value="Non English" required>
<label>Non English</label>
<input id="button" type="submit" name="submit" value="Submit">
?>
//above question for answer this..>>>
<?php
$checkbox = $_POST['check_list'];
if($_POST["submit"]=="submit"){
for($i=0;$i<sizeof($checkbox);$i++){
$query1="INSERT INTO user(language) VALUES
('".$checkbox[$i]."')";
mysql_query($query1) or die(mysql_error());
}
echo "Record is inserted.."
}
?>

Related

How to upload a radio button value entered in an html form

I have made the form so that it gets the selected radio value button and it gets passed to the php section and to the database.But in the database it shows as "on" no matter what the selection is.
I have no idea where I have gone wrong
HTML form:
<form action="Database.php" name="register" method="post">
<div>
First Name <input type="text" name="fname"/><br>
Last Name <input type="text" name="lname"/><br>
Email <input type="email" name="email"/><br>
Contact No. <input type="text" name="num"/><br>
Gender <br> <input type="radio" name="g1" value="Male"/>Male
<input type="radio" name="g1" value="Female"/>Female
<br>
<br>
</form>
PHP:
$fname = $conn->real_escape_string($_POST['fname']);
$lname = $conn->real_escape_string($_POST['lname']);
$email = $conn->real_escape_string($_POST['email']);
$cnumber = $conn->real_escape_string($_POST['num']);
$gender = $conn->real_escape_string($_POST['g1']);
$sql="INSERT INTO data (fname, lname, email, cnumber, gender)
VALUES ('".$fname. "','".$lname."','".$email."', '".$cnumber."', '".$gender."')";
I expected output to be male/female
but it says "on"
Using your form I have used a small code and found this works
<form action="Database.php" name="register" method="post">
<div>
First Name <input type="text" name="fname"/><br>
Last Name <input type="text" name="lname"/><br>
Email <input type="email" name="email"/><br>
Contact No. <input type="text" name="num"/><br>
Gender <br> <input type="radio" name="g1" value="Male"/>Male
<input type="radio" name="g1" value="Female"/>Female
<br>
<input type="submit" style="min-width:100%" align="center" name='submit' value="SUBMIT">
<br>
</form>
Your PHP side should be this:
if(!isset($_POST['submit']))
{
//This page should not be accessed directly. Need to submit the form.
echo "Submitted";
}
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$g1 = $_POST['g1'];
$sql = "INSERT INTO etrack.test SET
fname = '".$fname."',
lname = '".$lname."',
g1 = '".$g1."'";
if ($conn->query($sql) === TRUE) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
echo("Error description: " . mysqli_error($con));
echo "Error 1";
}
I am getting the required results

Can't get my PHP to show error when form field is blank

I am making a PHP Journal through a form, but no matter what I do, it always comes up as successfully posted. I've tried using empty() and null but I'm not sure what I'm doing wrong.
Here is the HTML for the form:
<form action="journal_post.php" method="post">
<p>Give your entry a title.</p>
<input class="input" type="text" name="title" />
<p>What is your mood today?</p>
<input class="input" type="text" name="mood" />
<p>Now please tell me about your day.</p>
<textarea class="input" name="entry" rows="12" cols="75" type="text"> </textarea>
<br>
<br>
<input class="submit" type="image" src="submit.png" name="submit" value="Submit" />
<form>
Here is the PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "blahblah";
debug_to_console($password);
//Establishing Connection with Server
$connection = mysql_connect($servername, $username, $password);
//Selecting Database from Server
$journal_db = mysql_select_db("journal_db", $connection);
if(isset($_POST['submit'])){
//Fetching variables of the form which travels in URL
$title = $_POST['title'];
$mood = $_POST['mood'];
$entry = $_POST['entry'];
if($title !=''||$entry !=''){
//Insert Query of SQL
$query = mysql_query("insert into entrys(j_title, j_mood, j_entry) values ( '$title', '$mood', '$entry')");
echo "<br/><br/><span>Journal entry recorded..!!</span>";
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
//Closing Connection with Server
mysql_close($connection);
?>
Change:
if($title !=''||$entry !=''){
to:
if($title !=''&&$entry !=''){
You want to check that both $title and $entry aren't empty, not either-or.
You should definitely use isset() to check the field before insertion into database
the line
<textarea class="input" name="entry" rows="12" cols="75" type="text"> </textarea>
actually adds a space in the entry, change it to
<textarea class="input" name="entry" rows="12" cols="75" type="text"></textarea>

Not updating SQL database

For some reason my code isn't updating mySQL database, but it isn't reporting any errors.
register.php (form)
<form class="register_form" action="action.php?do=register" method="post">
Team Name*: <input type="text" name="teamname" required />
Team Region*: <input type="text" name="teamregion" maxlength="4" required />
Team Leader*: <input type="text" name="teamleader" maxlength="16" required />
Team Members: <input type="text" name="teammembers" />
<input name="register_submit" type="submit" value="Register" />
</form>
action.php
<?php
$con=mysqli_connect("192.185.#.###","########_reg","#######","#########");
if (mysqli_connect_errno()) {echo "Failed to connect to MySQL: " . mysqli_connect_error();}
$action = $_GET['do'];
if($action=="register") {
$teamname = $_POST["teamname"];
$teamregion = $_POST["teamregion"];
$teamleader = $_POST["teamleader"];
$teammembers = $_POST["teammembers"];
$result = mysqli_query($con, "INSERT INTO teams (teamname, region, teamleader, teammembers, wins, loses)
VALUES (" . $teamname . "," . $teamregion . "," . $teamleader . "," . $teammembers . ",0,0);");
}
?>
Any ideas why this isn't working correctly?
Here's a working sample with prepared statements, that are "better" to use generally instead of query
action.php
$con = new mysqli('localhost', 'root', '', 'dachi');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (isset($_GET['do']) && $_GET['do'] === "register") {
$teamname = $_POST["teamname"];
$teamregion = $_POST["teamregion"];
$teamleader = $_POST["teamleader"];
$teammembers = $_POST["teammembers"];
$wins = 0;
$loses = 0;
$stmt = $con->prepare("INSERT INTO `teams` (`teamname`,`region`,`teamleader`,`teammembers`,`wins`,`loses`) VALUES (?,?,?,?,?,?)");
$stmt->bind_param('ssssii', $teamname, $teamregion, $teamleader, $teammembers, $wins, $loses);
$stmt->execute();
$stmt->close();
}
register.php
<form class="register_form" action="action.php?do=register" method="post">
Team Name*: <input type="text" name="teamname" required />
Team Region*: <input type="text" name="teamregion" maxlength="4" required />
Team Leader*: <input type="text" name="teamleader" maxlength="16" required />
Team Members: <input type="text" name="teammembers" />
<input name="register_submit" type="submit" value="Register" />
</form>
You should change:
if($action=="register") {
to
if($action=="register_submit") {
Because your input has a tag name set to value register_submit not register.
and change $action = $_GET['do']; to $action = $_POST['register_submit'];
register.php (form)
<form class="register_form" action="action.php?do=register" method="post">
action.php
$action = $_GET['do'];

Not inserting values to database:

I am trying to make Sign Up Now! area for a restaurant website and want to insert data of new members in the members_t table of database members with all running on localhost. I am using PHP and HTML for the purpose. Moreover, I am doing form validation using javaScript in a separate file which is working perfectly!
Code for PHP:
<?php
$user="root";
$password="";
$database="members";
$con = mysql_connect('localhost',$user,$password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $con) or die( "Unable to select database");
if(isset($_POST['sign_up']) && !empty($_POST['sign_up']))
{
$sql = "INSERT INTO members_t('Name', 'Email', 'Password', 'Phone', 'Address', 'Sex', 'More') VALUES('".$_POST['username']."','".$_POST['email']."','".$_POST['passid_1']."','".$_POST['zip']."','".$_POST['address']."','".$_POST['sex']."','".$_POST['desc']."');";
$resultDI = mysql_query($sql, $con) or die(mysql_error());
mysql_close($con);
echo "Successfolly run database query!";
}
else
{
echo("Failed to update database!!!");
}
?>
Code for HTML:
<html>
<body>
<h2 class="letter_spacing">Not a Member?<span><br>Sign Up Now:</br></span></h2>
<form id = "register" name="registration" method = "post" onSubmit="return formValidation();">
<ul>
<li><label for="username">* Full Name:</label></li>
<li><input type="text" name="username" size="50" /></li>
<li><label for="email">* Email:</label></li>
<li><input type="text" name="email" size="50" /></li>
<li><label for="passid_1">* Desired Password:</label></li>
<li><input type="password" name="passid_1" size="12" /></li>
<li><label for="passid_2">* Re-Enter Password:</label></li>
<li><input type="password" name="passid_2" size="12" /></li>
<li><label for="zip">* Contact Number:</label></li>
<li><input type="text" name="zip" /></li>
<li><label for="address">* Address:</label></li>
<li><input type="text" name="address" size="50" /></li>
<li><label id="gender">* Sex:</label></li>
<li><input type="radio" name="msex" value="Male" /><span>Male</span></li>
<li><input type="radio" name="fsex" value="Female" /><span>Female</span></li>
<li><label for="desc">Anything More:</label></li>
<li><textarea name="desc" id="desc" cols="40" rows="4"></textarea></li>
<li><label for="note" ><h6>Note: All feilds marked with * are necessary</h6></label></li>
<li><input class="button1" type="submit" name="sign_up" value="Sign Up!" /></li>
</ul>
</form>
</body>
</html>
I have tried to keep the code in a separate file called insert.php and added the action field to the HTML form tag yet of no use.
I am never able to insert data into the database. It seems the PHP code never goes into the
if(isset($_POST['sign_up']) && !empty($_POST['sign_up']))
block.
Try this:
<form id="register" action="" method="post" name="registration" onSubmit="return formValidation();">
<input type="text" name="username" size="50" />
<input type="text" name="email" size="50" />
<input type="password" name="passid_1" size="12" />
<input type="password" name="passid_2" size="12" />
<input type="text" name="zip" />
<input type="text" name="address" size="50" />
<input type="radio" name="sex" value="Male" /><span>Male</span>
<input type="radio" name="sex" value="Female" /><span>Female</span>
<textarea name="desc" id="desc" cols="40" rows="4"></textarea>
<input class="button1" type="submit" name="sign_up" value="Sign Up!" />
</form>
<?php
if (isset($_POST['sign_up']) && !empty($_POST['sign_up'])) {
// escape all submitted data before inserting into database
foreach ($_POST as $key => $value) {
$_POST[$key] = mysql_real_escape_string(strip_tags($value));
}
$result = mysql_query("
INSERT INTO members_t (Name, Email, Password, Phone, Address, Sex, More)
VALUES ('{$_POST['username']}', '{$_POST['email']}', '{$_POST['passid_1']}', '{$_POST['zip']}', '{$_POST['address']}', '{$_POST['sex']}', '{$_POST['desc']}')
") or die(mysql_error());
if (mysql_affected_rows() == 1) {
echo "Successfully run database query!";
} else {
echo("Failed to update database!!!");
}
}
?>
Note that name of the radio buttons should be the same "sex" not "msex" and "fsex" as in your code. And I have added the action attribute in the form tag plus some other modifications you can easily notice.
First of all, i have cleaned up the code a little so it looks nice and smooth. Then i have removed the !empty part you made, cant see the reason why you want to verify that it actually is empty when you already used isset.
HTML:
<?php
$hostname = "";
$user = "root";
$password = "";
$database = "members";
$desc = $_POST['desc'];
$con = mysql_connect($hostname, $user, $password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $con) or die( "Unable to select database");
if(isset($_POST['sign_up']))
{
if(isset($_POST['username'])){
$username = $_POST['username'];
}
else {
echo "The username is not set"; die;
}
if(isset($_POST['email'])){
$email = $_POST['email'];
}
else {
echo "The email is not set"; die;
}
if(isset($_POST['zip'])){
$zip = $_POST['zip'];
}
else {
echo "The zip code is not set"; die;
}
if(isset($_POST['address'])){
$address = $_POST['address'];
}
else {
echo "The gender is not set"; die;
}
if(isset($_POST['sex'])){
$sex = $_POST['sex'];
}
else {
echo "The gender is not set"; die;
}
if(isset($_POST['passid_1'])){
$passid = $_POST['passid_1'];
}
else {
echo "The password is not set"; die;
}
if(isset($_POST['passid_2'])){
$passid2 = $_POST['passid_2'];
}
else {
echo "The re-entered password is not set"; die;
}
if($passwid == $passid2){
$correctpid = $passwid;
}
else {
echo "The passwords do not match"; die;
}
$sql = "INSERT INTO members_t('Name', 'Email', 'Password', 'Phone', 'Address', 'Sex', 'More') VALUES('$username', '$email','$correctpid', '$zip', '$address', '$sex', '$desc');";
mysql_query($sql) or die(mysql_error());
mysql_close($con);
echo "Successfolly run database query!";
}
else
{
echo("Failed to update database!!!");
}
?>
I have made the php code to check if all the fields are filled with data. If not the site die and gives them a error message. It kills the website before it can set anything into the database.
-- I made some more changes to the code after comments, thanks btw.

Register PHP/SQL won't insert longtext fields

OK so my register system is correctly inserting into my database the username, password, and e-mail but not any other fields. I first tried putting the values directly into the SQL query and then put them in the form as hidden text fields. The direct values gave an SQL syntax error and the hidden text doesn't insert anything but successfully adds the user, pass, and email. All MYSQL field types are LONGTEXT. Here's the code.
Register.php
<form name="register" method="post" action="register2.php"><br />
Username<br><input name="username" type="text" size="20" /><br /><br />
Password<br><input name="password" type="password" size="20" /><br /><br />
E-mail<br><input name="email" type="text" size="20" /><br /><br />
<input="hidden" id="status" type="text" value=Waiting for a request size="100" />
<input="hidden" id="request" type="text" value="None sent" size="100" />
<input="hidden" id="paid" type="text" value="Please pay for an instant spot" size="100" />
<input="hidden" id="priority" type="text" value="To be determined by your web designer" size="100" />
<input="hidden" id="files" type="text" value="None" size="100" />
<input="hidden" id="filespass" type="text" value=None" size="100" /><div id="captcha2">
<img id="captcha" src="securimage/securimage_show.php" alt="CAPTCHA Image" /><br><br>Please re-write the security code below<br><input type="text" name="captcha_code" size="10" maxlength="6" size="20"/></div>
<br>
<input type="submit" name="submit" value="Register" /><br><br>
<a href='forgot.php'>Forgot</a> your password?<br>
</form>
Register2.php
<?php
include_once 'securimage/securimage.php';
$securimage = new Securimage();
if ($securimage->check($_POST['captcha_code']) == false) {
// the code was incorrect
// you should handle the error so that the form processor doesn't continue
// or you can use the following code if there is no validation or you do not know how
echo "The security code entered was incorrect.<br /><br />";
echo "Please go <a href='javascript:history.go(-1)'>back</a> and try again.";
exit;
}else{
$con = mysql_connect(secret);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dylanmediagroup", $con);
$username = htmlspecialchars($_POST['username']);
$password = htmlspecialchars($_POST['password']);
$email = htmlspecialchars($_POST['email']);
$status = htmlspecialchars($_POST['status']);
$priority = htmlspecialchars($_POST['priority']);
$paid = htmlspecialchars($_POST['paid']);
$files = htmlspecialchars($_POST['files']);
$filespass = htmlspecialchars($_POST['filespass']);
$checkuser = mysql_query("SELECT * FROM users WHERE username ='$username'");
$checkemail = mysql_query("SELECT * FROM users WHERE email='$password'");
if(mysql_num_rows($checkuser) > 0 ) { //check if there is already an entry for that username
echo "<img src='http://www.myhealthguardian.com/wp-content/uploads/2010/01/sad-face.gif' width='25%' height='21%'><br><br>Account already registered.<br> <a href='forgot.php'>Forgot</a> your password?<br><br>";
} else {
$sql="INSERT INTO `users` (username, password, email, status, priority, paid, files, filespass) VALUES ('$username', '$password', '$email', '$status', '$priority', '$paid', '$files', '$filespass')";
}
if (!mysql_query($sql,$con))
{
}else{
echo "<img src='http://3.bp.blogspot.com/-vpsc13PCfc0/TaLCGaq2SjI/AAAAAAAACTA/hw2MDzTk6mg/s1600/smiley-face.jpg' height='21%' width='25%'><br><br>Your registration was successful, please <a href='login.php'>login</a> to continue.";
}
}
mysql_close($con)
?>
You're using id instead of name for your hidden inputs.
And please use this syntax:
<input type="hidden" name="name" value="value" />
Also one of your values seem to break the string since it has quotation marks in it.

Categories