开发者

Forms, Mysql and values

So say I have a form like so:

            <form action="submit2.php">
                <input name="name" type="text" />
                <input name="age" type="text" />
                <input typ开发者_JAVA百科e="submit" />
            </form>

I using this code to insert the values of the form into a database table called "example" after the user clicks the submit button.

mysql_query("INSERT INTO example (name, age) VALUES('$name', '$age' ) ") or die(mysql_error());  

However, all I get is a blank entry in the table. Am I wrong in assuming that an input's value becomes a variable if if is giving a name(e.g. name="age") in the html code?


Access the variables through the $_POST global variable.

if(isset($_POST['name']) && isset($_POST['age'])){
 $name = mysql_real_escape_string($_POST['name']);
 $age = mysql_real_escape_string($_POST['age']);
 mysql_query("INSERT INTO example (name, age) VALUES('$name', '$age' ) ") or die(mysql_error());
}


An input named "name" will create a variable $name in submit2.php only if register_globals is enabled, which is a security issue. You should never have register_globals turned on (it will be removed in PHP6, by the way).

I'm not sure what the default method attribute is, but it should create a variable named either $_GET['name'] or $_POST['name']. If it doesn't create any of them, add a method attribute to your form :

<form action="submit2.php" method="post">

However, this does not assure you that those variables exist (what if someone access submit2.php without using your form?). You have to use either isset or !empty (I prefer the latter, because it also checks if it's not empty).

Last thing : don't forget to escape your variables. Never trust user input. In this case, since you're inserting a variable in a query, you should use mysql_real_escape_string function.


you need to change the data from the form to usable values

        <form action="submit2.php" method="post">
            <input name="name" type="text" />
            <input name="age" type="text" />
            <input type="submit" />
        </form>

and change database query portion to:

        $name=mysql_real_escape_string($_POST['name']);
        $age=mysql_real_escape_string($_POST['age']);
        mysql_query("INSERT INTO example (name, age) VALUES('$name', '$age' ) ") or die(mysql_error());  

The mysql_real_escape_string helps security for not having script injected into your database and having someone change or remove entries.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜