[eluser]RaGe10940[/eluser]
Hi,
Currently I have a script that is used as a back end update kinda script for a database. My friend is working on a website to help women choose clothing and what not. She has around 300 or 400 some arrays and she also needs to store those values in a database.
This is my current code that some what works but needs debugging :
Code:
<?php
//Set our database variables
$host="xxxxxxxxxxxx"; // Host name
$username="xxxxxxxxxxxxx"; // Mysql username
$password="xxxxxxxxxxxxx"; // Mysql password
$db_name="xxxxxxxxxxx"; // Database name
// Connect to database via PHP Data Object
$conn = new PDO("mysql:host=$host;dbname=$db_name;charset=utf8", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$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 ","
var_dump($finSQL); //
$stmt = $conn->prepare($finSQL); // Prepare our finished query
$stmt->execute(); // And then execute this query
?>
Doing a var_dump of $finSQL I get this :
Code:
string(152) "INSERT INTO `product_features` (Colors_All,Colors_Bright_All) VALUES ('Black', 'Black'),('Charcoal', 'Charcoal'),('Silver', 'Silver'),('White', 'White')"
As you notice the columns work just fine and what not, but my issue is in the VALUES() where the value is being duplicated. I have added comments to my code block. Hopefully some one can help me.
Now also the above code is only handling 2 arrays (or 2 columns if you will) How can I dynamically expand on that depending on the amount of arrays she has? (probably around ~350)