![](/img/trans.png)
[英]How do I use SESSION data to SELECT 1 database entry and then INSERT into another table with data from a form as well with PHP and MySQL?
[英]How do I insert data in a mySQL database from a form using PHP?
我需要将学生插入我的数据库。
学生表有3个字段。 id_Students
, Student_firstname
和Student_surname
我希望用户将数据插入表单,按下提交按钮然后将数据添加到数据库中,但我没有太多运气。
这是我到目前为止所做的:
表格:
<form method="POST">
First name: <input type="text" name="firstname"><br>
Surname: <input type="text" name="surname">
<input type="submit" name="action"></button>
</form>
添加学生的功能:
function addStudent()
{
$data = "INSERT INTO Students (Student_firstname, Student_surname)
VALUES('$_POST['firstname']', '$_POST['surname']')";
if(!$data)
{
die("Invalid Query: " . mysql_error());
}
}
if( isset($_POST['action']))
{
addStudent();
}
我的第一个想法是我不是要求用户输入学生ID号,但是这被设置为自动递增,这使我认为我可以添加其他2个字段并且id将自动填写。
此外,我没有收到我的错误消息,数据根本没有放入表中。
- 您需要执行查询。
- 您的查询不正确
试试这样:
function addStudent()
{
$data = "INSERT INTO Students (Student_firstname, Student_surname)
VALUES('".$_POST['firstname']."', '".$_POST['surname']."')";
$mysqli = new mysqli("host", "my_user", "my_password", "db_name");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if(!$mysqli->query($data))
{
die("Invalid Query: " . $mysqli->error());
}
}
您应该使用预准备语句,以便可以与恶意用户对抗SQL注入,并使用条件语句来评估我们的插入是否成功。
function addStudent(){
$mysqli = new mysqli('host', 'user', 'password', 'database');
$stmt = $mysqli->prepare('INSERT INTO Students (Student_firstname, Student_surname) VALUES(?, ?)');
$stmt->bind_param('ss', $_POST['firstname'], $_POST['surname']);
if($stmt->execute()):
echo 'We have successfully added this student.';
else:
exit('execute() failed: ' . $stmt->error);
endif;
$stmt->close();
}
你必须使用mysql_query
运行查询
$sql = "INSERT INTO Students (Student_firstname, Student_surname)
VALUES('$_POST['firstname']', '$_POST['surname']')";
$result=mysql_query($sql);
因为它被弃用,使用mysqli
比使用mysql
更好。 您可能还需要阅读一些有关SQL injection
下面的第一件事是不正确的
$ data =“INSERT INTO Students(Student_firstname,Student_surname)VALUES('$ _ POST ['firstname']','$ _POST ['surname']')”;
它应该是
$ data =“INSERT INTO Students(Student_firstname,Student_surname)VALUES('”。$ _ POST ['firstname']。“','”。$ _ POST ['surname']。“')”;
第二件事
你没有执行你需要使用的查询mysql_query()在这里学习http://in2.php.net/mysql_query
您尚未执行查询。 后
$data = "INSERT INTO Students (Student_firstname, Student_surname)
VALUES('$_POST['firstname']', '$_POST['surname']')";
你应该执行你的SQL查询,
$exec = mysql_query( $data, $con );
其中$data
是你的查询& $con
是建立mysql连接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.