I am trying to insert into database the form data but it is not working, I have added the code below. Please check and inform me what the problem is. As the deletion and search queries are working but insertion is the only query that are not working. Thanks
<form method="post" action= "assign5.php">
Name : <input type ="text" name="name" >
<br>
Flavor : <select name="flavor">
<option value="Chocolate">Chocolate</option>
<option value="Vanilla">Vanilla</option>
<option value="Strawberry">Strawberry</option>
<option value="MahngiVanilla">MahngiVanilla</option>
<option value="SastiStrawberry">SastiStrawberry</option>
</select>
<br>
Scoops:
<input type ="radio" name="scoops" value="1">1</input>
<input type ="radio" name="scoops" value="2">2</input>
<input type ="radio" name="scoops" value="3">3</input>
<input type ="radio" name="scoops" value="4">4</input>
<input type ="radio" name="scoops" value="5">5</input>
<input type ="submit" name="button" value="Place Order"/>
<br>
<br>
</form>
<?php
require_once 'login.php';
$connection = new mysqli($db_hostname,$db_username,$db_password,$db_database);
if($connection ->connect_error) die($connection ->connect_error);
if(isset($_POST['name']) && isset($_POST['Flavour']) && isset($_POST['Scoops']) ){
$CName=$_POST['name'];
$Flavor=$_POST['flavor'];
$Scoops=$_POST['scoops'];
$sql ="INSERT INTO orders VALUES (CName, Flavour, Scoops) VALUES ('$CName', '$FLAVOUR', '$Scoops')";
$result=$connection->query($sql);
if(!$result) die($connection->error);
header("Location: assign5.php");
}
$connection->close();
?>
You must have to provide name, flavour & scopps from form. Even you provided but still your query does not work. Because your input key at form is small letter and you checking it at condition using Capital letter of first character. So try it
if(isset($_POST['name']) && isset($_POST['flavour']) && isset($_POST['scoops']) ){
.....
.....
}
You used Values in two times. Please correct this from
$sql ="INSERT INTO orders VALUES (CName, Flavour, Scoops) VALUES ('$CName', '$FLAVOUR', '$Scoops')";
To:
$sql ="INSERT INTO orders (CName, Flavour, Scoops) VALUES ('$CName', '$FLAVOUR', '$Scoops')";
As you are not sanitizing user input nor are you using prepared statements you could simply do the following and avoid the spelling / capitalisation errors:
$sql ="INSERT INTO orders (CName, Flavour, Scoops)
VALUES
('{$_POST['name']}', '{$_POST['flavor']}', '{$_POST['scoops']}')";
Also, the use of values before the field/column names was incorrect - it comes after the column names!
Note: It would be far, far better to use prepared statements however!
Untested example of prepared statements for this use case would be perhaps:
$sql = 'insert into `orders` (`cname`,`flavour`,`scoops`)' values(?,?,?);
$stmt = $connection->prepare( $sql );
if( $stmt ){
$name=$_POST['name'];
$flavour=$_POST['flavor'];
$scoops=intval( $_POST['scoops'] );
$stmt->bind_param('ssi',$name,$flavour,$scoops);
$result = $stmt->execute();
echo $result ? 'OK' : 'Bad Foo!';
}
Related
Below is code that I am using, when i submit the survey, arrrive and mode work but not trans/checkboxes, data comes back displayed as 'on' in table (survey) database (wdtlabwork), also the field is trans, same with the other two being mode n arrive in the database, all fields were type VARCHAR. Apologies if formatting is bad i am new to site. NOTE: I want the data to come back as either car, train or bus but because its checkboxes if the user checked train and car i want the database to display train and car.
HTML
<section id="content">
<form action="connect.php" method="post">
<div class="col-6 col-s-9">
<h3>Available Transportation?</h3>
<input id="trans1" type="checkbox" name="trans[]"><label for ="trans1">Car</label>
<input id="trans2" type="checkbox" name="trans[]"><label for ="trans2">Train</label>
<input id="trans3" type="checkbox" name="trans[]"><label for ="trans3">Bus</label>
<h4>How do you intend to arrive at the Hostel?</h4>
<input id="arrive1" type="radio" value="car" name="arrive"><label for="arrive1">Car</label>
<input id="arrive2" type="radio" value="train" name="arrive"><label for="arrive2">Train</label>
<input id="arrive3" type="radio" value="bus" name="arrive"><label for="arrive3">Bus</label>
<h5>Preferred mode of transport?</h5>
<select name="mode">
<option selected hidden value="">Select Option</option>
<option value="car">Car</option>
<option value="train">Train</option>
<option value="bus">Bus</option>
</select><input type="submit" class="btn btn=primary"></div></section>
PHP
<?php
$arrive = $_POST['arrive'];
$trans = $_POST['trans'];
$mode = $_POST['mode'];
$conn = new mysqli('localhost', 'root','','wdtlabwork');
if ($conn->connect_error){
die('Connection Failed : '.$conn-> connect_error);
}else{
$stmt = $conn->prepare("insert into survey(trans, arrive, mode)
values(?, ?, ?)");
$stmt->bind_param("sss",$trans, $arrive, $mode);
$stmt->execute();
echo "registration successfully...";
$stmt->close();
$conn->close();
}
?>
Your input fields do not have value= attribute so they default to on as described here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox#Value
To get the values in the POST you need to specify the values, for example:
<input id="trans1" type="checkbox" name="trans[]" value ="car"><label for ="trans1">Car</label>
<input id="trans2" type="checkbox" name="trans[]" value ="train"><label for ="trans2">Train</label>
<input id="trans3" type="checkbox" name="trans[]" value ="bus"><label for ="trans3">Bus</label>
Then in your PHP you would receive an array of the selected elements in $_POST['trans']. If you would like to join them (not recommended) to be saved in a single field in the database you can just use implode(',', $_POST['trans']), for example:
$trans = implode(',', $_POST['trans']);
$arrive = $_POST['arrive'];
$mode = $_POST['mode'];
I have come across a problem when inserting values from a html select in to a mysql database. I can't seem to get the values to insert for some reason; I have looked for help on this but they keep giving me errors.
Also, can some please tell me what the difference between mysql and mysqli?
php code
<?php
$con = mysql_connect("localhost","barsne","bit me");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("testing", $con);
$sql="INSERT INTO client_details (id, f_name, l_name, phone, email, job_est) VALUES
('', '$_POST[f_name]', '$_POST[l_name]', '$_POST[phone]', '$_POST[email]', '$_POST[job_est]')";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
echo "Thank you for booking a with us we will contact you in the next 24 hours to confirm your booking with a time and date";
mysql_close($con)
?>
html code
<form method="post" action="processing_booking.php">
<h4><u>Basic Contact Details</u></h4>
<label>First Name</label>
<input type="text" name="f_name">
<label>Last Name:</label>
<input type="text" name="l_name" id="l_name">
<label>Phone Number:</label>
<input type="text" name="phone" id="phone">
<label>Email:</label>
<input type="text" name="email" id="email">
<h4><u>Job Details</u></h4>
<label>You Would Like To Book A:</label>
<select name="job_est">
<option value="select">--SELECT--</options>
<option value="job">Job</option>
<option value="est">Estimation</option>
</select>
<label>Service Your Booking:</label>
<select name="job_type">
<option value="select">--SELECT--</option>
<option value="gardening">Gardening</option>
<option value="landscaping">Landscaping</option>
<option value="painting">Painting & Decorating</option>
<option value="decking">Decking & Fencing</option>
</select>
<label>Any Additional Information </label>
<textarea name="extra_info"></textarea>
<input type="submit" value="lets get your dreams started">
</form>
sorry wirting is not my strong point
Note that $_POST['name'] you missed single quotations
you must prevent from injection with
// String Type Fields
$name = strip_tags($_POST['name']);
$f_name= strip_tags($_POST['f_name']);
$l_name= strip_tags($_POST['l_name']);
$phone= strip_tags($_POST['phone']);
$email= strip_tags($_POST['email']);
// Int Type Fields
if (isset($_POST['job_est']) && is_numeric($_POST['job_est']))
$job_est= $_POST['job_est'];
else
$job_est= 0;
then use in your query
other point is
if your id field is primary and auto increment , you can define your query as below :
$sql="INSERT INTO client_details (f_name, l_name, phone, email, job_est) VALUES
( '".$f_name."', '".$l_name."', '".$phone."', '".$email."', ".$job_est.")";
for strings you must use '".$variable."'
and for integer or numeric you must use ".$variable."
other point is you must change your select element to below because you have noticed in your comments your job_est field type is int(11)
<select name="job_est">
<option value="0">--SELECT--</option>
<option value="1">Gardening</option>
<option value="2">Landscaping</option>
<option value="3">Painting & Decorating</option>
<option value="4">Decking & Fencing</option>
</select>
The mysql functions are deprecated. Use the mysqli or pdo class
instead.
mysqli: https://php.net/manual/en/class.mysqli.php
pdo: https://php.net/manual/en/book.pdo.php
Make a var_dump($_POST) and you will see what the problem is. By the way you missed the single quotes $_POST['value']
Never ever write $_POST or $_GET data directly in your sql queries. Always validate them before, because even the value of a selectbox can get easily changed with tampadata or chrome developer tools.
Well you can obviously start printing the results of your $_POST array with :
print_r($_POST,1);
to check all variables existence in it
so im trying to store values from a checkbox into my database
It works if I use a normal Textbox but as soon as I attempt it with a checkbox it doesnt work any idea? I want to have two for example checkbox1 and checkbox2 there values should be stored in my database colums for example Colum1 colum2.
Thanks in advance for anyhelp
<form name="checkbox.php" id="names" action="<?php echo JURI::current(); ?>" method="post">
<p><input type="checkbox" name="game" value="ExampleGame" />b</p>
<p><input type="checkbox" name="Age" value="ExampleAge" />b</p>
<p><input id="submit" name="submit" type="submit" value="Submit Names" /></p>
</form>
<?
if( (isset($_POST['game'])) || (isset($_POST['Age'])) ) {
//first name or last name set, continue-->
$game = $_POST['game'];
$Age= $_POST['Age'];
$db =& JFactory::getDBO();
$query = "INSERT INTO `gameTable` (`game`, `Age`)
VALUES ($game, $age);";
$db->setQuery( $query );
$db->query();
} else {
echo '<h4>One Field Is Required!</h4>';
}
?>
Try this
$query = "INSERT INTO `gameTable` (`game`, `Age`) VALUES ('".$game."','".$age."', )";
Check the values that come back from your form:
$game = $_POST['game'];
$Age= $_POST['Age'];
You should find that if the checkbox isn't selected, no value (in fact, no field) is returned.
That may be your problem.
Use some alerts for troubleshooting:
echo $_POST['game'];
echo $_POST['Age'];
echo $_POST['query'];
Even when you don't know what you are doing/doing wrong, try to troubleshoot the problem.
Alerts help alot in PHP to check if you get the values on your variables that you expect.
If you get your query string, test this directly on your database.
I resolve with this easy way:
<input type="checkbox" name="field_name" value="N" style="display: none;" checked />
On mysql database i have create a trigger
if new.field_name= '' then set new.field_name= 'S';
I am working on a system and i want to check if a record exist. If a record exist then it will not record the data and instead will return to the form. If the data does not exist then it will proceed to recording the data to DB.
HTML form:
<form name="studentform" onSubmit="return validate_form ( );" action="queries/insert.php" method="post">
Student Number: <input type="text" name="studentnumber"/>
College:
<select name="college" id=a></select>
Course:
<select name="course" id=b></select>
<input type="radio" name="status" value="regular" />Regular
<input type="radio" name="status" value="irregular" />Irregular
<br><br>
<hr>
<br>
Name:
<input type="text" name="lname">
<input type="text" name="fname">
<input type="text" name="mname">
Address:
<input type="text" name="address" />
<br><br>
Gender:
<select name="gender">
<option value="">---</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<input type="submit" value="Submit">
</form>
PHP form:
$query = ("SELECT studentnumber FROM students where studentnumber = '$_POST[studentnumber]'");
$result=mysql_query($query);
if($result)
{
if(mysql_num_rows($result) >= 1)
{
echo "<script type='text/javascript'>alert('User already exist'); location.href = '../admin_home.php';</script>";
}
}
else{
$sql="INSERT INTO students (studentnumber, college, course, status, lname, fname, mname, address, gender)
VALUES
('$_POST[studentnumber]','$_POST[college]','$_POST[course]','$_POST[status]','$_POST[lname]','$_POST[fname]','$_POST[mname]','$_POST[address]','$_POST[gender]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "<script type='text/javascript'>alert('Record Successfully Added'); location.href = '../admin_home.php';</script>";
}
I don't know why but i always get the undefined index error. Maybe i've done something wrong somewhere. Thanks !!
"Undefined index" is referring to your array ($_POST, probably), and it should be a notice, not an error. Can you post the exact message?
In the meantime, switch your first line for
$query = "SELECT studentnumber FROM students where studentnumber = '".mysql_real_escape_string($_POST['studentnumber'])."'";
Also, it's helpful for debugging to print out the query to make sure it looks like you'd expect:
print $query."<br />"; // obviously
[edit]As you've now posted the error message, it becomes far more simple - $_POST['studentnumber'] does not exist. Check your form.
A good way to debug posted results is to use the code
print '<pre>';
print_r($_POST);
print '</pre>';
The problem is in your queries:
$query = ("SELECT studentnumber FROM students where studentnumber = '$_POST[studentnumber]'");
$_POST[studentnumber] is not correct. It needs to be $_POST['studentnumber']. Notice the quotes around the key.
I suggest doing it this way:
$query = sprintf("SELECT studentnumber FROM students where studentnumber = '%s'"
, mysql_real_escape_string($_POST['studentnumber']));
Change all your queries accordingly.
try with this:
if( isset($_POST['submit']) ){
$student_num = mysql_real_escape_string( $_POST['studentnumber'] );
// Set all the require form fields here with mysql_real_escape_string() fun
if( !empty($student_num) ){
// Your Query Here
}
else{
echo 'Value not Set in Student Number Field!';
}
}
Edit: first check all the fields after isset($_POST['submit']) so that you confirm about all the values are properly getting or not
after getting all the required values start your query
How can i populate a mysql database with more than 1 dropdown lists ?
My code in html page is:
<form method="post" action="submit.php">
Number: <select name="number">
<option value="535">535</option>
<option value="338">228</option></select>
<br>
Name: <select name="name">
<option value="John">John</option>
<option value="Dave">Dave</option></select>
<br>
<input type="submit" value="Add" />
</form>
My code in php is:
$Number = $_POST['number'] ;
$Name = $_POST['name'] ;
$query = "INSERT INTO submit (Number,Name) VALUES ('number','name')";
mysql_query($query) or die('Error Updating Database');
echo "Added";
Yes, you can store the values from two different select lists in a MySQL query, but you need to actually insert the values that come back in $Number and $Name like so:
$Number = mysql_real_escape_string($_POST['number']);
$Name = mysql_real_escape_string($_POST['name']);
$query = "INSERT INTO submit (Number,Name) VALUES ('$Number','$Name')";
mysql_query($query) or die('Error Updating Database');
echo "Added";
I have also added mysql_real_escape_string() to help sanitise the user input before blindly inserting it into a database. This is a basic anti-SQL Injection measure.
Of course you also need to already be connected to the MySQL server and have selected a database.