Php 如何传递多个列以更灵活地绑定_result()?
我有一些长MySQL表,其设计还没有完全固定。因此,偶尔,我需要添加/删除一些列。但是,每次修改表时,我都必须重写所有处理bind_result()的行。我正在寻找一个解决方案,使这一变化容易 假设我当前有一个表,其中包含列,如col_a、col_b、col_c、…、col_z。因此,我使用bind_result()存储结果值,如手册所述Php 如何传递多个列以更灵活地绑定_result()?,php,mysql,prepared-statement,Php,Mysql,Prepared Statement,我有一些长MySQL表,其设计还没有完全固定。因此,偶尔,我需要添加/删除一些列。但是,每次修改表时,我都必须重写所有处理bind_result()的行。我正在寻找一个解决方案,使这一变化容易 假设我当前有一个表,其中包含列,如col_a、col_b、col_c、…、col_z。因此,我使用bind_result()存储结果值,如手册所述 $res = $stmt->bind_result($a, $b, $c,..., $z); 但是,如果我更改表设计,我必须更改处理这个bind_re
$res = $stmt->bind_result($a, $b, $c,..., $z);
但是,如果我更改表设计,我必须更改处理这个bind_result()的所有行的参数,以匹配新的MySQL表
有没有像下面这样的技巧
// Some php file defining constants
define("_SQL_ALL_COLUMNS", "\$a, \$b, \$c, \$d, ... \$z");
// Some SQL process in in other php files
stmt->execute();
$res = $stmt->bind_result(_SQL_ALL_COLUMNS);
所以,我不需要担心其他文件中参数数量的变化,只要我在某个地方正确定义了它们。当然,我已经发现我在上一个例子中的尝试不是正确的方法
对于这种情况有什么好的解决方案吗?用于动态设置参数的数量:
function execSQL($con, $sql, $params = null)
$statement = $con->prepare($sql);
if (!$statement){
// throw error
die("SQL ERROR: $sql\n $con->error");
}
$type = "";
$arg = array();
if ($params && is_array($params)){
foreach($params as $param){
if (is_numeric($param)){
$type .= 'd';
continue;
}
$type .= 's';
}
$arg[] = $type;
foreach($params as $param){
$arg[] = $param;
}
call_user_func_array(array($statement,'bind_param'), refValues($arg)); // php 7
}
$res = $statement->execute();
if (!$res){
die("Looks like the Execute Query failed.\n\nError:\n{$statement->error}\n\nQuery:\n{$sql}\n\nParams:\n{".implode(",", $arg)."}");
}
return $con->insert_id;
}
function refValues($arr){
if (strnatcmp(phpversion(),'5.3') >= 0) { //Reference is required for PHP 5.3+
$refs = array();
foreach($arr as $key => $value){
$refs[$key] = &$arr[$key];
}
return $refs;
}
return $arr;
}
$result = execSQL($connection,$sql,["a","b","c","..."]);
可以通过使用参数数组调用函数execSQL来使用它:
function execSQL($con, $sql, $params = null)
$statement = $con->prepare($sql);
if (!$statement){
// throw error
die("SQL ERROR: $sql\n $con->error");
}
$type = "";
$arg = array();
if ($params && is_array($params)){
foreach($params as $param){
if (is_numeric($param)){
$type .= 'd';
continue;
}
$type .= 's';
}
$arg[] = $type;
foreach($params as $param){
$arg[] = $param;
}
call_user_func_array(array($statement,'bind_param'), refValues($arg)); // php 7
}
$res = $statement->execute();
if (!$res){
die("Looks like the Execute Query failed.\n\nError:\n{$statement->error}\n\nQuery:\n{$sql}\n\nParams:\n{".implode(",", $arg)."}");
}
return $con->insert_id;
}
function refValues($arr){
if (strnatcmp(phpversion(),'5.3') >= 0) { //Reference is required for PHP 5.3+
$refs = array();
foreach($arr as $key => $value){
$refs[$key] = &$arr[$key];
}
return $refs;
}
return $arr;
}
$result = execSQL($connection,$sql,["a","b","c","..."]);
这样做的目的是检查参数的数据类型,并将其附加到
$type
变量,然后将该变量作为第一个参数传递给bind方法。否,没有内置的方法可以这样做。也许你应该使用ORM进行调查。顺便说一句,您缺少第一个参数,该参数包含一个类似“sssiii”
的字符串。