多个数组 - 将值插入数据库

时间:2013-04-20 04:57:34

标签: php mysql arrays pdo foreach

目前正与朋友一起处理服务脚本。当我说服务脚本时,我的意思是它只会用于更新和向数据库添加值。现在,我的朋友很快将她所有的数据存储为数组。

我已经成功进入其中一个阵列现在我对如何为多个阵列进行操作感到困惑。总而言之,这更像是一个关于如何重构我的问题 当前代码更具动态性。

另外请记住,她有数百个需要完成的阵列,所以它不像2或3那样几百个。

我的更新代码:(请阅读评论)

$colors['Colors_All'] = array("Black","Charcoal"); // Add unique indexes
$colors['Colors_Bright_All'] = array("Silver","White"); // Add unique indexes

$AllArrays = get_defined_vars(); // Get all defined vars
$Arrays = array(); // Set a default array

foreach ($AllArrays as $varName => $value) { // Run through all the variables set in AllArrays
        if(is_array($value) && $varName == 'colors') { // If array is colors then
                $Arrays = array_merge($Arrays, $value); // Merge those arrays into the new array
        }
}

var_dump($Arrays);

$sql = "INSERT INTO `product_features` ("; // Create the initial query

foreach ($Arrays as $column => $value) { // ForEach over the array
        $sql .= "$column,"; // Use the Key Example : 'Colors_All and Color_Bright_All' as a column name
}

$sql2 = rtrim($sql, ","); // trim the initial "," from the columns at the end
$sql2 .= ")"; // Close off the columns names
$sql2 .= " VALUES ";

foreach ($Arrays as $column => $value) { // This is where the problem starts -_-
        foreach ($value as $key => $insert) { // Get the value
                $sql2 .= "('$insert', '$insert'),"; // I need to have unique values here :(
        }
}

$finSQL = rtrim($sql2, ","); // Strip off the remaining ","

此外,我知道我没有绑定参数,一旦我得到实际的硬件,我将会一路走来。

现在在进行$ finSQL的转储时,我得到了这个:

string(152) "INSERT INTO `product_features` (Colors_All,Colors_Bright_All) VALUES ('Black', 'Black'),('Charcoal', 'Charcoal'),('Silver', 'Silver'),('White', 'White')"

如何在插入查询中将唯一值作为VALUES?这是令我困惑的最后一部分。

6 个答案:

答案 0 :(得分:1)

将$ Colors_Bright_All,$ Colors_Light_All放入一个最终数组中,让我们说$ finalArray并使用foreach循环遍历该数组,然后执行现有的foreach循环。

答案 1 :(得分:0)

作为上述问题的解决方案,请尝试执行以下代码段

E.g。

    $finalarray=array();

    $Colors_Bright_All =    array("Silver","White","Gold","Royal_Blue","Dodger_Blue","Deep_Sky_Blue","Deep_Green","Forest_Green","Bright_Green","Violet"); 

   $Colors_Light_All = array("Light_Gray","Silver","White","Gold","Dodger_Blue","Deep_Sky_Blue","Light_Blue","Bright_Green","LightGreen","Light_Green");

 array_push($finalarray,'('.join(',',$Colors_Bright_All).')');
 array_push($finalarray,'('.join(',',$Colors_Light_All).')');

  $value=join(',',$finalarray);

 $sql = "INSERT INTO `product_features` (Colors_All) VALUES ".$value; // Build the initial query 
 $finSQL = rtrim($sql, ","); // Strip the last , so our mysql query doesn't goof up. 
 $stmt = $conn->prepare($finSQL);
 $stmt->execute();

答案 2 :(得分:0)

正如你已经在其他答案中被告知的那样,制作嵌套数组是唯一理智的方式

$colors['bright'] = array("Silver","White","Gold"...); 
$colors['light']  = array("Light_Gray","Silver","White"...);

foreach ($colors as $type => $array) {

     // put your code here

}

如果您需要在$type旁边插入更多数据(因为无法从极其模糊的问题中说出),您可以添加一个包含此数据的数组

答案 3 :(得分:0)

我通过序列化每个数组并使用实际的数组索引作为数据库中的唯一标识符来完成“完成”,如下所示:

<?php
ini_set("error_reporting", E_ALL);
ini_set("display_errors", TRUE);

$conn = new MysqlI("HOST", "USER", "PASSWORD", "DATABASE" /*Optionally put the PORT NUMBER HERE : , 3306 */);    
$conn->set_charset('utf8'); // Always explicitly state the character encoding!

$clearSQL = "TRUNCATE TABLE `product_features`;";
$clearNOW = $conn->prepare($clearSQL);// For updating this will delete all records in the table
$clearNOW->execute();

$colors['Colors_All'] = array("Black", "Charcoal", "Pink", "Cheese", "Dog", "Punk"); // Add unique indexes
$colors['Colors_Bright'] = array("Silver", "White", "Yellow", "Blue", "Indigo"); // Add unique indexes
$colors['Colors_Bright_All'] = array("Silver", "White", "DarkYellow", "Dark_Pink",); // Add unique indexes
$colors['Colors_Dark'] = array("Silver", "White", "DarkWE", "DarkCheese", "DarkBla"); // Add unique indexes
$colors['Colors'] = array("Silver", "White", "DarkIDK", "DarKsome", "waDark", "dark"); // Add unique indexes
$colors['Colors_Green'] = array("Silver", "White", "WAA", "WIWIW", "OMG", "Blood"); // Add unique indexes
$colors['Colors_Red'] = array("Silver", "White", "IRI", "owow", "Darkness", "night"); // Add unique indexes

$AllArrays = get_defined_vars(); // Get all defined vars
$Arrays = array(); // Set a default array

foreach ($AllArrays as $varName => $value) { // Run through all the variables set in AllArrays
    if (is_array($value) && $varName == 'colors') { // If array is colors then
       $Arrays = array_merge($Arrays, $value); // Merge those arrays into the new array
    }
}

$sql = "INSERT INTO `product_features` (`ArrayIndex`, `ArrayValues`) VALUES "; // Create the initial query

foreach ($Arrays as $ArrayIndex => $Arrayvalues) { // ForEach over the array
     $sql .= "('$ArrayIndex','" . $mysqli->mysqli_real_escape_string(serialize($Arrayvalues)) . "'),"; // Use Array Index as the Unique Array Identifyer and Arrayvalues for the value
}

$finSQL = rtrim($sql, ","); // Strip off the remaining ","

var_dump($finSQL); // Check the query

$INSERT = $conn->prepare($finSQL); // Get query ready
$INSERT->execute(); // Execute

?>

数据库中的结果是this

答案 4 :(得分:0)

如果您的代码正常,请更改

foreach ($Arrays as $column => $value) { // This is where the problem starts -_-
        foreach ($value as $key => $insert) { // Get the value
                $sql2 .= "('$insert', '$insert'),"; // I need to have unique values here :(
        }
}

foreach ($Arrays as $column => $value) { // The problem will be fixed :D
        $sql2 .="(";
        foreach ($value as $key => $insert) { // Get the value
                $sql2 .= "'$insert',"; // You will have unique values here :D
        }
        $sql2 = chop($sql2,","); // strip the ending ,
        $sql2 .= "),";
}

答案 5 :(得分:-1)

<?php
function myInsert($myArray)
{
    $colour_value = "";
    $stmt = $mysqli->prepare("INSERT INTO `product_features` (Colors_All) VALUES (?)");

    if ($stmt) {
        $stmt->bind_param("s", $colour_value );


        foreach ($myArrayas AS $value) {
            $colour_value = $value;
            $stmt->execute();
        }

        $stmt->close();
    }
}


function myInsert($Colors_Bright_All);
function myInsert($Colors_Light_All);
?>

修改

<?php
$newArray = array();

foreach( $_GLOBALS as $val )
{
    if( substr($val, 0, 7) == "Colors_" )
        myInsert($val);
}

?>