gpt4 book ai didi

php - 如何使用绑定(bind)变量来启动 mySql 表的列?

转载 作者:行者123 更新时间:2023-11-29 15:46:16 25 4
gpt4 key购买 nike

我会使用 PHP 的 SELECT QUERY,但我不知道我的表有多少列。表(名称 Player)目前有 6 列(ID、名字、姓氏、鸟的日期、财政代码和 team1,它是表 TEAM 列“id”的外键),但在我的 Android 程序中,用户可以为每个玩家添加更多团队(使用 QUERY ALTER TABLE)。

现在,我将创建一个片段来查看按团队划分的玩家...因此,在公共(public)函数中,我创建了 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 列吗?

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

$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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com