More than 1 Dropdown lists HTML/PHP-Mysql - php

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.

Related

Unable to post a value selected from db in a drop down box

I had spent some time trying to get the drop down box working correctly, getting the values of department and location to populate from the DB. This is working fine and I have added additionally date fields so a customer can select records for a specific period, location and department. When I action the form running departmentReport.php the page returns blank even when trying to echo each value as seen below.
<form id="departmentReport" action="departmentReport.php" method="get" onsubmit="#">
<fieldset id="departmentReport">
<h3>Department Report</h3>
<br>
<?php
include 'includes/DbCon.php';
$sql = "select department_name from departments";
echo"<select name = 'departments' value=''>Department Name</option>";
foreach ($conn->query($sql) as $row){
echo "<option value=$row[department_name]>$row[department_name]</option>";}
echo "</select>";
?>
<br></br>
<?php
include 'includes/DbCon.php';
$sql = "select `location_name` from `location`";
echo "<select name = 'location' value=''>Location Name</option>";
foreach ($conn->query($sql) as $row){
echo "<option value=$row[location_name]>$row[location_name]</option>";}
echo "</select>";
?>
<br></br><br>
<label for="date">Date From<br></label>
<input id="date1" type="date" name="dateF"
autofocus="true"/>
<br>
<br>
<label for="date">Date To<br></label>
<input id="date2" type="date" name="date2"
autofocus="true"/>
<br>
<br>
<input type="submit" class="button" value="Submit">
On Submit departmentReport.php is actioned
<?php
include "../includes/dbCon.php"; //* CONNECTION TO DATABASE
$department = mysqli_real_escape_string($conn, $_POST['departments']); //* CLEAN DATA, THIS DELETES ANY SPECIAL CHARACTERS THAT CAN BE USED FOR MALICIOUS CODE
$location = mysqli_real_escape_string($conn, $_POST['location']); //* CLEAN DATA, THIS DELETES ANY SPECIAL CHARACTERS THAT CAN BE USED FOR MALICIOUS CODE
$date1 = mysqli_real_escape_string($conn, $_POST['date1']); //* CLEAN DATA, THIS DELETES ANY SPECIAL CHARACTERS THAT CAN BE USED FOR MALICIOUS CODE
$date2 = mysqli_real_escape_string($conn, $_POST['date2']); //* CLEAN DATA, THIS DELETES ANY SPECIAL CHARACTERS THAT CAN BE USED FOR MALICIOUS CODE
echo "$department";
echo "$location";
echo "$date1";
echo "$date2";
This brings the results below..
However when adjusting post to get I see the values I selected
http://localhost:8888/departmentReport.php?departments=Marketing&location=London&dateFrom=02%2F01%2F2017
Im unsure why I cannot see the values when echoing them!
Any assistance will be much appreciated.
Your variable when retrieving the post data is wrong
Select department html code:
<select name = departments value=''>Department Name</option>
In the select form, the name is "departments", but when you retrieve them in the PHP, it is:
$_POST['departmant_name']
Which is wrong input variable name. It should be:
$_POST['departments']
Also, please put quotes mark on the select name
<select name = 'departments' value=''>Department Name</option>
All other variable also wrong.
Looks like you entered the database column name, not the form input name.
Edit:
I also noticed that in your form, the form "method" is set to "GET" while your PHP code is using "POST"

Data not inserting into database

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!';
}

how to insert data from a select box using php

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

data from droplist to database mysql

I need advice, what i did wrong and this code not working. In short I have droplist menu with data read from mysql database and I want this data what user selected put in to another table/row in db. with present code I received only NULL value in inserted row... some I assume maybe something wrong with syntax, I tried search similar topic and tried different way but result is same :| This is my code :
get function and form
<br><br>
<?php
include 'connectdb.php';
$sql="select * from persons";
$result=mysqli_query($con,$sql);
while ($row=mysqli_fetch_array($result)) {
$id=$row["id"];
$name=$row["name"];
$name_done.="<OPTION VALUE=\"$id\">".$name;
}
?>
<form action="insert.php" method="post">
<SELECT name="name_done" id="nane_done">
<OPTION VALUE=0>Choose Your name :
<?=$name_done?>
</SELECT> <br>
RFC: <input type="text" name="number"><br>
Date: <input type="text" id="datepicker" name="date">
<input type="submit" value="submit" />
</form>
And Insert
<?php
include 'connectdb.php';
$name_done = $_POST['nane_done'];
mysqli_query($con,"INSERT INTO rfc(name_done) VALUES (.$name_done)");
---- below working OK----
$sql = "INSERT INTO rfc(number,date)
VALUES
('$_POST[number]','$_POST[date]')";
if (!mysqli_query($con,$sql,$name_done))
{
die('Error: ' . mysqli_error($con));
}
echo "RFC added";
mysqli_close($con);
?>
You have a typo - "nane_done" rather than "name_done" in this line: $name_done = $_POST['nane_done'];.

Undefined index in inserting records on DB

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

Categories