2012-07-18 54 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