doqpm82240 2013-02-27 06:49
浏览 8
已采纳

如何在推荐系统中显示上述推荐?

I'm having a problem to show users in my referral system.

If you look at table you'll notice userid '29' was refered by '28'; and '28' by '26'; also '26' by '10'

When user session '29' is active the page should display above users. Hope you got the idea.

Referal table:

enter image description here

Code:

<?php
$rs=mysql_query("select userid from referal where refereduserid='29'") or  die(mysql_error());
$exitloopcount=mysql_num_rows($rs);
$last=mysql_fetch_array($rs);
if ($exitloopcount>0) 
{
  for($i=0;$i<$exitloopcount;$i++)
  {
    $rs=mysql_query("select userid from referal where refereduserid='".$last[$i]."'");
    while($data=mysql_fetch_array($rs))
    {
      echo $data[$i];
    } 
  }
}
?>
  • 写回答

1条回答 默认 最新

  • doudeng9425 2013-02-27 07:27
    关注

    This should be able to done by one single query (like Oracle's CONNECT BY clause), but I'm not familiar with MySQL, so I'm offering you the alternative solution, as you will be told "don't use mysql_* functions anymore" by someone here.

    This solution uses MySQLi instead of the deprecated mysql_* function collection.

    $stmt=$mysqli->prepare("SELECT `userid` FROM `referal` WHERE `refereduserid`=?");
    $stmt->bind_param("i",$id); //here $id=29
    $stmt->execute();
    $result=$stmt->get_result();
    while($row=$result->fetch_assoc())
    {
        echo $row["userid"];
        $id=intval($row["userid"]);
        $stmt->bind_param("i",$id);
        $stmt->execute();
        $result=$stmt->get_result();
    }
    

    Edit:

    Explanation:

    One thing about MySQLi and PDO is that they supports prepared statement.

    As this is a chained relationship (and thankfully a one-to-one one), I can simply prepare one query:

    SELECT `userid` FROM `referal` WHERE `refereduserid`=?
    

    this query will be used to continuously fetched the "referrer".

    Then we bind the "initiate" id, 29, and executes the query.

    While a "referrer" is found, echo it out (as demonstrated in your code), and then re-bind it to the prepared query, and executes it to find its "referrer". Continue this step.

    Using the sample date in your question:

    1. bind: 29 -> executes -> get: 28
    2. bind: 28 -> executes -> get: 26
    3. bind: 26 -> executes -> get: 10
    4. bind: 10 -> executes -> no result
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM