php insert into not adding data to database, any ideas?
I'm new to php and am making a simple login system. When someone wants to register, they go to register.html, then insert.php. The code below should add the data from the form to the table but is doesn't come up in it. I suspect it is probably the line: $sql=INSERT INTO... The only thing appearing is the echo statement at the bottom of the code I know there probably is a simple answer to this, but I still can't find it. Thanks, any help is really appreciated!
The code for insert.php
<?php
$email=$_POST['email'];
$name=$_POST['name'];
$password=$_POST['password'];
$con = mysql_connect("localhost","user","p@ssword");
mysql_select_db("database", $con);
$sql="INSERT INTO table_name (email, name, password)
VALUES ('$email', '$name',开发者_如何转开发 '$password')";
echo"Thank you, you are now registered and can login on our homepage";
mysql_close($con);
?>
Thanks again!
You established the connection and prepared the query, but you didn't actually execute it! You need to call mysql_query(), passing in the SQL and the connection handle, to instruct the database to perform the statement.
<?php
$email=$_POST['email'];
$name=$_POST['name'];
$password=$_POST['password'];
$con = mysql_connect("localhost","user","p@ssword");
mysql_select_db("database", $con);
$sql="INSERT INTO table_name (email, name, password)
VALUES ('$email', '$name', '$password')";
mysql_query( $sql, $con ) or trigger_error( mysql_error( $con ), E_USER_ERROR );
echo"Thank you, you are now registered and can login on our homepage";
mysql_close($con);
?>
Since you say you're new to PHP (and probably database development in general?), let me also point you in the direction of the PHP tutorial on SQL injection, which explains what it is and why you need to guard against it - your example code, for instance, is vulnerable.
The reason that this code doesn't work is that you haven't got the call to mysql_query
that actually makes the query:
mysql_query($sql);
However a bigger problem is that your application is currently highly insecure, because you are not checking the validity of $email
, $name
or $password
, so a malicious user could easily do nasty stuff to your database. At the least, use mysql_real_escape_string
to escape them; preferably, use a library such as PDO to help ensure the security of your site.
精彩评论