2014-01-05 2 views
1

foreach 및 implode 함수를 사용하여 많은 예제를 통해 MySQL 삽입 쿼리를위한 SQL 문자열을 작성했습니다. 그러나 모든 예제에서는 Array의 모든 값과 MySQL 테이블의 모든 열은 문자열 또는 숫자로 가정합니다. 거기에 비슷한 일을 할 수있는 방법이 있지만, 문자열과 숫자를 모두 가지고 있으며 문자열과 숫자 열을 가진 MySQL 테이블에 삽입되는 배열을 가지고 있습니까? order_iduser_id은 문자열과 pricequantity 숫자 때문에MySQL에 문자열과 숫자가 모두 포함 된 다차원 배열을 삽입하십시오.

$insertArr[] = array(
     'order_id' => $orderID, 
     'user_id' => $userID,   
     'price' => $price, 
     'quantity' => $quantity); 

$colNames = "(" . implode(", ",array_keys($insertArr[0])) . ")"; 
foreach ($insertArr as $row) 
{   
    $colValuesArr[] = "('" . implode("', '", $row) . "')"; 
} 
$colValues = implode(", ", $colValuesArr); 
$strsql = "INSERT INTO tbl_orders $colNames 
      VALUES $colValues"; 

위의 코드는 잘 작동하지 않습니다. 따옴표와 쉼표로 Imploding하면 모든 값이 문자열이라고 가정하고 따옴표없이 값을 채우면 모든 값이 숫자라고 가정합니다. 이 작업을 수행하기 위해 배열의 모든 단일 요소를 반복하지 않고도 방법이 있습니까?

+0

변수'$의 strsql'가 유효하지 않은 SQL 구문을 가지고있다. 그 이유는 코드가 작동하지 않는 이유를 설명 할 수 있습니다. –

+1

MySQL은 따옴표로 묶인 숫자를 사용하는 것이 좋습니다. 간단하게 유지하려면 모든 것을 인용하십시오. (그러나 데이터를 탈출하는 것을 잊지 마십시오!) 또는 준비된 진술을 살펴보십시오. 장기적으로, 그들은 당신을 위해 일을 훨씬 쉽게 할 것입니다. – cHao

+0

Gordon Linoff, $ strsql SQL 구문의 문제점은 무엇입니까? 그것은 나에게 좋은 것처럼 보인다. 나는 그것을 인쇄했다, 그것과 함께 틀린 아무것도 보지 마라. 더 자세하게 얘기해 주 시겠어요? – user2395238

답변

1

이것을 처리하려는 방식이라고 가정하면 & 배열을 반복하거나 준비된 명령문을 사용하지 않으려 고합니다.이 방법이 효과가 있다고 생각합니다. 나는 당신의 코드를 약간 다시 포맷했지만 전반적인 로직은 그대로이다. 내가 추가 한 논리는 기본적으로 두 개의 개별 배열을 만드는 것입니다. 하나는 숫자 값입니다. 텍스트 값 다른 :

// Test data. 
$orderID = 'testorderid'; 
$userID = 'testuserid'; 
$price = 7.99; 
$quantity = 2; 

// Create the text values array. 
$insertArrText[] = array('order_id' => $orderID, 'user_id' => $userID); 

// Create the numerical values array. 
$insertArrNumerical[] = array('price' => $price, 'quantity' => $quantity); 

// Get the array keys & merge them into one combined array. 
$array_keys = array_merge(array_keys($insertArrText[0]), array_keys($insertArrNumerical[0])); 

// Set the column names. 
$colNames = "(" . implode(", ", $array_keys) . ")"; 

// Loop through the '$insertArrText' 
foreach ($insertArrText as $key => $row) { 

    // Set the numerical values. 
    $numerical_values = implode(", ", $insertArrNumerical[$key]); 

    // Set the text values. 
    $text_values = "'" . implode("', '", $row) . "'"; 

    // Set the column values array. 
    $colValuesArr[] = "(" . $text_values . "," . $numerical_values . ")"; 
} 

// Set the column values string. 
$colValues = implode(", ", $colValuesArr); 

// Create the MySQL query. 
$strsql = "INSERT" 
     . " INTO tbl_orders " . $colNames 
     . " VALUES " . $colValues 
     ; 

// Echo the output for testing. 
echo $strsql; 

해당 스크립트의 출력은 :

INSERT INTO tbl_orders (order_id, user_id, price, quantity) VALUES ('testorderid', 'testuserid',7.99, 2) 

EDIT 여기 문자열 유형을 검출하는 gettype를 사용하여 재 작업이다. 더 유연한 & 강력한. 이것은 물론 테스트 데이터를 사용하고 있지만 실제 시나리오에 쉽게 적용 할 수 있어야합니다.

// Test data. 
$orderID = 'testorderid'; 
$userID = 'testuserid'; 
$price = 7.99; 
$quantity = 2; 

// Create an array map based on strings & MySQL DB field values. 
$array_map = array(); 
$array_map['orderID'] = 'order_id'; 
$array_map['userID'] = 'user_id'; 
$array_map['price'] = 'price'; 
$array_map['quantity'] = 'quantity'; 

// Create the text arrays. 
$insertArrText = array(); 
$insertArrNumerical = array(); 

// Set arrays for text and numberical types. 
$text_types = array('string'); 
$numerical_types = array('double','integer'); 

// Lopop through the array map & assign values based on type. 
foreach ($array_map as $array_map_key => $array_map_value) { 
    if (in_array(gettype($$array_map_key), $text_types)) { 
    $insertArrText[0][$array_map_value] = $$array_map_key; 
    } 
    else if (in_array(gettype($$array_map_key), $numerical_types)) { 
    $insertArrNumerical[0][$array_map_value] = $$array_map_key; 
    } 
} 

// Get the array keys & merge them into one combined array. 
$array_keys = array_merge(array_keys($insertArrText[0]), array_keys($insertArrNumerical[0])); 

// Set the column names. 
$colNames = "(" . implode(", ", $array_keys) . ")"; 

// Loop through the '$insertArrText' 
foreach ($insertArrText as $key => $row) { 

    // Set the numerical values. 
    $numerical_values = implode(", ", $insertArrNumerical[$key]); 

    // Set the text values. 
    $text_values = "'" . implode("', '", $row) . "'"; 

    // Set the column values array. 
    $colValuesArr[] = "(" . $text_values . "," . $numerical_values . ")"; 
} 

// Set the column values string. 
$colValues = implode(", ", $colValuesArr); 

// Create the MySQL query. 
$strsql = "INSERT" 
     . " INTO tbl_orders " . $colNames 
     . " VALUES " . $colValues 
     ; 

// Echo the output for testing. 
echo $strsql; 

는 그리고이 코드의 출력은 다음과 같습니다

INSERT INTO tbl_orders (order_id, user_id, price, quantity) VALUES ('testorderid', 'testuserid',7.99, 2) 
+0

특정 용도로만 사용하는 경우 작동 할 수 있습니다. 그러나 필자는 언제든지 사용할 수있는 함수를 만들려고하고 있으며 배열이 다를 때마다 다른 값 형식을 사용하려고합니다. – user2395238

+0

글쎄,'gettype'을 사용하여 값이 문자열인지 정수인지를 결정한 다음 그 값을 기반으로 텍스트 또는 숫자 배열에 배치하는 것은 어떻습니까? – JakeGould

+0

준비된 진술은 어떻게 사용합니까? – user2395238

0

사용 array_map :

$row = array_map(function ($a) { 
    if (is_numeric($a)) return $a; 
    else return "'".$a."'"; 
},$row); 

데이터 안전이 가정, 그렇지 않으면 mysql_real_escape 같은 것을 사용하거나 PDO를 사용하십시오 명령문을 준비했다.

관련 문제