1

我需要一些帮助,将 PHP 代码添加到我的 MySQL 中。这是代码:

$query_qPosts = "SELECT * FROM front_news WHERE draft = 1 AND department_id = 1 OR     department_id = 0 ORDER BY id DESC";

在上面写着“department_id = 1”的地方,我需要将 1 替换为<?php echo $id ?>.

4

6 回答 6

3
$query_qPosts = "SELECT * FROM front_news WHERE draft = 1 AND department_id = $id OR     department_id = $id ORDER BY id DESC";

在 php 中,您可以将变量封装在双引号内,它们将构成字符串的一部分。例如

$foo = 'foo';
$echo = "I am $foo";
----> I am foo

至于单引号,您需要将它们连接起来。例如

$foo = 'foo';
$echo = 'I am ' . $foo;
----> I am foo

至于你会使用哪一个,这取决于你使用它们的环境,通常这取决于个人喜好。单引号比双引号执行得更快。

于 2012-12-11T05:08:58.643 回答
1

如果你使用mysqli,它会使这个过程变得非常简单:

$db = new mysqli("localhost", "user", "password", "mydatabase");
$query_qPosts = $db->prepare("SELECT * FROM front_news WHERE draft = 1 AND department_id = ? OR department_id = 0 ORDER BY id DESC")
$id = 1;
$query_qPosts->bind_param("i",$id)
if (!$query_qPosts->execute()) {
    echo "There was an error (" . $query_qPosts->errno . ") " . $query_qPosts->error;
}
于 2012-12-11T05:15:21.467 回答
0

在 SQL 查询中同时使用“AND”和“OR”时,必须用括号分组。否则结果不可预测或查询失败。

如果部门可以为 0 或 1,而草稿必须为 1,请执行以下操作:

"SELECT * FROM front_news WHERE draft = 1 AND (department_id = 1 OR department_id = 0) ORDER BY id DESC"

或者如果草稿必须为 1 且部门必须为 1 或部门为 0,请尝试以下操作:

"SELECT * FROM front_news WHERE (draft = 1 AND department_id = 1) OR department_id = 0 ORDER BY id DESC"

我不确定你想做什么。

您正在使用双引号,因此代码中的每个“$”都作为变量执行。为了确保发生这种情况,如果你想要“{$id}”,你可以用花括号括起来。

于 2012-12-11T05:11:36.780 回答
0
$query_qPosts = "SELECT * FROM front_news WHERE draft = 1 AND department_id = 1 OR   department_id = ".$id." ORDER BY id DESC";
于 2012-12-11T05:14:10.687 回答
0

尝试

"SELECT * 
 FROM front_news 
 WHERE draft = 1 
    AND department_id = ".<?php echo (int)$id?>." 
    OR  department_id = 0 
 ORDER BY id DESC";
于 2012-12-11T05:15:56.600 回答
0

试试这个代码:

$query_qPosts = "SELECT * FROM front_news WHERE draft = 1 AND department_id = $id OR department_id = 0 ORDER BY id DESC";

请确保 $id 是数字而不是 null

于 2012-12-11T06:18:14.053 回答