2016-10-19 65 views
0

我已經創建了一個函數,但我已經到了一個障礙,我想使if/else hrefs可點擊,我需要他們添加/刪除條目到數據庫中,什麼做到這一點的最佳方式?WORDPRESS:創建一個函數,點擊更新數據庫

// 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

使用GET參數,然後在代碼中查詢到。例如:'http://somedomain.com/wordpress/?action = inconvourite&user = someuser'。在PHP中,你會得到''_GET'全局數組填充'action'和'user'索引。 '$ action = $ _GET ['action']; // $ action =='unfavourite''。從此,你可以在每個動作背後附加你的邏輯。 :) – iSS

回答

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" 
相關問題