Forum Moderators: coopster
I have a database of about 20000 entries both in txt format and CSV format. I want to pull one line from the file based on an ID which is submitted from a previous form, so basically a user types in a code then clicks submit and the codes looks up this ID and displays just the info on that line in a HTML form?
Can this be done?
I want to avoid using a database where possible because of the sheer amount of data in it.
Cheers in advnace.
TonyL
You will be far better off using a database, and taking advantage of proper indexing on your dataset.
To use a text file, Look at PHP's fgetcsv() [uk2.php.net] function. You don't have any easy option but to read the file until you find the row you want.
The reason I would prefer to use either txt or csv is purely for updates sake. Say for arguments sake every friday this list was updated and the only way this list is published was a csv it would be easier just to overwrite the existing file rather than import it in to a DB. Also, I need to create DSNless connection which I have had errors for ever and a day with.
This is my first outing with PHP so I'm not really sure where I am going with to tbh :o)
The PHP is straight forward. I assume that you want an exact match on some field; so assume an incoming variable $match that you have retrieved from a form or whatever.
The following should point you in the right direction:
$match = "SOMEKEY"; // what we're looking for
$index = 0; // the field in which to look for $match, where the first value on a row of comma separated values is at index 0
$fp = fopen("/path/to/data.csv")
while($row = fgetcsv($fp,32768))
{
if ($row[$index] == $match)
{
$found = $row;
break;
}
}fclose($fp);
if (is_array($found))
{
print "found it!";
print_r($found);
}
else
{
print "not found";
}
I have some codewhich accessand displays every line but I really don't know enough to edit this?
Sorry I know I'm a classic newbie. :o)
<?
$fp = fopen("members.csv", "r");
$line_data = file("members.csv");
for($i=1;$i<count($line_data);$i++){
$line_elements = explode("¦", $line_data[$i]);
print trim($line_elements[0]) . '<br />';
print trim($line_elements[1]) . '<br />';
}
fclose($fp);
?>
<?
$match = "002001"; // what we're looking for
$index = 0; // the field in which to look for $match, where the first value on a row of comma separated values is at index 0
$fp = fopen("fads.csv", "r");
$line_data = file("fads.csv");
while($row = fgetcsv($fp,32768))
{
if ($row[$index] == $match)
{
$found = $row;
break;
}
}
fclose($fp);
if (is_array($found))
{
print "found it!";
print_r($found);
}
else
{
print "not found";
}
?>
Returns an Array based on the ID number. How can I split this in to individual elements to populate an HTML form? I have tried:
print_r($found_elements[0]);
to separate out ID number, being the first column in the csv