Hi,
I need to insert the contents of a CSV file into a table, however need to give users the ability to also insert an array of “Authors”. I have managed to get the first bit working where it simply inserts the contents into a table like so:
public function InsertCSVFileToDB(){
$has_title_row = true;
$not_done = array();
if(is_uploaded_file($_FILES['csvfile']['tmp_name'])){
$filename = basename($_FILES['csvfile']['name']);
if(substr($filename, -3) == 'csv'){
$tmpfile = $_FILES['csvfile']['tmp_name'];
if (($fh = fopen($tmpfile, "r")) !== FALSE) {
$i = 0;
while (($items = fgetcsv($fh, 10000, ",")) !== FALSE) {
if($has_title_row === true && $i == 0){ // skip the first row if there is a tile row in CSV file
$i++;
continue;
}
$sql = "INSERT INTO ConfPaper SET
CPRid = ".$items[0].",
Pid = ".$items[1].",
CPtitle = '".mysql_real_escape_string($items[2])."',
CPabstract = '".mysql_real_escape_string($items[3])."',
CPspage = ".mysql_real_escape_string($items[4]).",
CPepage = ".mysql_real_escape_string($items[5]).",
CPfile = '".mysql_real_escape_string($items[6])."',
CPlastedited = now(),
CPUid = ".$_SESSION['Uid']."";
//die($sql);
if(!mysql_query($sql)){
$not_done[] = $items;
}
$i++;
}
}
// if there are any not done records found:
if(!empty($not_done)){
echo "<strong>There are some records could not be inserted</strong><br />";
print_r($not_done);
}
}
else{
die('Invalid file format uploaded. Please upload CSV.');
}
}
else{
die('Please upload a CSV file.');
}
}
But if you look at my csv file here…
You will notice “Author” in the last few columns. What i need to do is insert these into a separate table. When i do this manually i have the following code:
public function insertAuthor($authArray, $PCorder=0)
{
$query = sprintf('SELECT Pid, Pname FROM People WHERE Pname IN(\\'%s\\') ORDER BY Pid ASC', implode('\\',\\'', $authArray));
$result = mysql_query($query);
$maxquery = "SELECT MAX(CPid) as max FROM ConfPaper WHERE CPRid = ".$_GET['CPRid'];
$maxresult = mysql_query($maxquery);
$max = mysql_fetch_array($maxresult);
$CPid = $max['max'];
if($result && mysql_num_rows($result) > 0)
{
$sqlValues = array();
while(list($PId, $PName) = mysql_fetch_row($result))
{
if(in_array($PName, $authArray))
{
$sqlValues[] = sprintf("(%d, 1, ".$CPid.", %d, now(), 0)", $PId
, $PCorder++ );
// Author already exists within the Pname table
// remove user from $authArray
$key = array_search($PName, $authArray);
unset($authArray[$key]);
}
}
$sql = "INSERT INTO PeopleCon(Person_id, PCHid, Pid, PCorder, PCdateadded, PCdeleted) VALUES \
";
$sql .= implode(",\
", $sqlValues);
$result = mysql_query($sql);
}
// If there are Authors left within the $authArray
// Add them to the Pname table
if(count($authArray) > 0)
{
People::insertPersons($authArray); // call insertPersons method for remaining authors
$this->insertAuthor($authArray, $PCorder); // insert the remaining auhtors into PeopleCon
}
}
Now how can i apply this to the CSV method?
Can anyone help…
Thanks