如何使用绑定变量来初始化mySql表的列?

时间:2019-07-12 15:18:57

标签: php mysql

我将对PHP使用SELECT QUERY,但我不知道我的表有多少列。 该表(名称Player)目前有6个列(ID,名称,姓氏,鸟数,财务代码和team1,这是表TEAM列“ id”的外键),但是在我的Android程序中,用户可以为每个玩家添加更多球队(使用QYERY 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不接受列名作为字符串类型! 我该怎么办? Ty

1 个答案:

答案 0 :(得分:0)

您不应在表格中为每个团队添加新列。您应该将表标准化为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)) {

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