I have created a form, with 5 textbox fields and I want to add those five entries in the database. I want to use the textbox "array", that way I can use a for-each when saving to the database. As anyone, any code on how to do this or can direct me in the right path?
input type="text" value="whateva" name= ?php text[0] ?>
input type="text" value="whateva" name= ?php text[1] ?>
input type="text" value="whateva" name= ?php text[2] ?>
if (isset($_POST['Submit']) {
//add to db
(for-each $text as $val) {
//add to db
}
}
Is this possible?
HTML
<input type="text" value="whateva" name="text[]" />
<input type="text" value="whateva" name="text[]" />
<input type="text" value="whateva" name="text[]" />
PHP
if (!empty($_POST['text'])) {
foreach ($_POST['text'] AS $value) {
// add to the database
$sql = 'INSERT INTO tableName SET fieldName = "' . mysql_real_escape_string($value) . '"';
}
}
Yes, HTML supports arrays. just name your textareas like this:
<textarea name="field[]"></textarea> /* Notice square brackets */
For this example, in PHP, your $_GET or $_POST will have array key with name 'field' and values from these textareas.
If 'Submit' is the name of the submit button. yeah that will work.
but few suggestions:
correct it as:
< input type="text" value="whateva" name= "" />
Use validation for the text submitted by user
IMPORTANT: "GET A BOOK ON PHP" and learn it. Seriously, if you learn this way, you wont become a good programmer. You are learning it the hardway. Book is must for you.
Related
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>"
}
Form:
<form method="POST" action="edit_work.php">
<input type="hidden" name="wid[]" size="1" value="<?php echo "$wid1" ?>" >
<input type="text" name="course[]" size="15" value="<?php echo "$course1" ?>" >
PHP:
extract($_POST);
for($i=0;$i<$count;$i++) {
echo $wid[$i];
echo $course[$i];
}
gives the wid values OK but not the text entered for the course names.
I have been through all forums for 2 days now. Any help? Thanks.
If you want your PHP to retrieve your data from the form, can't you name your text input "course", then get it inside your PHP with $_POST['course'] ?
What is your $count ?
Using brackets with your name attribute inside your input tag may be dangerous.
If you're using a list of inputs maybe you can define a text format like name="course#" where # is your index and then access it form your $_POST variable using $_POST['course'.$index]
You don't need to extract($_POST) in that case.
I am trying to get information from an html form and pass it to my php file as an array
here is a snippet of the code for my html form:
<form action ="upload.php" method="post">
Name<input id= "n" type="text" name="info[name]" /><br />
Address: <input id="a" type = "text" name="info[address]" /><br />
City: <input id="c" type = "text" name="info[city]" /><br />
</form>
then in my php file I tried to print the content:
$information = $_POST['info'];
echo $information['name'];
but nothing gets printed to the page
I don't think you can do that (shove it all into a separate array (apart from $_POST)) directly with your HTML. You'll have to do some extra PHP work at the beginning.
Firstly, for the love of all that is holy, make your HTML input names cleaner:
<form action ="upload.php" method="post">
Name<input id= "n" type="text" name="info_name" /><br />
Address: <input id="a" type = "text" name="info_address" /><br />
City: <input id="c" type = "text" name="info_city" /><br />
</form>
And now, for the PHP:
//this is how I would do it, simply because I don't like a bunch of if/elseifs everywhere..
//define all the keys (html input names) into a single array:
$infoKeys[0]='name';
$infoKeys[1]='address';
$infoKeys[2]='city';
//define your end array
$information=array();
//now loop through them all and if they're set, assign them to an array. Simple:
foreach ( $infoKeys as $val ){
if(isset($_POST['info_'.$val])){
$information[$val]=$_POST['info_'.$val];
}//end of isset
else{
$information[$val]=null;
}//end of no set (isset===false)
}//end of foreach
//now, when you want to add more input names, just add them to $inputKeys.
//If you used the if/elseif ways, your doc would be plastered in ifs and elseifs.
//So i personally think the looping through the array thing is neater and better.
//but, feel free to change it, as I have a feeling I'll have allot of critics because of this method.
// anyway, that should do it. The var $information should be an array of all your 'info_' html inputs....
Happy coding!
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.
Let me explain.
Normally when hidden fields are passed from a form to the page specified in the action of the form, those hidden fields can be accessed on the processing page like so:
The Form:
<form action="process.php" method="POST">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="hidden" name="loginTime" value="1:23PM" />
<input type="hidden" name="userIp" value="173.23.22.5" />
<input type="submit" name="submit" value="Submit" />
</form>
Processing Page (process.php):
<?php
if isset($_POST['submit']) {
echo $_POST['username'];
echo $_POST['loginTime'];
echo $_POST['userIp'];
}
?>
You see how I had to call the two hidden fields by name and individually. Is there any way I can call all hidden fields that are passed to a page from a form all at once despite what the field names of those are or how many there are?
In other words how do I make PHP do this:
// echo the contents of all hidden
fields here (if there were any)
EDIT
Additional info:
The form is designed in such a way (not the one above of course) that field names will be of the following sort:
product_name_1
product_quantity_1
product_price_1
product_name_2
product_quantity_2
product_price_2
and so incremented so on...
Depending on the user action there can be 3 hidden fields or thousands, there are no limits.
Make an array of valid hidden field names, then iterate through $_POST and if the $_POST field name is in the array of valid field names, echo them.
$valid = array('first_name', 'last_name');
foreach ( $_POST as $key => $value ) {
if ( in_array( $key, $valid ) ) {
echo $_POST[$key];
}
}
PHP does not care whether the field was hidden or not, HTTP doesn't tell PHP how it appeared on the website.
The closest thing I would come up with was saving all names of the hidden fields inside an array and echoing them all in a loop.
You can try the following:
<form action="process.php" method="POST">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="hidden" name="group_hidden[loginTime]" value="1:23PM" />
<input type="hidden" name="group_hidden[userIp]" value="173.23.22.5" />
<input type="submit" name="submit" value="Submit" />
</form>
And then print it:
echo htmlspecialchars(print_r($_POST, true));
This might give you a clue about how to solve this.
there's no way to tell the type of the input built-in, so instead you'll need to come up with a way to identify the ones you want yourself. This can be done either by coming up with a special naming scheme, or by storing a list of the names of the hidden fields in another field. I'd recommend the former option, since you don't have the risk of losing data integrity somehow. Look at using array_filter to parse through the array to get the specially-named fields out.
Maybe, assuming that your hidden fields will be in sequence (i.e. 1,2,3 and not 1,2,4) following all of the end users' actions (adding and taking away fields), you could try something along the lines of
$i = 1;
while(isset($_POST["product_name_$i"]))
{
echo $_POST["product_name_$i"];
echo $_POST["product_price_$i"];
$i++;
}
Or something along those lines?