不能在mysql数据库中插入数据使用php
首先我对mysql和php很新,现在我只是想在mysql数据库中插入一些数据形式使用php的两个文本框。不能在mysql数据库中插入数据使用php
这里的数据库名称是“信息”和表名是“学生”有三列像id(主键,自动增量激活),名称和部门。有两个文本框txtName和txtDept。我希望当我按下输入按钮的数据形式的文本框将被插入到MySQL数据库。我曾尝试下面的代码,但数据未在表中插入....
<html>
<form mehtod="post" action="home.php">
<input type="text" name="txtName" />
<input type="text" name="txtDept" />
<input type="submit" value="Enter"/>
</form>
</html>
<?php
$con = mysqli_connect("localhost","root","","info");
if($_POST){
$name = $_POST['txtName'];
$dept = $_POST['txtDept'];
echo $name;
mysqli_query($con,"INSERT INTO students(name,dept) VALUES($name,$dept);");
}
?>
有几件事情错了你发布代码。
mehtod="post"
它应该是method="post"
- 拼写错误。
另外,引用你的价值观
VALUES('$name','$dept')
DO使用prepared statements,或者PDO with prepared statements。
,因为你现在的代码是开放的SQL injection
,并添加error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
您也应该检查数据库的错误。
$con = mysqli_connect("localhost","root","","info")
or die("Error " . mysqli_error($con));
以及or die(mysqli_error($con))
到mysqli_query()
旁注/建议:
如果整个代码是相同的文件内(这似乎是),考虑使用名为attribute的提交按钮o在条件语句内包装您的PHP/SQL此外,您可能会收到Undefined index...
警告。
命名您的提交按钮<input type="submit" name="submit" value="Enter"/>
,做
if(isset($_POST['submit'])){ code to execute }
只是做if($_POST){
时错误报告设置可能会出现意想不到的结果。
重写:一些使用mysqli_real_escape_string()
和stripslashes()
<html>
<form method="post" action="home.php">
<input type="text" name="txtName" />
<input type="text" name="txtDept" />
<input type="submit" name="submit" value="Enter"/>
</form>
</html>
<?php
$con = mysqli_connect("localhost","root","","info")
or die("Error " . mysqli_error($con));
if(isset($_POST['submit'])){
$name = stripslashes($_POST['txtName']);
$name = mysqli_real_escape_string($con,$_POST['txtName']);
$dept = stripslashes($_POST['txtDept']);
$dept = mysqli_real_escape_string($con,$_POST['txtDept']);
echo $name;
mysqli_query($con,"INSERT INTO `students` (`name`, `dept`) VALUES ('$name','$dept')")
or die(mysqli_error($con));
}
?>
按手动添加的安全性:http://php.net/manual/en/mysqli.connect-error.php,如果你想使用下面的方法,其中评论有被赋予这种效果:
<?php
$link = @mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');
if (!$link) {
die('Connect Error: ' . mysqli_connect_error());
}
?>
上帝保存我们所有的... 使用PDO类,而不是:)。通过使用PDO,您还可以在客户端准备语句并使用命名参数。如果你需要改变你的数据库驱动程序PDO支持的话,那么MySQLi只支持一个驱动程序(MySQL),这个驱动程序可以支持12个不同的驱动程序(十八个不同的数据库!)。 :( 在性能方面MySQLi的速度提高了大约2.5%,但这并没有太大差别,我的选择是PDO :)。
@VMai我不明白。编辑,好吧。 – 2014-09-20 15:06:57
@VMai好点。做了编辑,最后还是'VALUES ...',当我将它放到'mysqli_query'下时,看起来很奇怪。随意编辑:) – 2014-09-20 15:10:23
为了在这种情况下检查连接错误,你可以使用'mysqli_connect_error()',因为如果错误'$ con'将会是'FALSE'和'mysqli_error()'需要有效的链接标识符。 – Timur 2014-09-20 15:18:40