我在执行插入多个记录时遇到错误

时间:2014-12-12 06:56:36

标签: php

<?php
session_start();
if(isset($_SESSION['id']))

$servername = "localhost";
$dbname = "school";


// Create connection
$conn = mysqli_connect($servername, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " .  mysqli_connect_error());
} 


$teacher_id=$_SESSION['id'];
$student_id=$_POST['student_id'];
$subject=$_POST['subject'];
$description=$_POST['description'];


$sql="INSERT INTO t_sent (teacher_id, student_id, subject, description)
VALUES
('$_SESSION[id]', '$_POST[student_id]', '$_POST[subject]', '$_POST[description]')";

$sql .="INSERT INTO p_inbox (teacher_id, student_id, subject, description)
VALUES
('$_SESSION[id]', '$_POST[student_id]', '$_POST[subject]', '$_POST[description]')";


if (mysqli_multi_query($conn, $sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>

我在添加记录时收到此错误信息

错误:

INSERT INTO t_sent (teacher_id, student_id, subject, description) VALUES ('Badri', 'ca11099', 'cm ', 'cm')INSERT INTO p_inbox (teacher_id, student_id, subject, description) VALUES ('Badri', 'ca11099', 'cm ', 'cm')
No database selected

我不知道我错过了什么

3 个答案:

答案 0 :(得分:1)

我认为你错过了mysqli_connet的语法

mysqli_connect(host, user,password, db);

如果它不适合你,请告诉我。

答案 1 :(得分:0)

首先,您似乎错误地使用了if语句 - 即

if(isset($_SESSION['id']))

if语句仅适用于下一行($servername = "localhost";)。你需要用{}来包装你想要该语句应用的代码(根据你的代码判断,之后是每一行)。

mysqli_connect()的参数错误 - 应该是

mysqli_connect($servername, $username, $password, $dbname);

您缺少应该在数据库名称之前的用户名和密码。

你也没有消毒或逃避你的输入,这非常糟糕,可能导致SQL injection attacks。你永远不会直接接受用户输入并对其进行查询。

答案 2 :(得分:0)

对所有参数使用正确的mysqli_connect():

 <?php
    $con = mysqli_connect($servername, $username,$password, $database_name);

    // Check connection
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }
    ?>

此外,您可以使用mysqli_select_db()函数

选择数据库