PHP get input , radio , selection data and insert into MySQL table - php

i'm new to php , i have been searching for a tutorial regarding inserting form's input(text) , radio and selection data to MySQL database's table using php. i found some tutorials but most are confusing. So i decided to ask.
Okay here's what i want to do. I have a form which have two types of input and a selection
1. input type text
2. input type radio
3. selection
Here's the HTML code :
<form action="" method="post" enctype="multipart/form-data">
<strong>Your Name: </strong><br>
<input type="text" name="myname" value="" />
<br /><br/>
<strong>Which class type you want:</strong><br>
<select name="selection">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<strong>Do you agree?</strong><br>
<input type="radio" name="agree" value="Yes"> or
<input type="radio" name="agree" value="No">
<input type="submit" name="submit" value="Submit">
</form>
I have set the form action to blank because the php code will be in the same file as the HTML (it's a php file btw)
MySQL table : info
structure :
1. name
2. class
3. agree
I want the php code to insert myname into name , selection's selected data into class , radio selected data into agree
P/S Yes i have added a connect to database php script , i just want to know how to get the form data into mysql.
Can someone write a php code example on how can i do this?
Thanks and have a nice day . I hope i have provided enough information. Thanks again if you help.

1. There is a problem with your radio element. The name should be the same for both options.
It should be like this:
<input type="radio" name="agree" value="Yes"> or
<input type="radio" name="agree" value="No">
2. You can access everything in the $_POST array, since you are using the method post for the form.
$name = $_POST['myname'];
$selection = $_POST['selection'];
$agree = $_POST['agree'];
3. If you are not using parametrized SQL with a library such as PDO, MySQLi, etc... you must always escape the data, which will be used in query using mysql_real_escape_string(), in order to protect against SQL injection.
This would be a sample code, to do the escaping and the query.
// write a function somewhere, to use as a shortcut
// for escaping data which will be used in a query
function sql_escape($str){
return "'".mysql_real_escape_string($str)."'";
}
// build the query
$query = sprintf('INSERT INTO table_name(name, class, agree) VALUES(%s, %s, %s)',
sql_escape($_POST['myname']),
sql_escape($_POST['selection']),
sql_escape($_POST['agree']));
// finally run it
$result = mysql_query($query);

I've taken it a little further here, there is still plenty more that can be done and many way's to do it, for instance you could extend the $errors array to include a field id and then highlight the HTML form field so the user can see exactly where they went wrong.
Considering your form is fairly simple you would not need this.
#Shef's code would certainly do the job but I thought you might be interested in some more.
<?php
// check the form has been submitted
if (isset($_POST['submit'])) {
// escape the form fields and assign them to variables
// validate myname to ensure the user entered data
if (isset($_POST['myname']) && $_POST['myname']!='') {
$myname = mysql_real_escape_string($_POST['myname']);
} else {
// create an error variable array to store errors to display
$errors[] = 'Please enter your name';
}
// no need to validate selection here as it alway's has a value
$classtype = mysql_real_escape_string($_POST['selection']);
// validate agree unless you want to add 'checked' to one of the values
if (isset($_POST['agree']) && $_POST['agree']!='') {
$agree = mysql_real_escape_string($_POST['agree']);
} else {
$errors[] = 'Please tell us if you agree?';
}
//if errors found tell the user else write and execute the query
if ($errors) {
$message = '<p class="error">We found a problem:</p><ul>';
foreach($error as $msg){
$message .= '<li>'.$msg.'</li>';
}
$message .= '</ul><p>Please fix the error/s to continue.</p>';
} else {
// write the query
$query = "INSERT INTO table (myname, classtype, agree) VALUES ";
$query .= "('$myname','$classtype','$agree')"
// run the query
mysql_query($query);
$message = '<p class="sucessful">Thanks '.htmlspecialchars($myname).'. Your selection has been saved.</p>';
}
}
// print the message
// show the variables in the form field so they don't need re-input
if ($message!='') { echo $message; }
?>
<form action="" method="post" enctype="multipart/form-data">
<strong>Your Name: </strong><br>
<input type="text" name="myname" value="<?php echo htmlspecialchars($myname) ?>" />
<br /><br/>
<strong>Which class type you want:</strong><br>
<select name="selection">
<option value="A"<?php if ($classtype=='A') { echo ' selected'; } ?>>A</option>
<option value="B"<?php if ($classtype=='B') { echo ' selected'; } ?>>B</option>
<option value="C"<?php if ($classtype=='C') { echo ' selected'; } ?>>C</option>
</select>
<strong>Do you agree?</strong><br>
<input type="radio" name="agree" value="Yes"<?php if ($agree=='Yes') { echo ' checked'; } ?>> or
<input type="radio" name="agree" value="No"<?php if ($agree=='No') { echo ' checked'; } ?>>
<input type="submit" name="submit" value="Submit">
</form>
Also: #sqwk, Don't point people towards w3schools, see this: http://w3fools.com/

Check whether there is any data in the $_POST array and get the values from it.
Have a look here—the second example down is what you need: http://www.w3schools.com/php/php_mysql_insert.asp
(You do have to make the changes that Shef suggested, though.)
Also remember to check your data-integrity, otherwise people could use your insert to run malicious code.

check this simple example:
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Sname: <input type="text" name="sname" />
<input type="submit" />
</form>
after you submit form, you can take name and sname.
welcome.php::
<?php
$name= $_POST["name"];
$sname= $_POST["sname"]; ?>
now you can use this variables as if you want.

Related

PHP code inside HTML value attribute

there!
I want to do a database search and display the result back to the user in a pre-populated HTML form.
I located the exact part in the code that is not working but I can't understand why PHP is not picked by the server. I'm using UwAMP.
To illustrate the problem here is my short snippet of code that I need help with:
<form id="st_reg" action="" method="POST">
Student Number:
<input type="number" name="s_num" min="1000000" max="3000000" > </br>
<input type="Submit" value="Search">
</form>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST"){
if(empty($_POST['s_num'])){
$errors[] = "You forgot to enter the Student No!";
}
else{
$st_no = trim($_POST['s_num']);
}
if(empty($errors)){
//Open database connection
require('../../connect_to_database/mysql_connect.php');
//Check if the student is already in the database
$query = "SELECT * FROM student WHERE student_no = $st_no";
//Run the query
$result = mysqli_query($db_connection,$query);
if(!$result){
echo "The student does not exist!";
echo"Please <a href='index.html'>go back</a> and choose another action!";
}
elseif($result){
echo "<h2>Student Details:</h2>";
while($row = mysqli_fetch_array($result)){
echo '<form id="st_reg" action="" method="POST">
<label>Student Number:</label>
<input type="number" name = "st_number" min="1000000" max="3000000" value="<?php if(isset(\$row[\'student_no\'])) echo \$row[\'student_no\']; ?> ">
AND the PHP code inside VALUE ATTRIBUTE is not executing when it should in reality. Don't bother about GLOBAL php tags not being closed 'cause they are in the file (I'm not that dump).
Please note all this code is inside a .php file with HTML code. This is a just the processing part after the form is submitted. I saved my time by using single-quotes for echo and escaped the sigle-quotes along the way where DB access was required. I tried curly brackets around variables, echo with double-quotes escaping double-qoutes within it but none of these attempts were successful. This is strange because I can perfectly echo $row['student_no'] outside of this context and is running fine.
I also looked at similar questions on this website. They were close but none of them had nearly to this context. I am open to any suggestions and better than that solutions.
echo '<form id="st_reg" action="" method="POST">
<label>Student Number:</label>
<input type="number" name = "st_number" min="1000000" max="3000000" value="<?php if(isset(\$row[\'student_no\'])) echo \$row[\'student_no\']; ?> ">
should look like this:
echo '<form id="st_reg" action="" method="POST">
<label>Student Number:</label>
<input type="number" name = "st_number" min="1000000" max="3000000" value="' . (isset($row['student_no']) ? $row['student_no'] : '') . '">
CONTINUATION OF STRING...
The following will do what you want.
value="<?= (isset($row["student_no"]) ? $row["student_no"] : "") ?>"
You don't need to worry about all of the escaping when you're inside the PHP chunk already.

Change certain text from User input (From a User Input field)

I want to have a simple HTML input field where people can type all kinds of nonsense. For example, a user types: "Hello, I'm Nicky". When the user then clicks the button Send, I want a simple PHP script to replace the word "Nicky" to "Nicki" and show it to the user. So basially, just a simple PHP script which replaces specific words from an input field and then print out the exact same line the user has inputted, except show Nicki instead of Nicky.
How can I achieve this, in the most simplest way?
My code looks like this now:
<?php
$_POST['name'] = str_replace("Nicky","Nicki",$_POST['name']);
?>
<form method="post">
<input type="text" name="name">
<input type="submit">
</form>
<?php
if(isset($_POST['form-action']) && $_POST['form-action'] == "submit-form"){ // form has been submitted
echo "<p>BEFORE: ".$_POST['name']."</p>"; // what the user entered "Nicky"
$_POST['name'] = str_replace("Nicky","Nicki",$_POST['name']); // find/replace Nicky with Nicki
echo "<p>AFTER: ".$_POST['name']."</p>"; // what the $_POST['name'] now is
}
?>
<form method="post">
<input type="text" name="name" value="Nicky">
<input type="submit">
<input type="hidden" name="form-action" value="submit-form">
</form>
In addition to this, if you want to expand the Find & Replace variables, you could use an array:
$FindReplace = array("Nicky"=>"Nicki", "Blue"=>"Red"); // build an array of find/replace variables
....
foreach($_POST as $Name=>$Value){
echo "<p>Before: ".$Name."=".$Value."</p>"
foreach($FindReplace as $Find=>$Replace){
$Value = str_replace($Find,$Replace,$Value);
}
echo "<p>After: ".$Name."=".$Value."</p>"
}

Popup on if statement in php

I have a html form which looks like this:
<form action="submitOrder.php" method="get">
<select name="orderForm">
<?php
echo '<option value=" "> </option>';
while($row = \mssql_fetch_array($employeeOrderResult))
{
echo '<option value="'.$row[EMPLOYEE].'">'.$row[EMPLOYEE].'</option>';
}
?>
<option value="Gæst">Gæst</option>
<option value="Praktikant-01">Praktikant-01</option>
<option value="Praktikant-02">Praktikant-02</option>
<option value="Praktikant-03">Praktikant-03</option>
</select>
<br>
Vare: <input type ="text" name="varenr"><br>
Antal: <input type="text" name="antal"><br>
<input type="submit" value="Bestil">
</form>
It fetches som data from a database and adds some special guests.
Now, when it confirms it redirects to a page which has this code in it:
<?php
$ofAntal = $_GET['antal'];
$ofMedarbejder = $_GET['orderForm'];
$ofDato = date('Y-m-d H:i:s');
$ofVareNr = $_GET['varenr'];
$sql = "INSERT INTO Bestillinger(bestillingsAntal,medarbejder,dato,vareNr) VALUES('$ofAntal','$ofMedarbejder','$ofDato','$ofVareNr')";
$validation = mysql_query($sql, $MySQLcon);
if(!$validation)
{
die('Couldnt enter data ' . mysql_error());
}
echo 'Entered data succesfully';
?>
Now, I need a confirmation popup of some kind, if the amount (ofAntal) is above 1, and Ive looked into several solutions. The problem is i started working with PHP tuesday morning, and i cant find a solution that works for me.
All it has to do, is submit the data is yes is clicked, and cancel it if the user clicks no/cancel. This is ofc done in an IF statement, thats not the issue, the issue is how to implement it properly.
ANY help is highly appreciated :)
Use javascript confirm box on onclick attribute for submit button. It will give you yes and cancel options.
<input type="submit" value="Bestil" onclick="confirm("Are you sure ?");">
Orelse
You can write a function in javascript to check that
<input type="submit" value="Bestil" onclick="myfunct();">
function myfunct(){
if(document.getElementById("antal").value > 1)
confirm("Are you sure");
return true;
}

get selected value of a drop down which is populated with results from an SQL query

So I have a drop down populated with the names based on an SQL query. I want to be able to see which option the user selected before they pressed submit and use this as a variable on a separate php file. I assume I will need to use session variables? I'm a bit lost so any help would be appreciated. I have the following code so far:
<form name="ClientNameForm" id="ClientNameForm" action="ClientDetails.php">
<input type="text" name="ClientName" id="ClientName" placeholder="Type Service User's name here:" style="width: 200px"/><br/><br/>
<select name="Name_dropdown" id="name_dropdown" style="width: 200px" >
<?php
$ClientName_Query= "SELECT CONCAT(FName, ' ', SName) AS FullName FROM ClientDetails";
$ClientName_Result= mysql_query($ClientName_Query) or die (mysql_error());
while ($row= mysql_fetch_array($ClientName_Result)){
echo "<option> $row[FullName] </option>";
}
?>
</select><br/><br/>
<input type="submit" name="submit_btn" id="submit_btn" value="Submit"/>
</form>
In your ClientDetails.php file the value will be available using,
$name = $_POST['Name_dropdown'];
If you need to change a setting in the form document before submitting you can use jQuery. Something like
$('#name_dropdown').change(function(){
var option = $(this.options[this.selectedIndex]).val();
});

Two forms with multiple submit buttons in single PHP file

I am trying to write a dynamic form using PHP. I'd like to have a single webpage that contains two forms:
The upper form allows to search for an element in the mysql database, e.g., for a name
The lower form shows the data that is associated with this name in the database
If I press on the "Search" button of the upper form, then the the lower form is shown and the text fields are filled with data from the database that belong to this name. If I change the user name to some other value and press again "Search", then the data that is associated with the new record is shown and so on.
The lower form also has a button "Update" which allows to transfer changes made to the text boxes (in the lower part) to the database.
Now, I have the following problem: In my script I set initially the value of name (from the upper form) to "". When I then press the "Search" button, then the lower part of the form is shown and the corresponding data is shown in the lower part. When I then press the "Update" button, then the text field associated with name is set to the empty string. This is because in my script I set initially name to the "". I'd like that in this case the data entered in the upper form is not changed, i.e., it stays the same.
I guess, I am missing something here. There is probably an easy solution for this and I am doing something fundamentally wrong. It'd be great if you could help me.
That's what I tried... I deleted lots of details, but I guess that can give you an idea what I am trying to do. Notice that the whole code is in the file update.php.
<?php
function search_bus($mysql, $name)
{
// do some stuff here...
}
function update_bus($mysql, $b_id)
{
// do some stuff here...
}
// some global variables
$b_id = 0;
$username = ""; // username of business
// get b_id that corresponds to username
if (isset($_REQUEST['search']))
{
$b_id =0; // business id
if (isset($_POST['user']))
{
$username = $_POST['user'];
$b_id = search_bus($mysql, $username);
}
}
elseif(isset($_REQUEST['update']))
{
update_bus($mysql, $b_id);
}
?>
<h2>Search:</h2>
<form name="search_bus" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Username: <input type="text" name="user" value="<?= htmlentities($username) ?>"/>
<input type="submit" value="Suchen" name="search"/>
</form>
<?php
if($b_id != 0)
{
?>
<h2>Data:</h2>
<form name="business_design" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<-- some form follows here -->
<?php
}
?>
I think what you're missing is to create a HTML Hidden field to keep the value of Name variable.
<input type="hidden" name="name" value="<?php print $nameVar ?>" />
Add this input to both forms so you can keep the value no matter what button the user clicks.
Hope this helps.
Adding code to verify the
<h2>Search:</h2>
<form name="search_bus" method="post"
action="<?php echo $_SERVER['PHP_SELF'];?>">
Username: <input type="text" name="user" value="<?= htmlentities($username) ?>"/>
<input type="hidden" name="b_id" value="<?php print $b_id?>" />
<input type="submit" value="Suchen" name="search"/>
</form>
<?php if($b_id != 0) { ?>
<h2>Data:</h2>
<form name="business_design" method="post" action="<?php echo $_SERVER['PHP_SELF'];>">
<input type="hidden" name="b_id" value="<?php print $b_id?>" />
<-- some form follows here -->
<?php } ?>
Dont initialize $b_id if it already comes into the http request.
if (!isset($_POST['b_id']))
{
$b_id = 0;
}
else
{
$b_id = $_POST['b_id'];
}
This way you can alway remember the last selected value of b_id.
Hope this can help you.

Categories