MySQLi GET,FROM和WHERE

时间:2016-09-20 16:48:37

标签: php mysqli

我想GET user id FROM players WHERE username='$username'并将其发布到另一个MySQLi查询中并将其发布为pid,但它以某种方式显示错误,我是否遗漏了某些内容?

if(isset($_POST["add"])) {
  $content = $_POST['content'];
  $sql = "SELECT id FROM players WHERE username='$username'";
  $sql1 = "INSERT INTO bulletinboard (pid,content) VALUES ('$sql','$content')"; 

    if (mysqli_query($conn, $sql1)) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . mysqli_error($conn);
    }  
}

这是我收到的错误。

Error: SELECT id FROM players WHERE username='nasty93'

由于

1 个答案:

答案 0 :(得分:2)

您需要执行查询,以便不需要引用它。您还应该熟悉insert...select语法。 http://dev.mysql.com/doc/refman/5.7/en/insert-select.html

您还应该使用参数化查询。在这里它被改变(未经测试)(我也只在SO上使用mysqli,因此这里可能是一个错误。)

if(isset($_POST["add"])) {
     $content = $_POST['content'];
     $sql1 = "INSERT INTO bulletinboard (pid,content) SELECT id, ? FROM players WHERE username=?"; 
     $stmt = mysqli_prepare($conn, $sql1) or die(mysqli_error($conn));
     mysqli_stmt_bind_param($stmt, "ss", $content, $username) or die(mysqli_error($conn));
     mysqli_stmt_execute($stmt) or die(mysqli_error($conn));
}