Jump to content

How Can I Store Values On DB?


refiking

Recommended Posts

I'm sure this is simple, but I'm struggling with finding out exactly how to do this.  I have a list of names that I want to add to my database.  In the text file they are listed like this:

 

Name1

Name2

Name3

 

I added this script:

$YourFile = "sql.txt";
$handle = fopen($YourFile, 'r');
$Data = fread($handle, 512);
fclose($handle);
print $Data;

 

And it returns like this:

 

Name1 Name2 Name3 Name4

 

My question is how can I code the script so that everytime there is a space, it adds a record to the db?

Link to comment
https://forums.phpfreaks.com/topic/143146-how-can-i-store-values-on-db/
Share on other sites

lonewolf217 he said the data was in a text file on new lines.  It displaying in a browser as spaces because browsers don't use the \n character. 

 

 

This should work.

 



$YourFile = "sql.txt";
$handle = fopen($YourFile, 'r');
$Data = fread($handle, 512);
fclose($handle);
#make array from each line in the text file.
$str=explode("\n",$Data);
$values = '';
#loop through array to create the values portion of sql
foreach($str as $val)
{
    $values .= '('.$val.'), '
}

#remove the last common.
$values = rtrim($values,',');

#run query
mysql_query('INSERT INTO table (columnName) VALUES '.$values);

To do a cleaner version without the fopen junk, I prefer this method:

 

$YourFile = "sql.txt";
$Data = file($YourFile);

// if it gives you a sql error uncomment this line:
// array_pop($Data);

#remove the last common.
$values = implode("' , '", $Data);

#run query
mysql_query('INSERT INTO table (columnName) VALUES ('.$values . ')');

 

At least I think that's a bit cleaner :)

Some of these are not names, but email addresses as well.  I get this error message when trying to execute this script:

 

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@sbcglobal.net ), (Randall ), (Micheal ), ([email protected]' at line 1

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.