普通网友 2016-01-08 20:49
浏览 123
已采纳

在另一个查询的WHERE条件中使用查询中的数据

I have database consist of different tables, the table I care about are, user and module, after the user login the second query must return the max(id) from the module user. What I am trying to do is: I want to get the max(id) of the same user who is logged in, the user are stored in module table in create_user column, is possible to do that and how should the where condition be?

The table structure:
user table: (id int pri.key, username varchar, password varchar).
module table: (id int pri.key, name varchar, creat_time date, create_user int)

When inserting new module the user id is stored in create_user.

The code:

<?php
$json["status"] = "running";
$details[] = "started get_tables ";
include_once('confi.php');
$request_body = file_get_contents('php://input');
$statement = "INSERT INTO tbl_archive (content) VALUES ('$request_body' );";
mysql_query($statement);
$input = json_decode($request_body, true);
$user = $input["user"];
$password = $user["password"];      
    $mySQLstring = "SELECT username, password, id FROM tbl_user where username = '$username' ;";
    $json["statement"][] = $mySQLstring;
    $qur = mysql_query($mySQLstring);
            if ($qur){
        $max = mysql_fetch_assoc($qur);
    }
    if ($max){
        $json["max"] = $max;
        if ($max["password"] == $password){
            $json["username"] = $username;
            $json["id"] = $max["id"];               
            $json["status"] = "ok";
            $tables = array("class", "class_user", "module", "module_class", "module_user", "rating", "student", "student_class");
            foreach($tables as $table){
                $id= $max["id"];
                if ( $table == 'module' ){

                $statement ='SELECT create_user, MAX(id) AS id FROM tbl_'.$table;
                  $statement .= ' WHERE create_user =$id' ;

                $qur = mysql_query($statement);
                if ($qur){
                    while($r = mysql_fetch_array($qur, MYSQL_ASSOC)){
                        $result[$table][] = $r;
                    }
                }
                }
            }
            $json = array("status" => "ok", "data" => $result);
        }
    }
}



@mysql_close($conn);
header('Content-type: application/json');
echo json_encode($json);
?>
  • 写回答

1条回答 默认 最新

  • dongtuo3795 2016-01-08 21:56
    关注

    So tbl_user.id and tbl_module.create_user are user-IDs. You queried tb_user and fetched the result into $max.

    $statement  = 'SELECT create_user, MAX(id) AS id FROM tbl_'.$table;
    $statement .= ' WHERE create_user = ' . $max['id'];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验