如何将文本输入传递给php函数?
I have the following code on a php page:
<form action="" method="get">
First Name:
<input type="text" name="first"/><br />
Last Name:
<input type="text" name="last"/>
<input type="submit" value="Add">
</form>
It is a form to add a new user to a sqlite database. In another file I have this php function:
function addUser($firstName, $lastName) {
$sql = "INSERT INTO USERS
(FIRST, LAST)
VALUES ('$firstName', '$lastName')";
return execSQL($sql);
}
So what I want to do is pass the text that a user enters in the text fields to the function (which has been placed in the global scope, but is in a different document). How can I do this?
You FORM method is get so use $_GET.As you mentioned in action your php code and form should be in same page.
<?php
$firstname=''; // Declare your variables first
$lastname=''; // Declare your variables first
if(isset($_GET['first']) && isset($_GET['last'])){ // Then validate it
$firstname = $_GET['first'];
$lastname = $_GET['last'];
addUser($firstName, $lastName); // Then use your function call
}
?>
You probably want to load a new page which calls this function using the variables from the form and then displays a confirmation message. You can get these variables with $_GET['variable name'].
Try this, You have used get
method in your form, so you need to use $_GET
.
if(isset($_GET['first']) && isset($_GET['last'])){
$firstName = $_GET['first'];
$lastName = $_GET['last'];
addUser($firstName, $lastName); // passing the value into function
}
Just set the form action to a page which includes:
addUser($_GET['first'], $_GET['last']);
However, this code is vulnerable to SQL injections and should never be used in production. Make sure you at least run it through mysql_escape_string, or preferably switch to PDO and use parameter binding.
http://us3.php.net/manual/en/function.mysql-escape-string.php