未知列 $name php 和 sql

Unknown column $name php and sql

我正在处理一个需要将数据插入数据库的项目,但我不断收到此错误:致命错误:未捕获的 PDOException:SQLSTATE[42S22]:未找到列:1054 未知列“$name”在 'field list' 中 /opt/lampp/htdocs/ramen.php:27 堆栈跟踪:#0 /opt/lampp/htdocs/ramen.php(27): PDOStatement->execute(Array) #1 { main} 在第 27 行 /opt/lampp/htdocs/ramen.php 中抛出

这是第 27 行:

$stmt-> execute(array(':content' => $_POST['content']));

这是那段代码:


if(isset($_POST['content'])){
    $name = $_SESSION['name'];
    echo $name;
    $sql = 'INSERT INTO notes_ (Text, User) VALUES (:content, $name);';
    $stmt = $pdo->prepare($sql);
    $stmt->execute(array(':content' => $_POST['content']));
}

将您的引号从单引号更改为双引号。您可以将变量注入双引号字符串。

if(isset($_POST['content'])){
    $name = $_SESSION['name'];
    echo $name;
    $sql = "INSERT INTO notes_ (Text, User) VALUES (:content, $name);";
    $stmt = $pdo->prepare($sql);
    $stmt->execute(array(':content' => $_POST['content']));
}

不过如果

会更好
if(isset($_POST['content'])){
    $name = $_SESSION['name'];
    echo $name;
    $sql = 'INSERT INTO notes_ (Text, User) VALUES (:content, :name);';
    $stmt = $pdo->prepare($sql);
    $stmt->execute(array(':content' => $_POST['content'], ':name' => $name));
}