致命错误:在 PHP 中使用 MySQL Left Join 对非对象调用成员函数execute()
我在编写一个与基本 CMS 配合使用的简单博客脚本时,在左连接方面遇到了一些问题。
$result = $dbc->prepare("SELECT blog.id, blog.title, blog.post, blog.date, blog.time, comments.blogid FROM blog LEFT JOIN comments ON blog.id = comments.blogid ORDER BY id DESC LIMIT $start_blog, $blog_per_page");
$result->execute();
$result->bind_result($id, $title, $post, $date, $time, $blogid);
上面的代码返回以下错误: 致命错误:在第 56 行对 C:\xampp\htdocs\pcms\includes\blog.php 中的非对象调用成员函数execute()(第 56 行是 $result ->execute();)
I只是看不到导致错误的原因,如果我删除 LEFT JOIN,SQL 代码就可以正常工作。
I am having some trouble with a left join in a simple blog script I am writing to go with my basic CMS.
$result = $dbc->prepare("SELECT blog.id, blog.title, blog.post, blog.date, blog.time, comments.blogid FROM blog LEFT JOIN comments ON blog.id = comments.blogid ORDER BY id DESC LIMIT $start_blog, $blog_per_page");
$result->execute();
$result->bind_result($id, $title, $post, $date, $time, $blogid);
The above code is returning the following error:
Fatal error: Call to a member function execute() on a non-object in C:\xampp\htdocs\pcms\includes\blog.php on line 56 (with line 56 being $result ->execute();)
I just cant see what is causing the error, if I remove the LEFT JOIN the SQL code is working fine.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据关于准备函数的 PHP 手册:
如果数据库服务器成功准备语句,PDO::prepare() 返回一个 PDOStatement 对象。如果数据库服务器无法成功准备语句,PDO::prepare() 将返回 FALSE 或发出 PDOException(取决于错误处理)。
您收到致命错误的原因是您没有检查准备是否成功。永远不要假设可能失败的方法是成功的。
调用准备失败的原因是您使用了错误的参数绑定语法。应该是? (对于未命名参数)或 :variable_name (对于命名参数)。 $variable_name 不起作用。
From the PHP manual on the prepare function:
If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object. If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException (depending on error handling).
The reason you're getting a fatal error is because you're not checking to see if prepare was successful. Never assume that a method that might fail was successful.
The reason why your call to prepare failed is because you're using the wrong syntax for parameter binding. It should be ? (for unnamed parameters) or :variable_name (for named parameters). $variable_name doesn't work.
好的,经过多次尝试和错误,我设法获得了正确的左连接查询。如果有人觉得有用或感兴趣的话,这是代码。
非常感谢您的帮助和输入,这一切加起来找到了我渴望的解决方案!
吉姆
Ok, after much trial and error I managed to get the correct left join query. Here is the code if anybody finds it of use or interest.
Many thanks for the help and input, it all added up to finding the solution that I craved!!
Jim
你的sql查询有错误,
应该是
Your sql query got an error,
should be