What are some best practices for handling tab-delimited data in PHP when importing into a database?
Tab-delimited data can be imported into a database in PHP by reading the file line by line, splitting each line into an array using the tab character as a delimiter, and then inserting that data into the database. It's important to properly handle any special characters or escape sequences that may be present in the data to prevent SQL injection attacks.
$file = fopen('data.txt', 'r');
while (($line = fgets($file)) !== false) {
$data = explode("\t", $line);
// Sanitize data before inserting into database
$data = array_map('mysqli_real_escape_string', $data);
// Insert data into database
$query = "INSERT INTO table_name (column1, column2, column3) VALUES ('$data[0]', '$data[1]', '$data[2]')";
mysqli_query($connection, $query);
}
fclose($file);
Keywords
Related Questions
- How can a logout functionality be implemented in PHP using link parameters?
- What are the potential pitfalls of not specifying the correct time zone in PHP?
- What potential pitfalls should be considered when dynamically generating connection parameters, such as server and SSL settings, from database values in PHP?