没有得到DB的结果

时间:2014-06-29 22:01:43

标签: php html mysql database

所以我要查看用户是否已经喜欢过帖子。这就是我正在做的事情

$id = 65;

//Get likes count
$stmt = $con->prepare("SELECT * FROM likes WHERE liked_post_id = :liked_post_id");
$stmt->bindValue(':liked_post_id', $id, PDO::PARAM_STR);
$stmt->execute();
$return = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<pre>
<?php
print_r($return);
?>
</pre>
<?php

//Get user IP
$ip = $_SERVER['SERVER_ADDR'];

//Check if user liked post
$result = $con->prepare("SELECT * FROM likes WHERE liked_post_user = :username");
$result->bindParam(':username', $_SESSION['user']);
$result->execute();
$reprint = $result->fetch(PDO::FETCH_ASSOC);
echo $reprint['liked_post_user'];
$return_cnt =  count($reprint);

if($return_cnt < 1){
//Insert like
$query = $con->prepare("INSERT INTO likes (liked_post_id, liked_post_user, liked_post_ip) VALUES (:usr_id, :user, :ip)");
$query->bindValue(':usr_id', $id, PDO::PARAM_STR);
$query->bindValue(':user', $_SESSION['user']);
$query->bindValue(':ip', $ip, PDO::PARAM_STR);
$query->execute();
}

问题是$query永远不会被运行。即使我没有DB中的用户名记录。所以我希望它运行一次,然后将$query插入数据库一次。但它不是。我也没有收到任何错误。有任何想法吗?

2 个答案:

答案 0 :(得分:0)

第二个查询应该查找特定的liked_post_id。它目前正在寻找用户喜欢的任何帖子,而不仅仅是这个帖子。

//Check if user liked post
$result = $con->prepare("SELECT * FROM likes WHERE liked_post_user = :username AND liked_post_id = :id");
$result->bindParam(':username', $_SESSION['user']);
$result->bindParam(':id', $id);
$result->execute();
$reprint = $result->fetch(PDO::FETCH_ASSOC);

然后您应该通过测试$reprint是数组还是false来测试查询是否找到了任何内容:

if ($reprint) {
    echo $reprint['liked_post_user'];
} else {
    //Insert like
    $query = $con->prepare("INSERT INTO likes (liked_post_id, liked_post_user, liked_post_ip) VALUES (:usr_id, :user, :ip)");
    $query->bindValue(':usr_id', $id, PDO::PARAM_STR);
    $query->bindValue(':user', $_SESSION['user']);
    $query->bindValue(':ip', $ip, PDO::PARAM_STR);
    $query->execute();
}

答案 1 :(得分:0)

首先,您可以简单地计算$reprint。要回答您的第二个问题,您需要选择帖子,否则它只需检查所有帖子。

$result = $con->prepare("SELECT * FROM likes WHERE liked_post_user = :username AND liked_post_id = :post_id");
$result->bindParam(':username', $_SESSION['user']);
$result->bindParam(':post_id', $_GET['id']);
$result->execute();
$reprint = $result->fetch(PDO::FETCH_ASSOC);

请注意,如果没有用户登录,则仍会输入空值。所以一定要想办法解决这个问题。