Reputation: 861
I need to assign text of textarea tag to php variable. I try do it like this:
<form method="GET">
<textarea rows="4" cols="50" name="query">some string</textarea>
</form>
<?php
$query = $_REQUEST['query'];
echo $query;
?>
But I'm getting
Notice: Undefined index: query in index.php on line _
What do I do wrong? Thanks.
Upvotes: 1
Views: 9542
Reputation: 74217
Since you're using the entire code inside the same page, it's normal for it to throw you that warning on page load.
Use empty()
with a conditional statement for that form element.
if(!empty($_REQUEST['query'])){
$query = $_REQUEST['query'];
}
Plus, in conjunction with empty()
, use isset()
with a named submit button, as I've outlined below.
if(isset($_REQUEST['submit']) && !empty($_REQUEST['query']) ){
Plus, you will need to add some type of button to submit the data.
Either a <button type="submit" name="submit">Submit</button>
or an input type <input type="submit" value="Submit" name="submit">
Such as your <form method="GET">
Otherwise, split your form and PHP apart, and use <form method="GET" action="handler.php">
having the HTML form as one file, and the PHP in the other.
It would still be best to use empty()
and isset()
for either case.
Upvotes: 4
Reputation: 3850
You need to use this:
// add a submit button first...
<input type="submit" name="submit">
<?php
if(isset($_GET['submit'])){
// means submit clicked!
$query = $_GET['query'];
echo $query;
print_r($_GET) // check the values of $_GET array..
}
?>
Upvotes: 1
Reputation: 13728
try to add a submit button to form and default form method will be get so no need to add method get
<form>
<textarea rows="4" cols="50" name="query">some string</textarea>
<input type="submit" name="submit">
</form>
and for check
<?php
if(isset($_GET['query'])) {
$query = $_GET['query'];
echo $query;
}?>
Upvotes: 1
Reputation: 23958
You need to post the form.
You are not posting it. This is the reason.
Add a new element submit
<input type="submit" name="submit" value="Submit"/>
Upvotes: 1