php PHP表单未插入到mySQL数据库中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22138746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP form not inserting into mySQL database
提问by privatestaticint
I am trying to pull two text fields from a form down into a basic mySQL DB and it is giving me trouble. So here are my two files, HTML form first:
我正在尝试将表单中的两个文本字段下拉到基本的 mySQL DB 中,这给我带来了麻烦。所以这是我的两个文件,首先是 HTML 表单:
<!DOCTYPE html>
<html>
<body>
<title>Home Page</title>
<h3>Please Place your Order Below:</h3>
<form action="tacoOrder.php" method="POST" />
<p>Name: <input type="text" name="name" /></p>
<p>Taco Order: <input type="text" name="tacoOrder" /></p>
<input type="submit" value="Submit" />
</form>
</body>
</html>
and PHP:
和 PHP:
<?php
define('DB_NAME', 'tacoPractice');
define('DB_USER', 'root');
define('DB_PASS', 'root');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
if(!$link)
{
die('Could not connect to database: ' . mysql_error());
}
$db_select = mysql_select_db(DB_NAME);
if(!$db_select)
{
die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
}
echo "HOLY EFF";
$name = $_POST('name');
$tacoOrder = $_POST('tacoOrder');
$query = "INSERT INTO orders ('name', 'tacoOrder') VALUES ('{$name}', '{$tacoOrder}')";
if(!mysql_query($query)
{
die("DAMMIT");
}
$mysql_close();
?>
It doesn't give a connection error, but no data is inserted into my DB. Any ideas?
它没有给出连接错误,但没有数据插入到我的数据库中。有任何想法吗?
Thanks.
谢谢。
回答by Funk Forty Niner
Others have already given you answers. To add, you are using quotes around column names which should be backticks or remove the quotes altogether.
其他人已经给了你答案。要添加,您在列名周围使用引号,应该是反引号或完全删除引号。
Change:
改变:
INSERT INTO orders ('name', 'tacoOrder')
^ ^ ^ ^
to
到
INSERT INTO orders (`name`, `tacoOrder`)
or
或者
INSERT INTO orders (name, tacoOrder)
or as a complete answer:
或者作为一个完整的答案:
$name = $_POST['name'];
$tacoOrder = $_POST['tacoOrder'];
$query = "INSERT INTO orders (`name`, `tacoOrder`) VALUES ('$name', '$tacoOrder')";
Sidenote: Backticks are not required but the single quotes for the column names cannot be used. It's just a force of habit that I myself use backticks around column names.
旁注:不需要反引号,但不能使用列名的单引号。我自己在列名周围使用反引号只是一种习惯。
Plus, this $mysql_close();should not have a $in front of mysql_closebut $linkinside the brackets:
另外,这$mysql_close();不应该在括号$前mysql_close而是$link在括号内:
Change to mysql_close($link);
改成 mysql_close($link);
Yet as noted by Mr. Alien, the variable for mysql_close()is optional (Thanks for that)
然而正如 Alien 先生所指出的,变量 formysql_close()是可选的(谢谢)
You also have a missing )in if(!mysql_query($query)which should read as if(!mysql_query($query))
你也有失踪)的if(!mysql_query($query),应读作if(!mysql_query($query))
Do consider switching to mysqli_*functions with prepared statements or PDO. The mysql_*functions are deprecated and will be deleted from future releases.
请考虑切换到mysqli_*带有准备好的语句或 PDO 的函数。这些mysql_*功能已弃用,并将从未来版本中删除。
complete rewrite: (testedand working on my server)
完全重写:(在我的服务器上测试和工作)
<?php
define('DB_NAME', 'tacoPractice');
define('DB_USER', 'root');
define('DB_PASS', 'root');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
if(!$link)
{
die('Could not connect to database: ' . mysql_error());
}
$db_select = mysql_select_db(DB_NAME);
if(!$db_select)
{
die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
}
echo "HOLY EFF";
$name = $_POST['name'];
$tacoOrder = $_POST['tacoOrder'];
$query = "INSERT INTO orders (name, tacoOrder) VALUES ('$name', '$tacoOrder')";
if(!mysql_query($query))
{
die("DAMMIT");
}
else{ echo "Success"; }
mysql_close();
?>
You could also use this method which is slightly different:
你也可以使用这个略有不同的方法:
$query = mysql_query("INSERT INTO orders (name, tacoOrder) VALUES ('$name', '$tacoOrder')");
if (!$query) {
die('Invalid query: ' . mysql_error());
}
else{ echo "Success"; }
Footnotes:
脚注:
You risk in getting empty data entries because you are not checking if your form elements are left empty.
由于您没有检查表单元素是否为空,因此您可能会获得空数据条目。
You could use a conditional statement to the effect of:
您可以使用条件语句来达到以下效果:
if(!empty($_POST['name']) || !empty($_POST['tacoOrder']))
{
// continue with code processing
}
Plus, use what Awlad mentions in his answerin regards to using mysql_real_escape_string()
另外,使用 Awlad 提到his answer的关于使用的内容mysql_real_escape_string()
You can also read a good article here on SO How can I prevent SQL injection in PHP?
你也可以在这里阅读一篇关于 SO 的好文章 How can I prevent SQL injection in PHP?
Here is a (basic) mysqli_*based method with the mysqli_real_escape_string()function and a conditional statement to check if any of the fields are empty.
这是一个mysqli_*基于(基本)的方法,带有mysqli_real_escape_string()函数和条件语句,用于检查是否有任何字段为空。
If one of the fields is left empty, the query won't execute.
如果其中一个字段为空,则不会执行查询。
<?php
define('DB_NAME', 'tacoPractice');
define('DB_USER', 'root');
define('DB_PASS', 'root');
define('DB_HOST', 'localhost');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASS);
if(!$link)
{
die('Could not connect to database: ' . mysqli_error());
}
$db_select = mysqli_select_db($link,DB_NAME);
if(!$db_select)
{
die('Can\'t use ' . DB_NAME . ': ' . mysqli_error());
}
echo "HOLY EFF";
$name = mysqli_real_escape_string($link,$_POST['name']);
$tacoOrder = mysqli_real_escape_string($link,$_POST['tacoOrder']);
if(!empty($_POST['name']) || !empty($_POST['tacoOrder'])){
$query = "INSERT INTO orders (name, tacoOrder) VALUES ('$name', '$tacoOrder')";
if(!mysqli_query($link,$query))
{
die("DAMMIT");
}
else{ echo "Success"; }
mysqli_close($link);
}
?>
回答by Marc B
Basic PHP: $_POST is an ARRAY. It's not a function:
基本 PHP: $_POST 是一个ARRAY。这不是一个函数:
$name = $_POST('name');
^------^--- should be []
回答by user3064914
No need of '{}' and $_POST('name')
不需要 '{}' 和 $_POST('name')
$name = $_POST['name'];
$tacoOrder = $_POST['tacoOrder'];
$query = "INSERT INTO orders ('name', 'tacoOrder') VALUES ('$name','$tacoOrder')";
回答by vinay k hegde
hi @user2839411 even I faced the same problem,where values was not geting inserted into the mysql database,so tried seaching in many related websites but finally w3schools helped me out to achive the result. here is the bellow code thta inserts the value into the database.
嗨@user2839411 即使我遇到了同样的问题,值没有被插入到 mysql 数据库中,所以尝试在许多相关网站上进行搜索,但最后 w3schools 帮助我获得了结果。这是将值插入数据库的波纹管代码。
PHP CODE:
代码:
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "dbitb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['btn-signup']))
{
$name = ($_POST['name']);
$address = ($_POST['address']);
$email = ($_POST['email']);
$mobile = ($_POST['mobile']);
$highest_degree = ($_POST['highest_degree']);
$relavant_exp = ($_POST['relavant_exp']);
$sql = "INSERT INTO dbitb.volunteer_reg (name,address,email,mobile,highest_degree,relavant_exp)
VALUES ('$name','$address','$email','$mobile','$highest_degree','$relavant_exp')";
if ($conn->query($sql) === TRUE)
{
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
HTML CODE:
HTML代码:
<form method="post" action ="register.php" id="contact-form">
<input type="text" name="name" placeholder="name" required />
<textarea id = "address" name="address" placeholder="address" required /></textarea>
<input type="email" name="email" placeholder="email" required />
<input type="mobile" name="mobile" placeholder="mobile" required />
<input type="highest_degree" name="highest_degree" placeholder="highest degree" required />
<textarea id = "relavant_exp" name="relavant_exp" placeholder="relavant experience" required /></textarea>
<div class="btn-group" role="group">
<input type="submit" class="btn btn-default" name="btn-signup" value="Enter the box" style="margin-top: 15px; margin-right: 15px; border-radius: 4px;">
<a href="index.html"><button type="button" class="btn btn-default" style="margin-top: 15px;">« Back</button></a>
</div>
</form>
回答by Josiah Ufono
I had the same challenge. This was how i solved it after 12 frustrating hours.
我遇到了同样的挑战。这就是我在令人沮丧的 12 个小时后解决它的方法。
<?php
if(isset($_POST['button'])){
// echo "hi";
$username = $_POST['username'];
$password = $_POST['password'];
//TO ALERT SUBMISSION OF BLANK FIELDS(IT DOESN'T PREVENT SUBMISSION OF BLANK FIELD THOUGH)
if (!$username && !$password){
echo "can't submit blank fields";
}
//TO CONFIRM YOU ARE CONNECTED TO YOUR DATABASE (OPTIONAL)
$connection = mysqli_connect('localhost', 'root', '', 'berrybells');
if ($connection){
echo "we are connected";}
else{
die("connection failed");
}
//TO INSERT username and password from field to jossyusers database
$query = "INSERT INTO jossyusers(username,password) VALUES('$username','$password')";
$result = mysqli_query($connection, $query);
if(!$result){
die("OOPPS! query failed".mysqli_error($connection));
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body>
<form action="login_create.php" method="post">
<div class="myclass">
<h1>Username</h1>
<input placeholder="Name" name="username" type="text">
<input placeholder="Password" name="password" type="password">
<input type="submit" name="button" value="submit">
<?php
?>
</div>
</form>
</body>
</html>
回答by any
Check that the fields are the same in your database and in your insert INTO:
检查您的数据库和插入 INTO 中的字段是否相同:
ejm: BD: fiel1 varchar...
ejm: BD: fiel1 varchar ...
INSERT INTO(fiel1)
插入(字段 1)
回答by Awlad Liton
all $_POST('var_name')should be $_POST['var_name'];
一切都$_POST('var_name')应该是$_POST['var_name'];
replace
代替
$name = $_POST('name');
$tacoOrder = $_POST('tacoOrder');
by :
经过 :
$name =mysql_real_escape_string($_POST['name']);
$tacoOrder = mysql_real_escape_string($_POST['tacoOrder']);

