dphnn333971 2015-12-07 02:30
浏览 48
已采纳

PDO插入数据库不工作[重复]

This question already has an answer here:

When I type in the information that will be inserted into the database I receive this error:

Fatal error: Call to a member function execute() on a non-object.

The problem occurs on line 14 This is my code so far.

$database_file = 'sqlite:inventory.sqlite';
$mysql = new PDO($database_file);

$new_name = $_POST['Name_Item'];
$new_amount = $_POST['Amount_Item'];
$new_detail = $_POST['Description'];


$query =$mysql->prepare("INSERT INTO Items (id, Name, Amount, Detail)
VALUES (''," . $new_name . "," . $new_amount . ",". $new_detail .")");
$query->execute();
echo "testing";
echo "<TABLE>";
echo "<tr>";
echo "<td>id</td>";
echo "<td>Name</td>";
echo "<td>Amount</td>";
echo "<td>Detail</td>";
echo"</tr>";
while ($row = $query->fetch()) {
    //print_r($row);
    echo "<tr>";
    echo "<td>$row[id]</td>";
    echo "<td>$row[Name]</td>";
}
</div>
  • 写回答

1条回答 默认 最新

  • douzhan1238 2015-12-07 02:43
    关注

    The issue is probably that you need quotes around the name and detail values.

    This is one way you could solve the problem:

    $query =$mysql->prepare("INSERT INTO Items (Name, Amount, Detail)
      VALUES (:name, :amount, :detail)");
    $query->execute(['name' => $new_name, 'amount' => $new_amount, 'detail' => $new_detail]);
    

    You could also encapsulate name and detail in quotes, but that is not a good approach because if they have quotes in them it breaks.

    Also, in most cases, id is assigned by the database.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 电脑拓展屏桌面被莫名遮挡
  • ¥20 ensp,用局域网解决
  • ¥15 Python语言实验
  • ¥15 我每周要在投影仪优酷上自动连续播放112场电影,我每一周遥控操作一次投影仪,并使得电影永远不重复播放,请问怎样操作好呢?有那么多电影看吗?
  • ¥20 电脑重启停留在grub界面,引导出错需修复
  • ¥15 matlab透明图叠加
  • ¥50 基于stm32l4系列 使用blunrg-ms的ble gatt 创建 hid 服务失败
  • ¥150 计算DC/DC变换器平均模型中的参数mu
  • ¥25 C语言代码,大家帮帮我
  • ¥50 关于#html5#的问题:H5页面用户手机返回的时候跳转到指定页面例如(语言-javascript)