0

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?

2
  • i dont see where the problem is .. just call the addUser function after you get ur values from the $_GET .. and dont forget to do some validation and filtration Commented Apr 27, 2014 at 8:26
  • fill up the "action" part of the form, submit, and then retrieve the values you passed in php using $_GET array... Commented Apr 27, 2014 at 8:26

4 Answers 4

1

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
}

?>
Sign up to request clarification or add additional context in comments.

Comments

0

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'].

Comments

0

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
 }

Comments

0

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.

https://www.php.net/manual/en/function.mysql-escape-string.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.