尝试使用PHP将数据从表单发送到MySql时出错

尝试使用PHP将数据从表单发送到MySql时出错

问题描述:

I have some problems while trying to send data from form to mysql database using php.I know how to fix this when i set form action to anothen page (<form action="example.php>, but i want that all procces stay on one page. WHen i run my php script and enter name in both of fields and go send, only url page changes, nothing else.Hope u can help me.Thanks

<?php
$con=mysqli_connect("localhost","root","","test");
if (mysqli_connect_errno())
{
echo"Error connecting to database". mysqli_connect_error();
}
if (isset($_POST['input_send']))
{
$name=($_POST['input_name']);
$lastname=($_POST['input_lastname']);
$insert="INSERT INTO test_mysql (name, lastname) VALUES ('$name', $lastname)";
echo"record added";
}
?>
<form action="" action="post">
First name: <input type="text" name="input_name"/>
Last name: <input type="text" name="input_lastname"/>
<input type="submit" value="send" name="input_send"/>
</form>

change this

  $insert="INSERT INTO test_mysql (name, lastname) VALUES ('$name', $lastname)";

to

 mysqli_query("INSERT INTO test_mysql (name, lastname) VALUES ('$name', '$lastname')");

and this

action="post"

to

method="post"

and escape your variables like that:

$name=mysqli_real_escape_string($_POST['input_name']);
$lastname=mysqli_real_escape_string($_POST['input_lastname']);

<form action="<?=echo $_SERVER['PHP_SELF']?>" method='post'> 

You can take info about the page url from your server.

It basicly action to the same page, i mean itself.

Your error is that you typed

action="post"

instead of

method="post"

Without a method specified, PHP will fall back to GET. Hence your isset($_POST) will return false and you are not seeing 'record added'

Another error, as pointed out by echo_ME is that you are not submitting the MySQL Query to the Database:

$insert="INSERT INTO test_mysql (name, lastname) VALUES ('$name', $lastname)";

With the function mysqli_query you can perform your query:

mysqli_query($insert);

As noted by others you should escape your variables to prevent SQL Injections