WORDPRESS:创建一个在点击时更新数据库的功能

时间:2016-10-19 13:29:07

标签: php wordpress

我创建了一个函数,但是我遇到了障碍,我想让if / else hrefs可以点击,我需要它们来添加/删除数据库中的条目,最好的方法是什么?

    // FAVORITE
function favorite($user_id, $post_id) {

    // DB Connection
    $mysqli = mysqli_connect("localhost", "???", "???", "???");

    // Check Favorite
    $getFavoriteQuery = "
        SELECT  *
        FROM    wp_favorites
        WHERE   user_id = $user_id
        AND     post_id = $post_id";

    $favoriteQuery = $mysqli->query($getFavoriteQuery); 

    if (mysqli_num_rows($favoriteQuery)) { ?>

        <a href="#">Un-favorite</a>

        <!-- UPDATE DATABASE MYSQLI QUERY -->

    <?php } else { ?>

        <a href="#">Favorite</a>

        <!-- UPDATE DATABASE MYSQLI QUERY -->

    <?php }

}
?>

1 个答案:

答案 0 :(得分:1)

这不是最好的方式,它当然不是最干净的,但它应该让你知道要进入哪个方向。这也是(我认为)几乎是@ iSS意思。所以很有信心。

前端

function isUserFavorite($user_id, $post_id) {

    // DB Connection
    $mysqli = mysqli_connect("localhost", "???", "???", "???");

    // Check Favorite
    $getFavoriteQuery = "
        SELECT  *
        FROM    wp_favorites
        WHERE   user_id = $user_id
        AND     post_id = $post_id";

    $favoriteQuery = $mysqli->query($getFavoriteQuery); 

    if (mysqli_num_rows($favoriteQuery))
        return true
    else 
        return false
}

if(isUserFavorite($user, $post)){
    $url = "http://domain.com/some/page/with/processing.php?action=unfavorite&user=$user&post=$post";
    $link = "UnFavorite";
}
else{
    $url = "http://domain.com/some/page/with/processing.php?action=favorite&user=$user&post=$post";
    $link = "Favorite";

<a href="<?php echo $url"><?php echo $link ?></a>

Processing.php

<?php
if(isset($_GET['action'],$_GET['user'],$_GET['post']){
    //MySQL Connect

    if($_GET['action']=='favorite'){
        //Query to favorite
    } 
    else if ($_GET['action']=='unfavorite'){
        //Query to unfavorite
    }
    //Redirect here if you like
}
else
    echo "Missing parameter"