Php 获取sql以返回正确的post

Php 获取sql以返回正确的post,php,mysql,pdo,Php,Mysql,Pdo,我正在尝试获取一个sql查询,以通过ID在我的数据库中返回帖子 我的桌子看起来像这样: function getUser($id) { echo $id; //i want to get the post that has this id. } function getProjects() { $sql = "select * FROM projects"; try { $db = getConnection(); $stmt = $db

我正在尝试获取一个sql查询,以通过ID在我的数据库中返回帖子

我的桌子看起来像这样:

function getUser($id) {
    echo $id; //i want to get the post that has this id.
}

function getProjects() {
    $sql = "select * FROM projects";
    try {
        $db = getConnection();
        $stmt = $db->query($sql);
        $users = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
        echo json_encode($users);
    }
    catch(PDOException $e) {
        echo json_encode($e->getMessage());
    }
}
id | img |描述|日期

现在我想返回一个帖子,具体取决于传递的id。 我使用PDO。要返回所有帖子,我会这样做:

function getUser($id) {
    echo $id; //i want to get the post that has this id.
}

function getProjects() {
    $sql = "select * FROM projects";
    try {
        $db = getConnection();
        $stmt = $db->query($sql);
        $users = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
        echo json_encode($users);
    }
    catch(PDOException $e) {
        echo json_encode($e->getMessage());
    }
}
尝试将SQL语句与WHERE子句一起使用,如下所示:

 $sql = "select * FROM projects where id=$id";

在您的项目上下文中,这可能看起来像

getProjects($id);

function getProjects($id) {
    $sql = "select * FROM projects where id=$id";
    /* rest of your code */
}

您忘记了
WHERE
子句

$sql = "select * FROM projects WHERE id = " . $whateveridyouwant;

你只是忘了WHERE子句。我不记得这是否是正确的语法,但肯定是这样的。试试看。

你试过使用where子句吗?你可能想用更多的上下文来扩展这个问题——事实上,这没有多大帮助。