Currently working on a service script with a friend. When I say service script I mean it will only be used for updating and adding values to the database. Now my friend has stored all her soon to be values of the database as arrays.
I have already succeeded at entering in one of the arrays now I am confused on how I could do it for multiple arrays. So all in all this is more of a question on how I can refactor my
current code to be more dynamic.
Also please keep in mind, she has hundreds of arrays that this needs to be done to so its not like 2 or 3 its literally hundreds.
My updated code : (please read the comments)
$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 ","
Also I know am not binding parameters, I will once I get the actual hard stuff out the way.
Now when doing a dump of $finSQL I get this :
string(152) "INSERT INTO `product_features` (Colors_All,Colors_Bright_All) VALUES ('Black', 'Black'),('Charcoal', 'Charcoal'),('Silver', 'Silver'),('White', 'White')"
How can I have the unique values be the VALUES in my insert query? That is the last part of this that is confusing me.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…