2012-07-18 53 views
1

我的代码来生成SQL语句工作正常 - 但是当生成$ stmt-> bind_param字符串时,我遇到了一个呃逆。代码如下:PHPs mysqli prepare - 动态生成

$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(); 

} 

的该格式弄乱。我很抱歉,如果它很难阅读。

我收到以下错误:

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

任何想法?

+0

这么多'mysql_'和'mysqli'在过去一小时......用[PDO](http://us2.php.net/manual/en /book.pdo.php)。 – 2012-07-18 02:32:08

+0

我正在研究它。然而,使用mysqli和PDO的争论在双方都是很好的。我认为mysqli是滚动的方式。也许不会。 – 2012-07-18 02:33:17

+0

我并没有觉得有很多争论,但我现在会去看看所说的论点。 – 2012-07-18 02:35:24

回答

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; 

} 
+0

我正在看PDO,很可能会将此测试代码迁移到测试代码。另外你实际上回答了我的问题,所以谢谢。 – 2012-07-18 02:48:56

0

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

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

每个这些值是一个实际的变量。

+0

我明白这一点。如果仔细观察代码,您会看到循环会生成$ bind_types和$ bind_values。然后我使用bind_param调用中的那些。我怀疑这仍然可能是问题,尽管这两个字符串的输出是正确的。 – 2012-07-18 02:40:39

+0

'$ bind_values'是一个字符串,'bind_param'不会将字符串作为第二个参数。 – 2012-07-18 02:41:57

+0

我怀疑那个。该死的。 – 2012-07-18 02:42:26