Page 1 of 1

Adding stuff from each line? (Fairly urgent)

Posted: Sat Dec 01, 2007 3:33 am
by Dale
(I've posted this already over on PHPFreaks)

Ok, so I have a massive file of information, now FIND AND REPLACE techniques do not work, so making a PHP script, should. Now I have the information like so (exactly how it is in the file)

Code: Select all

id<br>
name<br>
title<br>
album<br>
year<br>
id<br>
name<br>
title<br>
album<br>
year<br>
id<br>
name<br>
title<br>
album<br>
year<br>
So on and so forth for about 4,500 times. (Obviously the values are set in the text file though). Now I am wondering how will I go about putting it into my database? I know how to insert:

Code: Select all

mysql_query("INSERT INTO listings VALUES('','','','','')");
But not sure how to make my text file do it in the format it is in.

I need to find a solution by midday today at the latest, any ideas please?? :D

Note 1: The <br> tags are in the file.
Note 2: The insert command will insert the information from every 5 lines.


---
I got a reply of:
You can easily modify this to fit what you need.

Code: Select all

<?php

$string ="id<br>
name<br>
title<br>
album<br>
year<br>
id<br>
name<br>
title<br>
album<br>
year<br>
id<br>
name<br>
title<br>
album<br>
year<br>";

$string = explode("<br>", $string);

$x=1;

foreach($string AS $alone){
	echo $alone . " ";
	
		if($x == '5'){
			echo "<br>\n";
			$x=0;
		}
	$x++;
}
?>
Of course, if it's a file. Just change the $string variable to

Code: Select all

$string = file_get_contents('file.txt');
My results were:

Code: Select all

id name title album year 
id name title album year 
id name title album year
And I replied...
But how would I get them into a mysql_query command? I've tried $string[0] and $alone[0]but none have worked.
But nothing since then, anyone got anymore help please?? Thank you. :D

Posted: Sat Dec 01, 2007 8:53 am
by kaszu

Code: Select all

$str = file_get_contents('file.txt');

$arr = explode('<br>', $str);
$rows = count($arr);

//Go through each 5 rows
for($i = 0; $i + 5 < $rows; $i = $i + 5)
{
	$values = array();
	
        //Escape strings and add to array
	for($k = $i; $k < $i + 5; $k++)
		$values[] = mysql_escape_string($arr[$k]);
	
        //Concatanate array
	$values = implode('", "', $values);
	
        //Execute query
	mysql_query('INSERT INTO listings VALUES ("' . $values . '")');
}

Posted: Sat Dec 01, 2007 9:31 am
by RobertGonzalez
Do you want to keep the breaks tags? Are you looking at taking a five line group and making five individual data pieces with them and insert those five data pieces per query? Do you have the run the query by way of the script or do you want to output a query string that you can pump into your database client app and process that way?