0

好的,我以为我有这个,但我不明白为什么它不起作用......我有一个带有变量表的 SELECT,因此我的列(bind_result)将是可变的。我需要调整返回的任意数量的列,并将其作为关联数组提取,因为将返回多行:

// Get table data
$mysqli = new mysqli('host','login','passwd','db');
if ($mysqli->connect_errno()) { $errors .= "<br>Cannot connect: ".$mysqli->connect_error()); }
$stmt = $mysqli->prepare("SELECT * FROM ?");
$stmt->bind_param('s', $table);
$stmt->execute();

// Get bind result columns
$fields = array();
// Loop through columns, build bind results
for ($i=0; $i < count($columns); $i++) {
$fields[$i] = ${'col'.$i};
}

// Bind Results
call_user_func_array(array($stmt,'bind_result'),$fields);

// Fetch Results
$i = 0;
while ($stmt->fetch()) {
  $results[$i] = array();
  foreach($fields as $k => $v)
     $results[$i][$k] = $v;
  $i++;
}

// close statement
$stmt->close();

任何想法都非常感谢^ _ ^

编辑:新代码:

$mysqli = new mysqli('host','login','passwd','db');
if ($mysqli->connect_errno)) { $errors .= "<br>Cannot connect: ".$mysqli->connect_error()); }
$stmt = "SELECT * FROM ".$table;

if ($query = $mysqli->query($stmt)) {
$results = array();
while ($result = $query->fetch_assoc()) {
    $results[] = $result;
}
$query->free();
}
$mysqli->close();
4

1 回答 1

1

不能绑定表名。Bind_param 接受列名及其数据类型。

要动态使用表名,请使用以下代码:

$stmt = $mysqli->prepare("SELECT * FROM ".$table);
于 2013-07-19T20:41:02.923 回答