dongtanlin0765 2016-10-19 13:29
浏览 49
已采纳

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

I have created a function but I have come to a hurdle, I want to make the if/else hrefs clickable and I need them to add/remove entries into the database, whats the best way to do this?

    // 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条回答 默认 最新

  • douzheng9221 2016-10-19 14:26
    关注

    This is not the best way necessarily, it certainly isn't the cleanest but it should give you an idea of which direction to head in. Also this is (I think) pretty much what @iSS meant. So credit.

    Front End

    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"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?