Domanda

I'm creating a flatfile database, in one of my functions that I use to add fields to a pre-existing table, I use file() to get the table, the first line is always contains the fields of the table so I can easily just append the new field to the pre-existing fields

public function addFields($table_fields) {
    // Make sure he opened a connection to the table
    if(empty($this->table_name)) throw new Exception('There is no connection to a table opened.');

    // Make sure table_fields is an array
    if(is_array($table_fields) === FALSE) throw new Exception('TABLE_FIELDS must be an array');

    // Build the data
    $table_data = file($this->table_name);
    $table_header = $table_data[0].self::$field_deliemeter;
    $table_header .= implode(self::$field_deliemeter, $table_fields);
    $table_data[0] = $table_header;
    // Put the data in the table
    file_put_contents($this->table_name, implode(self::$linebreak, $table_data));
    }
}

The problem is that, after adding the fieldname to the pre-existing fieldnames using this

    $table_data = file($this->table_name);
    $table_header = $table_data[0].self::$field_deliemeter;
    $table_header .= implode(self::$field_deliemeter, $table_fields);
    $table_data[0] = $table_header;

The first index which is 0 seems to contain a linebreak, even though file() is supposed to remove that since file implodes by linebreaks

so for example, if my table was

Name    Email   Password    IP  Login_Date
somename    someemail   123 123 123

Then after running the class by doing this

$db = new FlatDB;
$fields = array("Last_Click");
$db->openTable('Test');
$db->addFields($fields);

It becomes this

Name    Email   Password    IP  Login_Date
    Last_Click
Ali ali-trixx@live.com  123 123 123

As you see, it is adding a random linebreak after the first line and I have no idea why is it doing so since file() is supposed to remove linebreaks

Note: $field_deliemeter is "\t"

Does anyone have any idea why is it doing this?

By running a print_r($table_data) before inserting, I get this

Array ( [0] => Name Email   Password    IP  Login_Date Last_Click [1] => somename   someemail   123 123 123 )
È stato utile?

Soluzione

"why is it doing so since file() is supposed to remove linebreaks"?

Only if you use FILE_IGNORE_NEW_LINES. Check file():

$table_data = file($this->table_name, FILE_IGNORE_NEW_LINES);

Returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. Upon failure, file() returns FALSE.

Note: Each line in the resulting array will include the line ending, unless FILE_IGNORE_NEW_LINES is used, so you still need to use rtrim() if you do not want the line ending present.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top