dongyulan6251 2015-12-28 15:58
浏览 50
已采纳

为每个MySQL行调用一个函数

I have a standard MySQL database, with around 60 rows (as in user accounts). When I first made it I made the mistake of making session IDs the same as the simple account ID, now I want to fix my mistake and I am obviously not going to go through 60 rows to reset them different secure session IDs, so I am writing this function:

function generate_sessionid(){
    return bin2hex(openssl_random_pseudo_bytes(32));
}

function assign_all_sessionids(){
    $sessionid = generate_sessionid();

    $conn = sql_connect();
    $result = mysqli_query($conn, "UPDATE accounts SET sessionid='$sessionid' WHERE 1");
    sql_disconnect($conn);
}
assign_all_sessionids();

Problem: Every account in the database gets the same random session ID as the rest. How do I make it recall the function for each row in order to allow it to be random for each row?

  • 写回答

3条回答 默认 最新

  • duanhe4155 2015-12-28 16:22
    关注

    Try get user's count from DB and simply execute it N times

    function assign_all_sessionids(){
    
      $conn = sql_connect();
    
      // getting users count
      // here just change 'id' to your id parameter
      $result = mysqli_query($conn, "SELECT id FROM accounts"); 
      $arr = $result->fetch_array(MYSQLI_NUM);
    
      // executing N times
      for($i = 0; $i < $result->num_rows; $i++){
         $sessionid = generate_sessionid();
      // here just change 'id' to your id parameter again
         mysqli_query($conn, "UPDATE accounts SET sessionid='$sessionid' WHERE `id`=".$arr[$i]);
      }
    
    sql_disconnect($conn);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?