Jump to content

novice using fgetcsv


kristinac

Recommended Posts

I am a web designer/PHP hack trying to solve a problem for our HR department. We have a quarterly newsletter in a Wordpress site I developed and they want to have a dynamically updated service anniversary page updated through excel. The solution to this problem is clearly fgetcsv, but I'm having trouble understanding how to implement it within the wordpress page.

 

Here is a really nice function from the php manual page

 

<?php
function csv_file_to_mysql_table($source_file, $target_table, $max_line_length=10000) {
    if (($handle = fopen("$source_file", "r")) !== FALSE) {
        $columns = fgetcsv($handle, $max_line_length, ",");
        foreach ($columns as &$column) {
            $column = str_replace(".","",$column);
        }
        $insert_query_prefix = "INSERT INTO $target_table (".join(",",$columns).")\nVALUES";
        while (($data = fgetcsv($handle, $max_line_length, ",")) !== FALSE) {
            while (count($data)<count($columns))
                array_push($data, NULL);
            $query = "$insert_query_prefix (".join(",",quote_all_array($data)).");";
            mysql_query($query);
        }
        fclose($handle);
    }
}

function quote_all_array($values) {
    foreach ($values as $key=>$value)
        if (is_array($value))
            $values[$key] = quote_all_array($value);
        else
            $values[$key] = quote_all($value);
    return $values;
}

function quote_all($value) {
    if (is_null($value))
        return "NULL";

    $value = "'" . mysql_real_escape_string($value) . "'";
    return $value;
}
?> 

 

But this leaves me with a few questions:

1. is this both function AND query? or do i need extra code to run the function and spit out the results?

2. where do i input my actual values?

3. does this have to mirror a mysql table somewhere else? i feel like i'm missing a crucial piece of info here.

 

the path to the csv file needs to be absolute, due to HR needing to manage the file themselves without the help of yours truly. the intended output will look like this:

 

5 YEARS

FirstName1 LastName1, FirstName2 LastName2, FirstName3 LastName3, etc

 

6 YEARS

FirstName1 LastName1, FirstName2 LastName2, FirstName3 LastName3, etc

 

and so on. so in addition to the FirstName, LastName and Year columns, the loop will need to include a conditional statement. something like:

 

<h1>5 YEAR</h1>
<ul>
<?php 
     if (quote_all_array(5) ) : ?>
          echo "<li>(FirstName, LastName), </li>";
<?php endif; ?> 
</ul> 

<h1>6 YEAR</h1>
<ul>
<?php 
     if (quote_all_array(6) ) : ?>
          echo "<li>(FirstName, LastName), </li>";
<?php endif; ?>
</ul> 

 

I'm sure my syntax is horribly wrong because I have virtually no idea what I'm doing. Which is why I'm asking you all for help :)

 

to help my understanding i'll supply a set of variables:

 

CSV Source: http://resource.mysite.com/anny.csv

Table Columns: FirstName, LastName, Year

External MySql database (should it apply): AnnySql

 

Thanks in advance for any help. I'm over my pay grade on this one.

Link to comment
Share on other sites

The problem is that you will have to know the exact CSV format.  Is there any way you could give a sample CSV file.  This way we could see if the first line contains column names, etc.

 

Given that, I would be glad to help you out.

Link to comment
Share on other sites

Try this:

<?php

function csv_file_to_mysql_table($source_file, $target_table, $max_line_length=10000) {
    if (($handle = fopen($source_file, "r")) !== FALSE) {
        $columns = fgetcsv($handle, $max_line_length, ",");
        foreach ($columns as &$column) {
            $column = str_replace(".","",$column);
        }
        while (($data = fgetcsv($handle, $max_line_length, ",")) !== FALSE) {
            while(count($data) < count($columns)) {
			array_push($data, NULL);
		}
		$c = count($data);
		for($i = 0; $i < $c; $i++) {
			$data[$i] = "'{$data[$i]}'";
		}
		$sql[] = '(' . implode(',',$data) . ')';
        }
	fclose($handle);
	$query = "INSERT INTO $target_table (".implode(",",$columns).")VALUES " . implode(',',$sql) . "\n";
	mysql_query($query) or trigger_error(mysql_error());		
    }
} 

$file = 'test.csv'; //path name to your CSV file;
$table = 'test'; //name of your database table.  **NOTE *** column names must match EXACTLY.

csv_file_to_mysql_table($file,$table); //calling the function.

?>

 

If nothing shows up in your database table, let me know.  This should work if the file is less than ~1,000 rows.

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.