我正在使用PHP和MySQL开发一个项目。
我有一个HTML表,其中包含3列,我从MySQL中的“任务”表中加载数据。这些列是:id
,taskname
和一个按钮列,当您点击该列时,会将您带到相关任务的Edit
页面(我将任务ID作为URL传递) - { {1}}
当我尝试加载有关此任务的详细信息时,会出现问题。这是代码:
http://localhost/tasks/?edit&id=3
我收到以下错误:
if(isset($_GET["id"]))
{
try
{
$sql = "SELECT * FROM tasks WHERE id = :id";
$result = $pdo->prepare($sql);
$result->bindValue(":id", $_GET["id"]);
$result = $pdo->query($sql);
}
catch(PDOException $e)
{
$error = "Error trying to load task - " . $e->getMessage();
include "error.php";
exit();
}
foreach($result as $task)
{
$tasktext = $task["task"];
$id = $task["id"];
}
$title = "Edit task";
$action = "edittask";
$button = "Edit task";
include 'form.php';
exit();
resetParameters();
当我将Error trying to load task - SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':id' at line 1
替换为WHERE id = :id
时,它可以正常运行并加载有关任务的详细信息,但我根本无法加载有关我在上一个屏幕中点击的任务的详细信息
有没有人发现我的代码/逻辑有什么问题,请指出我正确的方向?
答案 0 :(得分:0)
使用准备好的查询时,您需要使用execute()而不是query():
尝试:
<?php
try
{
$sql = "SELECT * FROM tasks WHERE id = :id";
$query = $pdo->prepare($sql);
$query->bindValue(":id", $_GET["id"]);
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
}
catch(PDOException $e)
{
$error = "Error trying to load task - " . $e->getMessage();
include "error.php";
exit();
}
?>