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

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog