Not inserting values to database: - php

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.

Related

PHP SQL Form Insert Creation

I am trying to create a simple form that will insert the given data received by my HTML form, into my SQL table named 'Vendors', however I am struggling to work with its functionality.
There are 7 text fields that I am wanting to add to my Vendors table, and these are so named:
vendorName
addressL1 (Line 1)
addressL2
postcode
email
telephone
description
The HTML for this form can be found below:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form action="" method="post">
<ul class="form-style-1">
<li>
<label style="color:#4D4D4D;" >Vendor Name <span class="required">*
</span></label>
<center> <input type="text" name="vendorName" class="field-long"
required="required" placeholder="Vendor Name" /> </center>
</li>
<li>
<label style="color:#4D4D4D;">Vendor Address <span class="required">*
</span></label>
<center> <input type="text" name="addressL1" required="required"
class="field-long" placeholder="Address Line 1" /> </center>
</br>
<center> <input type="text" name="addressL2" required="required"
class="field-long" placeholder="Address Line 2" /> </center>
</br>
<center> <input type="text" name="postcode" required="required"
class="field-short" placeholder="Postcode" /> </center>
</li>
<li>
<label style="color:#4D4D4D;">Vendor Contact Details <span
class="required">*</span></label>
<center> <input type="text" name="email" required="required"
class="field-long" placeholder="Email Address" /> </center>
</br>
<center> <input type="text" name="telephone" required="required"
class="field-long" placeholder="Phone Number" /> </center>
</select>
</li>
<li>
<label style="color:#4D4D4D;">Vendor Description </label>
<center> <textarea name="description" id="field5" class="field-long
field-textarea" placeholder="Description"></textarea> </center>
</li>
<li>
<center> <input type="submit" class="AddButton" value="POST"></input>
</center>
</li>
</ul>
</form>
</body>
</html>
And the PHP I have used is:
<?php
date_default_timezone_set('Europe/London');
$server = "";
$connectionInfo = array( "Database"=>"");
$conn = sqlsrv_connect($server,$connectionInfo);
if (!$conn)
{
die("Connection failed");
}
$_SERVER['REQUEST_METHOD'];
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$VendorName = $_POST['vendorName'];
$AddressLine1 = $_POST['addressL1'];
$AddressLine2 = $_POST['addressL2'];
$Postcode = $_POST['postcode'];
$VendorEmail = $_POST['email'];
$VendorNumber = $_POST['telephone'];
$VendorDes = $_POST['description'];
$time = time();
$timestamp = date("Y-m-d H:i:s", $time);
$describeQuery = ("INSERT INTO Vendors (VendorName, VendorAL1,
VendorAL2, VendorPost, VendorEmail, VendorNumber, VendorDes,
Added)
VALUES ('".$VendorName."', '".$AddressLine1."',
'".$AddressLine2."', '".$Postcode."',
'".$VendorEmail."', '".$VendorNumber."',
'".$VendorDes."', '".$timestamp."')");
$results = sqlsrv_query($conn, $describeQuery);
if(sqlsrv_query($conn, $describeQuery))
{
$alert = "Vendor Successfully Added";
echo "<script type='text/javascript'>alert('$alert');
</script>";
}
else
{
echo 'Information not inserted';
}
}
sqlsrv_close($conn);
?>
Each time I submit the form, it goes straight to the 'Information not inserted' ELSE statement and doesn't import the data into my database.
I have removed my server name and database name for precautionary reasons, however I can assure you they are correct as I have worked on a previous project and used the same method of connecting.
Any help on this would be greatly appreciated, and if there are any formatting mistakes, apologies in advance, I am not an avid user of stack overflow.
Use Mysqli Please, I have updated the script.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Vendors (VendorName, VendorAL1,
VendorAL2, VendorPost, VendorEmail, VendorNumber, VendorDes,
Added)
VALUES ($VendorName, $AddressLine1, $AddressLine2,$Postcode,$VendorEmail,$VendorNumber,$VendorDes,$timestamp)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>

HTML post to PHP

Trying to insert data into my table but I keep getting an undefined index because there are "no value set when I submit my form". The if (isset($_POST['submit'])) removes my error even when I run the .php alone but no data is inserted when I submit my form. Any help is appreciated. Thank you
My form.html
<form name="supportForm" class="form" action="database.php" method="POST" onsubmit="return validateForm()">
<label>Name:</label>
<input type="text" name="name"/>
<br/>
<label>Client ID:</label>
<input type="text" name="clientID"/>
<br/>
<label>E-mail address:</label>
<input type="email" name="email"/>
<br/>
<label>Phone number:</label>
<input type="tel" name="tel"/>
<br/>
<br/>
Support Type:<br>
<input type="radio" name="suppType" value="Question/Inquiry">Question/Inquiry<br>
<input type="radio" name="suppType" value="Software">Software Issue<br>
<input type="radio" name="suppType" value="Hardware">Hardware Issue<br>
<input type="radio" name="suppType" value="Connectivity">Connectivity<br>
</br>
Operating System:
<select id="select">
<option disabled selected value="">Choose a product</option>
<option value="w7" name="OS">Windows 7</option>
<option value="w8" name="OS">Windows 8/8.1</option>
<option value="w10" name="OS">Windows 10</option>
</select>
<br> </br>
Problem Description:
<br><textarea id="ta" rows="10" cols="80" name="pDesc"></textarea></br>
<input type="checkbox" name="terms" value="agree">
I agree to the terms and conditions.
<br> </br>
<input type="hidden" name="submitted" value="true">
<input type="submit" name="submit" onClick="validateSubmit()">
</form>
My PHP file
<?php
//Creates static credentials
define('DB_NAME', 'data');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
//Creates connection to the database
$con = new mysqli(DB_HOST, DB_USER, DB_PASSWORD);
//Checks for connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
//If there are no connection, error
if (!$con) {
die ('Could not connect' . mysqli_error());
}
//Select the 'data' database
$con->select_db(DB_NAME);
//Checks if database 'data' has been selected
if (mysqli_select_db($con, DB_NAME)) {
echo "Database exists <br>";
} else {
echo "Database does not exist";
}
//Successful connection message
echo "Connected successfully <br>";
if (isset($_POST['submit'])) {
//Retrieving values from support form
$name = $_POST['name'];
$clientID = $_POST['clientID'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$suppType = $_POST['suppType'];
$OS = $_POST['OS'];
$pDesc = $_POST['pDesc'];
//Inserting values into a table
$sql = "INSERT INTO info (fullname, clientID, email, tel,
suppType, OS, pDesc)
VALUES ($name, $clientID, $email, $tel,
$suppType, $OS, $pDesc)";
if (!mysqli_query($con, $sql)) {
echo "No data";
} else {
echo "Data recorded successfully";
}
}
//Closes connection
mysqli_close($con);
You must write name="OS" in <select> not in <option>
<select id="select" name="OS">
<option disabled selected value="">Choose a product</option>
<option value="w7">Windows 7</option>
<option value="w8">Windows 8/8.1</option>
<option value="w10">Windows 10</option>
</select>
And Sql must be like this you need apostrophes ('') around variables
$sql = "INSERT INTO `info` (fullname, clientID, email, tel, suppType, OS, pDesc)
VALUES ('$name', '$clientID', '$email', '$tel', '$suppType', '$OS', '$pDesc')";
You not showing us the validateForm() function, therefore we won't really know whats happening there, nonetheless I have edited your form and did a validation using php,
what you need to do first is to check if all values are set before jumping to insert into db, and make sure email is a proper email, also the select option the name attribute needs to be on the select tag not on the option tag, the option must only have values.
Then Validate,Filter and sanitize user input before storing to the
database. Treat every userinput on your form as if its from a very dangerous hacker.
There's something called prepared statements, in mysqli and PDO you should try to learn that and use it :) you will enjoy it, I will leave it to you to research as to why you need to use prepared statements.
This is how your code should look
<form name="supportForm" class="form" action="database.php" method="POST">
<label>Name:</label>
<input type="text" name="name"/>
<br/>
<label>Client ID:</label>
<input type="text" name="clientID"/>
<br/>
<label>E-mail address:</label>
<input type="email" name="email"/>
<br/>
<label>Phone number:</label>
<input type="tel" name="tel"/>
<br/>
<br/>
Support Type:<br>
<input type="radio" name="suppType" value="Question/Inquiry">Question/Inquiry<br>
<input type="radio" name="suppType" value="Software">Software Issue<br>
<input type="radio" name="suppType" value="Hardware">Hardware Issue<br>
<input type="radio" name="suppType" value="Connectivity">Connectivity<br>
</br>
Operating System:
<select id="select" name="OS">
<option value="0">Choose a product</option>
<option value="w7">Windows 7</option>
<option value="w8">Windows 8/8.1</option>
<option value="w10">Windows 10</option>
</select>
<br> </br>
Problem Description:
<br>
<textarea id="ta" rows="10" cols="80" name="pDesc"></textarea>
</br>
<input type="checkbox" name="terms" value="agree">
I agree to the terms and conditions.
<br> </br>
<input type="hidden" name="submitted" value="true">
<input type="submit" name="submit">
</form>
Then database.php
<?php
//Creates static credentials
define('DB_NAME', 'data');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
$errors = ""; //checking for errors
//Creates connection to the database
$con = new mysqli(DB_HOST, DB_USER, DB_PASSWORD);
//Checks for connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
//If there are no connection, error
if (!$con) {
die('Could not connect' . mysqli_error());
}
//Select the 'data' database
$con->select_db(DB_NAME);
//Checks if database 'data' has been selected
if (mysqli_select_db($con, DB_NAME)) {
echo "Database exists <br>";
} else {
echo "Database does not exist";
}
//Successful connection message
echo "Connected successfully <br>";
if (isset($_POST['submit'])) {
//check values are set
if (empty($_POST['name'])) {
echo "enter name";
$errors++;
} else {
$name = userIput($_POST['name']);
}
if (empty($_POST['clientID'])) {
echo "enter id";
$errors++;
} else {
$clientID = userIput($_POST['clientID']);
}
if (empty($_POST['email'])) {
echo "enter email";
$errors++;
} else {
$email = userIput($_POST['email']);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) { //validate email,
echo "enter valid email";
$errors++;
}
}
if (empty($_POST['tel'])) {
echo "enter tel";
$errors++;
} else {
$tel = userIput($_POST['tel']);
}
if (!isset($_POST['suppType'])) {
echo "select one option";
$errors++;
} else {
$suppType = userIput($_POST['suppType']);
}
if (isset($_REQUEST['OS']) && $_REQUEST['OS'] === "0") {
echo "please select product";
$errors++;
} else {
$OS = userIput($_POST['OS']);
}
if (empty($_POST['pDesc'])) {
echo "enter Description";
$errors++;
} else {
$pDesc = userIput($_POST['pDesc']);
}
if ($errors <= 0) { // No errors
//prepare and insert query
$sql = $con->prepare("INSERT INTO info (fullname, clientID, email, tel,suppType, OS, pDesc) VALUES (?, ?, ?, ?, ?, ?, ?)");
$sql->bind_param("sssssss", $name, $clientID, $email, $tel, $suppType, $OS, $pDesc);
if ($sql->execute()) {
echo "records inserted successfully";
} else {
echo "Could not insert " . mysqli_error();
}
$sql->close();
$con->close();
}
}
function userIput($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Hope this will help a little, and you will learn a thing or two, and I'm always available for suggessions, just incase I missed something. Thanks

how to check whether old password entered is present or not in db

I m having a login page where user enters id and password.To reset the password i have to check whether the entered password is present or not whether it matches with the id i have entered.How to validate it.I m unable to validate it. If user enters any password it displays the record is updated. How to validate it. Here is the code
login.php
<label type="text" name="id" maxlength="50" size="20">ID</label><br />
<input type="text" name="id" placeholder="ID" class="input" size="20"/><br /></div>
<div class="formItem">
<label type="text" name="uid" maxlength="50" size="20">Password</label><br />
<input type="password" name="uid" placeholder="ID" class="input" size="20"/><br /></div>
<span class="field">(* Required field)</span><br /><br />
<input type="submit" name="login1" value="LOGIN" class="button"><br /><br /><br /><br />
</form>
</div>
</body>
</html>
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$db = "abc";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
mysql_select_db($db,$dbhandle) or die('cannot select db');
if(isset($_POST['login1']))
{
$id= $_POST['id'];
$uid= $_POST['uid'];
$query= "select * from resume where id='$id'
AND uid='$uid'";
$run= mysql_query($query);
if(mysql_num_rows($run)>0){
echo "<script>window.open('resetp.php','_self')</script>";
}
else {
echo "<script>alert('Login details are incorrect!')</script>";
}
}
?>
resetp.php
<label type="text" name="uid" maxlength="50" size="20">Old Password</label><br />
<input type="text" name="uid" placeholder="id" class="input" size="20"/><br /></div>
<div class="formItem">
<label type="text" name="uid" maxlength="50" size="20">New Password</label><br />
<input type="password" name="pass" placeholder="pass" class="input" size="20"/><br /></div>
<div class="formItem">
<label type="text" name="cpas" maxlength="50" size="20">Confirm Password</label><br />
<input type="password" name="cpas" placeholder="" class="input" size="20"/><br /></div>
<div class="formItem">
<input type="submit" name="login1" value="RESET" class="formButton"><br /><br /><br /><br /></div>
</form>
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$db = "resume1";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
mysql_select_db($db,$dbhandle) or die('cannot select db');
if(isset($_POST['login1']))
{
$pass= $_POST['pass'];
$uid= $_POST['uid'];
$cpas=$_POST['cpas'];
$query = "Update `resume` SET uid='".$_POST['pass']."' where uid='".$_POST['uid']."'";
$run = mysql_query($query);
if($query)
{
echo "<script>alert('Record updated')</script>";
}
else
{
echo "<script>alert('no')</script>";
}
}
?>
How can i validated it
Try this:
This line
<label type="text" name="uid" maxlength="50" size="20">New Password</label><br />
should be
<label type="text" name="pass" maxlength="50" size="20">New Password</label><br />
I guess couldn't understand your requirement.
Why don't you validate like you are doing in login.php
$query= "select * from resume where id='$id'
AND uid='$uid'";
$run= mysql_query($query);.................
the PHP script should be at the beginning, not at the end of the code. Begin with the <?php .... ?> and then follow the <HTML> ... </HTML> otherwise the result is returned even before the script is processed.
There are a lot of security issues with your code. You can try this.
<?php
require 'db.php';
$username = isset($_POST['username']) ? htmlspecialchars(trim($_POST['username']), ENT_QUOTES, 'UTF-8') : '';
$password = isset($_POST['password']) ? htmlspecialchars($_POST['password'], ENT_QUOTES, 'UTF-8') : '';
$error = array();
$error_found = 0;
if(isset($_POST['submit']) && ($_POST['submit'] == 'Reset'))
{
//check for errors.
//check if username field is empty.
if(empty($username))
{
$error[] = 'Please provide your user-name.';
}
//check if password field is empty.
if(empty($password))
{
$error[] = 'Please provide a password.';
}
//if errors exist, put errors found as true.
if(!empty($error))
{
$error_found = 1;
}
//else no errors are found.
else
{
//proceed to reset.
//connecting to database.
$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or die('Unable to connect, check your connection parameters. ');
mysql_select_db(MYSQL_DB, $db) or die('Could not select database, check availability. ' . mysql_error($db));
//querying the database. Checking if user-name password combination exists.
$query = 'SELECT username FROM resume WHERE username = "' . mysql_real_escape_string($username, $db) .
'" AND password = PASSWORD("' . mysql_real_escape_string($password, $db) . '")';
$result = mysql_query($query, $db) or die(mysql_error($db));
//checking if result is true.
if(mysql_num_rows($result) > 0)
{
//the result is true and so you can now reset your password.
}
else
{
$error[] = 'The username password combination you provided does not exist.';
$error_found = 1;
}
}
}
//HTML
?>
<!DOCTYPE HTML>
<html>
<head><title> ... </title></head>
<body>
<!--Your html code here -->
<?php
//if errors are found, then errors are shown here.
if($error_found == 1)
{
echo '<fieldset><center>';
echo '<ul>';
foreach($error as $e)
{
echo '<li>' . $e . '</li>';
}
echo '</ul>';
echo '</center></fieldset>';
}
?>
<form action="nameOfThisScript.php" method="POST">
Username:<input id="username" type="text" name="username" required />
Password:<input id="password" type="password" name="password" required />
<button id="Reset" type="submit" name="submit" value="Reset">Reset</button>
</form>
</body>
</html>
create a script named db.php in the same folder as this script and put the code
<?php
define('MYSQL_HOST', 'localhost');
define('MYSQL_USER', 'root');
define('MYSQL_PASSWORD', '');
define('MYSQL_DB', 'resume1');
?>
Hope this helps.

Prossessing checkbox value in a php form connected to mysql database

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.."
}
?>

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