【问题标题】:PDO dont work when trying to execute INSERT command尝试执行 INSERT 命令时 PDO 不起作用
【发布时间】:2018-10-08 08:22:15
【问题描述】:

我正在尝试插入一个 sql 查询,但它不起作用 - 我没有错误,$pdo->errorInfo(); 只返回 Array 并且在 mysql 中没什么可看的! 我 100% 确定 $text、$file 和 $title 已设置(我已使用 echo 检查过) /strong>我该怎么办???

datenbank.php

<?php
$pdo = new PDO('mysql:host=localhost;dbname=db', 'user', 'password');
?>

dev.php

include("datenbank.php");
// Prepare an insert statement
$post = $pdo->prepare("INSERT INTO news (text, date, file, title) VALUES ($text, NOW(), $file, $title)");
$post->execute(); 
$help = $pdo->errorInfo();

【问题讨论】:

  • 您需要阅读一些 MySQL 语法基础知识。您在这里使用了几个不带引号的关键字作为列名,以及没有正确引用的可能是字符串值。 “$pdo->errorInfo();仅返回 Array” - 您是否尝试使用 echo 输出它?使用 var_dump 或 print_r。
  • @misorude 现在 errprInfo();返回'1':/我知道这个列名不是最好的,但这只是为了我,所以我不关心我只关心它的名字:3
  • php.net/manual/en/pdo.prepare.php 看看 PDO 的语法 在这里准备一些例子
  • “我知道这个列的名称不是最好的,但这只是为了我,所以我不关心名称” - 但数据库关心。所以请首先阅读dev.mysql.com/doc/refman/8.0/en/keywords.html

标签: php mysql pdo


【解决方案1】:

您没有在prepare PDO 语句中使用参数标记。当您使用 PDO 扩展准备查询时,您需要在查询语句中放置标记,并在 execute 函数中指示这些标记的值,就像关联数组一样。

您可以使用:marker 或问号? 之类的标记,您的查询将是这样的:

include("datenbank.php");
// Prepare an insert statement with marks params
$post = $pdo->prepare(INSERT INTO news (text, date, file, title) VALUES (:text, NOW(), :file, :title));
//execute statements with the marks values in prapare function params
$post->execute(array(':text' => $text, ':file' => $file, ':title' => $title)); 

编辑:PD:这可以防止 SQL 注入.......

【讨论】:

    【解决方案2】:

    字符串值需要引号

    $post = $pdo->prepare("INSERT INTO news (text, date, file, title) 
       VALUES ('$text', NOW(),'$file', '$title')");
    

    无论如何你不应该在 sql 中使用 php var,你有 sqlinjection 的风险。使用准备好的语句和绑定参数来代替

    $stmt = $conn->prepare("INSERT INTO news (text, date, file, title) 
             VALUES (:text, NOW(), :file, :title)");
    $stmt->bindParam(':text', $text);
    $stmt->bindParam(':file', $file);
    $stmt->bindParam(':title', $title);
    
     $stmt->execute();
    

    【讨论】:

      猜你喜欢
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-18
      • 2021-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多