PHPs mysqli准备 - 动态生成

时间:2012-07-18 02:30:43

标签: php mysqli

我生成SQL语句的代码运行正常 - 但是在生成$ stmt-> bind_param的字符串时遇到了打嗝。代码如下:

$stmt = $mysqli->stmt_init(); if ($stmt->prepare ($sql)) { $bind_types = '"'; $bind_values = '';

    if ($action == 'insert' || $action == 'update') {
        reset ($array);
        foreach ($array as $key => $value) {
            if (is_string ($value)) { $type = 's'; } else if (is_int ($value)) { $type = 'i'; } else if (is_float ($value)) { $type = 'd'; } else { die ('Cannot determine type for ' . $key . ' => ' . $value . ''); }
            $bind_types .= $type;
            $bind_values .= $value . ', ';
            //$stmt->bind_param ($type, $value);
        }
    }

    if ($action == 'update' || $action == 'delete') {
        if (is_string ($id_value)) { $type = 's'; } else if (is_int ($id_value)) { $type = 'i'; } else if (is_float ($id_value)) { $type = 'd'; } else { die ('Cannot determine type for ' . $id_column . ' => ' . $id_value . ''); }
        $bind_types .= $type;
        $bind_values .= $id_value . ', ';
        //$stmt->bind_param ($type, $id_value);
    }

    $bind_types .= '"';

    $bind_values = substr ($bind_values, 0, -2);

    echo $bind_types  . ', ' . $bind_values;

    $stmt->bind_param ($bind_types, $bind_values);
    $stmt->execute();

}

if ($action == 'insert' || $action == 'update') { reset ($array); foreach ($array as $key => $value) { if (is_string ($value)) { $type = 's'; } else if (is_int ($value)) { $type = 'i'; } else if (is_float ($value)) { $type = 'd'; } else { die ('Cannot determine type for ' . $key . ' => ' . $value . ''); } $bind_types .= $type; $bind_values .= $value . ', '; //$stmt->bind_param ($type, $value); } } if ($action == 'update' || $action == 'delete') { if (is_string ($id_value)) { $type = 's'; } else if (is_int ($id_value)) { $type = 'i'; } else if (is_float ($id_value)) { $type = 'd'; } else { die ('Cannot determine type for ' . $id_column . ' => ' . $id_value . ''); } $bind_types .= $type; $bind_values .= $id_value . ', '; //$stmt->bind_param ($type, $id_value); } $bind_types .= '"'; $bind_values = substr ($bind_values, 0, -2); echo $bind_types . ', ' . $bind_values; $stmt->bind_param ($bind_types, $bind_values); $stmt->execute(); }

格式化了搞砸了。如果难以阅读,我道歉。

我收到以下错误:

“警告:mysqli_stmt :: bind_param()[mysqli-stmt.bind-param]:类型定义字符串中的元素数与...中的绑定变量数不匹配”“

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

我强烈建议您使用PDO,因为您可以轻松完成。如果你想在mysqli中这样做,它会更复杂,因为你不能轻易地动态绑定它们。 要动态绑定它们,请查看这个丑陋的黑客

$bind_values= explode(',', $bind_values);
call_user_func_array(array($stmt, 'bind_param'), makeValuesReferenced($bind_values));
$stmt->execute();

function makeValuesReferenced(&$arr){ 
    $refs = array(); 
    foreach($arr as $key => $value) 
        $refs[$key] = &$arr[$key]; 
    return $refs; 

}

答案 1 :(得分:0)

您对bind_param的来电是错误的:它应该是:

bind_param($types, $value1, $value2, $value3 ...);

其中每个值都是实际变量。