Jump to content

I hate textfiles...


Mortekai

Recommended Posts

We have an assignment in school where we will build a small database of movies using a textfile as database and a dropdown list to act as filter.

 

I am not very comfortable with textfiles, probably because I never use them, so I could use a pointer or two.

 

The first thing I did was to use explode to break out the variables from each string and then populate the droplist, which works fine but I need to reduce the variables so they don't show up more then once insread of just picking out the first item of each row...

 

 <form action="$_SERVER['PHP_SELF']" method="post" name="items">
<select name="item_name">
<option selected="selected">Välj Genre:</option>
<?php
$file = 'filmer.txt'; //definierar databaskällan

$handle = @fopen($file, 'r'); //Öppnar filen 
if ($handle) { 
   while (!feof($handle)) {
       $line = fgets($handle, 4096);
       $item = explode(',', $line);

   
       echo '<option value="' . $item[0] . '">' . $item[0] . '</option>' . "\n";
   }
   fclose($handle);
}
?>
</select>
<input type="submit" name="submit" value="Submit" />
</form>

 

What I need to do next is to figure out how to filter the table output depending on the choice in the dropdownlist...

 

I am kind of stomped here and I realise I hate textfiles :)

Link to comment
Share on other sites

Okay, here are a few hints at how I would handle this.

 

1. I would use file() to read the contents of the text file into an array - each line in the file is an element in the array. So, you would want to ensure each line in the file is indeed a separate record.

 

If each record has multiple fields (i.e. title, genre, etc). I would list each record as a tab or comma separated line. You just need to ensure that the delimiter is either not allowed in the data or that it is properly escaped.

 

2. Next I would process each line and explode it into a sub array. So, the array would look something like this:

array(
    0 => array (
        title => "Armageddon",
        year => "1992",
        genre => "Action",
    ),
    0 => array (
        title => "UP",
        year => "2009",
        genre => "Family",
    ),
)

 

Now let's assume the drop-down you need to create is for "genre". Since each record will have a genre and each genre may appear multiple times I would also include a process in step 2 to add the genre to a separate array that just includes 1 entry for each unique genre. When processing each line, you could either test to see if the current genre already exists in the array before adding it [in_array()] or you could just add each genre as each record is processed and then run array_unique() which will remove duplicates.

 

You will now have a multidimensional array with all the movie records from the text file and a second array that has each unique genre. You should be able to extrapolate on the information provided to fit any other needs you have.

Link to comment
Share on other sites

Wow, that's the perfect answer.

 

Use the file() commands to write a .txt file like this

 

<?php

$Thing = array(
databasename1 => array(
	tablename1 => array(
		rownumber => array(
			columnname1 => "Data"
			etc...
			)
		)
	)
)
?>

 

And so on, you get the picture, then just use include "File.txt";

 

And you have your array as $Thing['Databasename']['Tablename'][Rownumber]['ColumnName']

 

Link to comment
Share on other sites

Hmmm...

 

Ok, I am getting closer...I think :)

 

I tried this:

<?php
// Get a file into an array.  
$lines = file('filmer.txt');

// Loop through our array.
foreach ($lines as $line_num => $line) {
    echo "Line #<b>{$line_num}</b> : " . ($line) . "<br />\n";
}

$item = explode(',', $line);

foreach($item as $key => $genre){
echo "$genre[]" . "<br />";
}
?>

 

The output is

Line #0 : Action, Death race, 106, 3, http://www.lovefilm.se/film/50801-Death+Race.do, 2008
Line #1 : Äventyr, Underworld, 116, 4, http://static.lovefilm.se/img/cover/movie/huge/Underworld/23357.jpg, 2003
Line #2 : Action, Death race, 106, 3, http://www.lovefilm.se/film/50801-Death+Race.do, 2008

 

For the first part so that array looks fine.

 

The output for the second part looks like this:

Action
Death race
106
3
http://www.lovefilm.se/film/50801-Death+Race.do
2008

 

Am I on the right track so far?

Link to comment
Share on other sites

 

<?php

$Thing = array(
databasename1 => array(
	tablename1 => array(
		rownumber => array(
			columnname1 => "Data"
			etc...
			)
		)
	)
)
?>

 

 

And you have your array as $Thing['Databasename']['Tablename'][Rownumber]['ColumnName']

 

That looks neat, could you elaborate a bit? Remember I am a newbie with sleepdepravation here ;)

Link to comment
Share on other sites

Right. Basically you want to write a php file that just created an array called thing, with the first dimension holding Database names, the second dimension holding tablenames, the third dimension holding row numbers and the last dimension holding column names in that row. Then you rename that php file to .txt and include it. So say this is my Database.txt

 

<?php

$Thing = array
(
Somedatabase => array
	(
	users => array
		(
		0 => array
			(
			username => "Garethp"
			password => "Some password"
			)

		1 => array 
			(
			username => "Mortekai"
			password => "Some other password"
			)

		)
	)
)
?>

 

Then my code to use the database would be

 

<?php

include "Database.txt";

for($i=0; $i < count($Thing['Somedatabase']['users']);$i++)
{
echo $Thing['Somedatabase']['users'][$i]['username'] . "'s password is " . $Thing['Somedatabase']['users'][$i]['password'] . "<br>";
}

?>

 

Which would then loop through all users and display their username and password or if you just wanted to call the first row you'd use

 

$Thing['Somedatabase']['users'][0]['username']

 

Get it?

 

You'd write to the file like so

 

$Datatowrite = "<?php ";
$Datatowrite = print_r($Thing);
$Datatowrite = "?>";

 

And then write that to Database.txt

Link to comment
Share on other sites

So you are basicly building the database structure in the ,txt file instead of converting a comma separated...It's an interesting thought, but I think that I need to figure this one out as I think we will surely poke with CSV files later on and then I need to grasp this :)

 

I appreciate the very clever solution though!

Link to comment
Share on other sites

Try this

 

<?php
// Get a file into an array.  
$lines = file('filmer.txt');

// Loop through our array.
foreach ($lines as $line_num => $line) 
{
$item = explode(',', $line);

$Name = $item[1];

$Movie[$Name]['Genre'] = $item[0];
$Movie[$Name]['ThirdItem'] = $item[2];
$Movie[$Name]['FourthItem'] = $item[3];
$Movie[$Name]['File'] = $item[4];
$Movie[$Name]['Year'] = $item[5];
}
?>

 

What it does is it looks through each line, and then it takes that line and explodes it with "," and then assigns it to $Movie['MovieName'] with the values being part of the array created by the ","s. You get it?

Link to comment
Share on other sites

Bah...see how easy that was? I feel like an idiot :)

 

Ok, now I have extracted the rows as string using file() and exploded them into subarrays.

 

Do I now need to make a new array for the genre, or can I use the one I have already?

Link to comment
Share on other sites

Use this

 

<?php
// Get a file into an array.  
$lines = file('filmer.txt');

// Loop through our array.
foreach ($lines as $line_num => $line) 
   {
   $item = explode(',', $line);

   $Name = $item[1];
   $Genre = $item[0];

   $Movie[$Name]['Genre'] = $item[0];
   $Movie[$Name]['ThirdItem'] = $item[2];
   $Movie[$Name]['FourthItem'] = $item[3];
   $Movie[$Name]['File'] = $item[4];
   $Movie[$Name]['Year'] = $item[5];

   $GenreStore['$Genre'] = 1;
   }

foreach ($GenreStore as $Key => $Value)
   {
   echo $Key . "<br>";
   }
?>

 

See, what I did was store the Genres in $GenreStore. By putting them as Keys instead of Values, it's automatically unique

Link to comment
Share on other sites

See, what I did was store the Genres in $GenreStore. By putting them as Keys instead of Values, it's automatically unique

 

Well, it works, but I think storing data as keys is kind of counterproductive. I would just do this:

<?php
// Get a file into an array.  
$lines = file('filmer.txt');

// Loop through our array.
foreach ($lines as => $data) 
{
    //Explode the data line into an array based on commas
    $item = explode(',', $line);

    //Add values to movie array
    $movie[$name]['Genre'] = trim($item[0]);
    $movie[$name]['ThirdItem'] = trim($item[2]);
    $movie[$name]['FourthItem'] = trim($item[3]);
    $movie[$name]['File'] = trim($item[4]);
    $movie[$name]['Year'] = trim($item[5]);

    //Add genre to grenre list
    $genres[] = trim($item[0]);;
}

//remove duplicates from genre list
$genres = array_unique($genres);

?>

 

 

Link to comment
Share on other sites

Elegant and nice :)

 

You make this look so easy :)

 

So what you did was explode out in subarrays and then add the genres array and add item 0 from each array into it? I also notice you used trim, is that to get rid of whitespace and linebreaks?

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.