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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀