我将对PHP使用SELECT QUERY,但我不知道表中有多少列。
该表(名称播放器)目前有6列(ID,名称,姓氏,鸟的床位,财务代码和team1,这是表TEAM的列“ id”的外键),但在我的Android程序中,用户可以为每个玩家添加更多的团队(使用QUERY ALTER TABLE)。

现在,我将创建一个片段,用于查看按团队划分的球员...因此,在公共功能中,我创建了SELECT QUERY,在这里我只选择具有与用户看到的相同团队ID的球员。

现在这就是问题所在:ID可能在未知列之一中,其名称以“ team”开头并加上一个数字。

因此,我尝试使用bind_param创建查询。

    //Code for get how many times i need to call showPlayerList methods
    //return the number of columns "team+NUMBER"
public function numberColumnsSquadra() {
    $stmt = $this -> con -> prepare("SHOW COLUMNS FROM player");
    $stmt -> execute();
    $stmt -> store_result();
    return ($stmt -> num_rows) - 5;
}

//code for find who player has the correct id of team in column "team+NUMBER"
//$id (int) is the team id
//&team (int) from 0 to ...
public function showPlayerList($id, $team) {
    $column = "team".$team;
    $stmt = $this -> con -> prepare("SELECT id, name, surname, 'date of birth', 'fiscal code' FROM Player WHERE ? = ?");
    if($stmt -> bind_param("si", $column, $id)) {
        if($stmt -> execute()) {
            $response = $stmt -> get_result();
            return $response;
        } else {
            return null;
        }
    } else {
        echo "bind_param failure";
    }
}

//In another file I call showPlayerList
...
    $t=0;
    $squadra = $db -> numberColumnsSquadra();
    for($i=1; $i <= $squadra; $i++) {
        $result = $db -> showPlayerList($_POST['id'], $i);
        //Save the result in &response array precedently create
        for($row = $result->fetch_assoc(); $row == true; $row = $result->fetch_assoc()) {
            $response['id '.$t] = $row['id'];
            $response['name'.$t] = $row['name'];
            $response['surname'.$t] = $row['surname'];
            $response['date of birth '.$t] = $row['date of birth'];
            $response['fiscal code '.$t] = $row['fiscal code'];
            $t++;
        }
...


如果我尝试查看$ result(以json_format封装后),我什么也看不到。
经过很多次我重新制作代码(并且做了很多调试)之后,我知道问题出在bind_param()中。

MySQL不接受列名作为字符串类型!

我该怎么办?

最佳答案

您不应该在表格中为每个团队添加新列。您应该将表标准化为3FN并为团队创建一个新表,为关系用户和团队创建另一个表。如果用户是100个团队的成员,会发生什么?您会为每个人增加100列吗?您将如何处理?

或更糟糕的是,如果为每个团队添加一个新列(每个人),那么如果您要管理500个团队,则每行将有500列。您怎么知道每个团队中都有哪位成员?您会查询500列吗?

并回答您的问题,您不能绑定列的名称,您需要像这样连接字符串:

$stmt = $this -> con -> prepare("SELECT id, name, surname, `date of birth`, `fiscal code` FROM Player WHERE ".$column." = ?");
if($stmt -> bind_param("i", $id)) {


另外,您需要更改'并使用反引号`作为列名

关于php - 如何使用绑定(bind)变量指示mySql表的列?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57009828/

10-14 19:32
查看更多