Hi all

I am importing a CSV file and for each line of the file, I store the cell contents into an array as such:

Array
(
[0] => 6
[1] => 1
[2] => Style black
[3] => style-black
[4] => Test text goes here
[5] => 123
[6] => 201
)

However I am using this line of code to help build my SQL query but I can't seem to get the strings with quotes around them in order for the SQL to work properly:

			for ($i=1; $i<sizeof($filecontents); $i++) {
			  $line 	= trim($filecontents[$i], "\t");
			  $arr 		= explode("\t", $line);
			  $insertquery .= "	(".implode(",", $arr)."), ";
			}

How can I get this to add quotes around the values with strings?

Many Thanks

    You would use something alonge these lines:

    $str = "'" . implode("','", $filecontents) "'";

    Of course, you need to adapt it since you should sanitise the input and leave out the first element.

      It's also possible that your database already has a command for importing CSV directly. If it does it will almost certainly be a lot faster.

        Hi weedpacket

        Could you elaborate further on that point you made?

        How would I know what to look for if the database has such a thing?

        Thanks

          More generally, the DBMS's manual would have a section somewhere on "importing" (and perhaps "CSV"). Searching the manual (perhaps its contents page, or its index if it has one) for pointers to the relevant sections for those terms may reveal something that sounds appropriate.

          Following those pointers and reading the material in those sections may make it clear that it's what you're after or it may turn out not to be, in which case any cross-references the manual provides would be worth checking out, or it's back to the contents and/or index again.

            Write a Reply...