是否有可能只为用户运行一次PHP代码?

时间:2015-09-26 18:57:18

标签: php wordpress

我的例子是,如果用户选择apple,它只会为该用户运行一次代码。我的示例代码:

<?php
/*
id  user_id   category
1         2      apple
2         4     banana
3         6      apple
4         7      berry
*/
$sql = $wpdb->get_results("SELECT category FROM $table_name WHERE user_id=1");
foreach( $sql as $value) {
    $category = $value -> category;
    if ($category == 'apple') {
        //code here only run once
    } else {
        //code will run as many as time if the user click
    }
}
?>

1 个答案:

答案 0 :(得分:1)

您可以设置SESSION变量,如:

foreach($sql as $value) {
   if($value->category == "apple" && !isset($_SESSION["yourvarname"])) {
      //run your code once
      $_SESSION["yourvarname"] = 1;
   }
   else {
      //run your code many times
   }
}