我正在做一个使用PHP和MySQL的项目。
我有一个包含3列的HTML表,我从MySQL中的"Tasks“表中将数据加载到其中。这些列是:id、taskname和一个按钮列,当单击该按钮列时,您将转到相关任务的Edit页面(我将任务id作为URL传递)- 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 = 3替换WHERE id = :id时,它可以工作并加载任务的详细信息,但是我就是不能让它加载我在前一个屏幕中单击的任务的详细信息。
谁能发现我的代码/逻辑中有什么错误,并给我指出正确的方向?
发布于 2013-07-14 23:55:48
在使用预准备查询时,您需要使用execute()而不是query():
statement::execute-执行准备好的SQL::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();
}
?>https://stackoverflow.com/questions/17640976
复制相似问题