Jump to content

insert quotes


ayok

Recommended Posts

Hi, thanks.

 

I am trying to make a csv importer. And the output "1,john,18,Cancer" is from the csv file. However, when I tried to insert the data into a table, i kept getting mysql error, and the way to fix it is to insert quotes on the data, like " '1','john','18','Cancer' ".

 

Here is my php so far:

$filecontents = file ("testable.csv"); 

for($i=1; $i<sizeof($filecontents); $i++) { 
	$insertrecord = "INSERT INTO ".$tablename." (".$filecontents[0].") VALUES (". $filecontents[$i].")"; 
}

 

If I echo the $insertrecord i got

INSERT INTO testable (id,name,age,zodiac) VALUES (1,john,18,Cancer)

which return mysql error. It works when I changed the values into  '1','john','18','Cancer'.

Link to comment
https://forums.phpfreaks.com/topic/184162-insert-quotes/#findComment-972319
Share on other sites

In the code you originally posted, then removed when you edited the post, you were using implode() to get your current string. All you would need to do is alter the impload() to add single quotes next to the comma and then add some single-quotes to the start and end of the complete string.

 

Since I don't know what variables you were using in your original code, take a look at this -

<?php
$output = "john,18,Cancer";
$together = implode("','",explode(',',$output));
$output = "'$together'";
echo $output;
?>

 

 

Link to comment
https://forums.phpfreaks.com/topic/184162-insert-quotes/#findComment-972346
Share on other sites

I'm confused as to why your wanting to echo a query?

 

The thing with the code you stated, it's hard to change $filecontents[$i] to have ' ' around each string. You'd have to get the strings in that way. If $filecontents[$1] meant "Hello" by doing echo "'". $filecontents[$1] ."'"; should do the trick.

You'd have to show where $filecontents[$1] is defined, which would be where $1 is defined in the file testable.csv I think.

Link to comment
https://forums.phpfreaks.com/topic/184162-insert-quotes/#findComment-974724
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.