2013-03-18 3 views
0

배열을 통해 MySQL에 여러 값을 삽입하려고하는데 작동하지 않거나 오류 메시지가 표시되어 어디서 잘못 될지 잘 모르겠습니다. 어떤 도움을 주시면 감사하겠습니다. 여기PHP mysqli insert command

내가 이제 기능을

$testArrayList = array(); 
      $testArrayList[] = 'Account_idAccount'; 
      $testArrayList[] = 'firstName'; 
      $testArrayList[] = 'lastName'; 
      $testArrayValues = array(); 
      $testArrayValues[] = $idAccount; 
      $testArrayValues[] = $firstName; 
      $testArrayValues[] = $lastName; 
      $dbManager->insertValues("User", $testArrayList, $testArrayValues); 

를 호출 할 경우, 여기입니다 호출되는 funciton insertValues입니다.

public function insertValues($table, array $cols, array $values) { 

    $mysqli = new mysqli(DBHOST, DBUSER, DBPASSWORD, DBDATABASE); 

    $colString = implode(', ', $cols); // x, x, x 
    $valString = implode(', ', array_fill(0, count($values), '?')); // ?, ?, ? 

    $sql = "INSERT INTO $table ($colString) VALUES($valString)"; 
    if (!$stmt = $mysqli->prepare($sql)) 
     echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error; 

    foreach ($values as $v) 
     if (!$stmt->bind_param('s', $v)) 
      echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error; 

    if (!$stmt->execute()) 
     echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error; 

    $stmt->close(); 
    $mysqli->close(); 

} 

당신은뿐만 아니라 생성자에서 대신 각 방법에 대해 한 번씩 mysqli 연결을 초기화한다 : 당신이 그 일을해야 기능이 오류의 무리가 있었다

 public function insertValues($table, $cols, $values) { 
    foreach ($cols as $col) 
     $colString .= $col.','; 
    foreach ($values as $value) 
    { 
     $valueAmount .= '?,'; 
     $valueType .= 's'; 
     $valueParam .= $value.","; 
    } 
    $colString = substr($colString, 0, -1); 
    $valueAmount = substr($valueAmount, 0, -1); 
    $valueParam = substr($valueParam, 0, -1); 

    $mysqli = new mysqli(DBHOST, DBUSER, DBPASSWORD, DBDATABASE); 
    $sql = "INSERT INTO $table ($colString) VALUES($valueAmount)"; 
    /* Prepared statement, stage 1: prepare */ 
    if (!($stmt = $mysqli->prepare($sql))) { 
     echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error; 
    } 
    print_r($valueParam); 
    /* Prepared statement, stage 2: bind and execute */ 
    if (!$stmt->bind_param("$valueType", $valueParam)) { 
     echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error; 
    } 

    if (!$stmt->execute()) { 
     echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error; 
    } 
    /* explicit close recommended */ 
    $stmt->close(); 
    $mysqli->close(); 
} 
+1

그래서 당신이 얻는 무슨 오류? –

+0

전혀 오류가 없습니다. 데이터베이스에 값이 표시되지 않기 때문에 작동하지 않는 것입니다. 이전에 -> bindParam 함수 주위에 따옴표를 사용하여 놀았을 때 오류가 발생하는 방식과 오류가 발생하지 않는 방식을 알았지 만 값이 없습니다. 데이터베이스 – AlexHeuman

+1

디버깅을 한 적이 있습니까? –

답변

1

, 여기에 다시 버전입니다 :

:

public function __construct() { 
    $this->mysqli = new mysqli(DBHOST, DBUSER, DBPASSWORD, DBDATABASE); 
} 

public function __destruct() { 
    $this->mysqli->close(); 
} 

또한 당신과 같은 이러한 오류를 처리 할 적절한 기능을 만드는 것이 좋다 당신이 청소기 버전으로 선도

public function showError($message, object $obj) { 
    echo "$message: (" . $obj->errno . ") " . $obj->error; 
} 

가 작동 : 당신은() 잘못된 bind_param를 사용하는 이유 명확하게 SE는 당신이 할 수 있도록

public function insertValues($table, $cols, $values) { 

    ... 

    if (!$stmt = $mysqli->prepare($sql)) 
     $this->showError("Prepare failed", $mysqli); 

    foreach ($values as $v) 
     if (!$stmt->bind_param('s', $v)) 
      $this->showError("Binding parameters failed", $stmt); 

    if (!$stmt->execute()) 
     $this->showError("Execute failed", $stmt); 

    ... 

} 
+0

내 기능을 다시 작성해 주셔서 감사합니다. 불행히도 여전히 작동하지 않습니다. 나는이 두뇌에 내 머리를 wracking. – AlexHeuman

+0

@AlexHeuman, 나는 그것들이 기능상 문제가 아닐까 걱정됩니다. – Shoe

+0

나는 그 사실을 알고 기쁘다. 그리고 당신의 상세한 답변을 주셔서 감사합니다. 또한 $ values ​​배열이 화면에 인쇄되고있는 것처럼 보이지만 어디서나 인쇄하지는 않습니다. 어쨌든, 도와 줘서 고마워. – AlexHeuman

0

내가 기능을 다시 작성했다.

이 버전은 2 열만 사용할 수있는 예입니다.

function insertValues($table, array $cols, array $values) { 

     $mysqli = new mysqli('localhost', 'petr', null,'test'); 

     $colString = implode(', ', $cols); // x, x, x 
     $valString = implode(', ', array_fill(0, count($values), '?')); // ?, ?, ? 

     $sql = "INSERT INTO $table ($colString) VALUES($valString)"; 
     if (!$stmt = $mysqli->prepare($sql)) 
      echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error; 

     list($a,$b) = $values; 
     // params $a and $b must exists during $stmt execution, therefore you can't use foreach with temproray variable 
     if (!$stmt->bind_param('ss', $a, $b)) 
       echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error; 

     if (!$stmt->execute()) 
      echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error; 

     $stmt->close(); 
     $mysqli->close(); 

    } 

이 작동 :

insertValues('test',array('firstName','lastName'),array('Jan Amos','Komensky')); 
+0

감사합니다. bind_param에있는 문자열이지만, 나는 틀렸어. 당신의 도움을 주셔서 감사합니다. – AlexHeuman

+1

감사와 clik "유용한"화살표에 말하지 마 :) – Petr