I am trying to write a function that will insert data into a MySQL table like this:
for ($i = 0; $i < $num; $i++){
if ($header[$i] == $user_table_property->name) {
$import = "
INSERT into testing (
$header[$i]
) values (
'$data[$i]'
)";
}
}
If I have something like this, it will just insert first data into first column, can I know what should I change or add? I Googled some examples and edited it myself, but it's still not working.
Here is the longer part of the codes.
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "<br></h1>";
echo "<h2>Displaying contents:</h2>";
readfile($_FILES['filename']['tmp_name']);
echo "<br>";
echo $headers;
}
$handle = fopen($_FILES['filename']['tmp_name'], "r");
$header = fgetcsv($handle);
while(! feof($handle)){
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
mysql_select_db("EMC", $db);
$sql = "SELECT * from CSVtest";
$result = mysql_query($sql,$db);
while ($user_table_property = mysql_fetch_field($result))
{
for($i=0; $i<$num; $i++){
if($header[$i] == $user_table_property->name )
{
$import = "insert into CSVtest ( `" . $header[$i] . "`) values ('" . $data[$i] . "')";
}
}
mysql_query($import) or die(mysql_error()) ;
}
}
}
fclose($handle);
print "Import done";
userid,aaa,aku,pwk, etc., with each representing a new row with one column?LOAD DATA INFILEin MySQL?LOAD DATA INFILEwon't work for some reason) is turn CSV file row data into a$columnsand$valuesarrays as you read in the file, checking and adding to each array a confirmed header and it's row contents as necessary. Then using those two arrays, createINSERTstatements per row by iterating over$values, then do themysql_query($import). You have to turn your current table-layout CSV format into arrays that can be iterated over without losing the referential integrity of each row and column, though.