PHP – Import CSV to MySQL

The following code snippet can be used to import CSV into MySQL using PHP.

<?php
$delimiter = ',';

$db = new mysqli('localhost', 'username', 'password', 'database');

if (($handle = fopen("import.csv", "r")) !== FALSE) {
	while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
		foreach($data as $i => $content) {
			$data[$i] = $db->real_escape_string($content);
		}
		$db->query("INSERT INTO mytable VALUES('" . implode("','", $data) . "');");
	}
	fclose($handle);
}

?>

A few things to keep in mind:

  • Make sure you change the MySQL login information to your own login information
  • Make sure you change the table name, in this case, mytable, to your own table name.
  • For your CSV (comma separated values) file, the delimiter may not necessarily be a comma. Change the $delimiter variable to the one-character delimiter separating the different fields.
  • This does NOT automatically create a table. You have to manually do that.
  • Every row would be inserted, so you should manually remove the first row if it is just the column names.

Starting Services on Boot with ntsysv on CentOS/RHEL/Fedora

ntsysv allows you to easily specify the scripts/services you want to automatically start on boot. For CentOS and RHEL users, you can easily install ntsysv using yum. This should work on Fedora too, as they are in the same boat as RHEL and CentOS. ntsysv is not available on Debian/Ubuntu natively, so this method of starting services won’t work.

yum install ntsysv

After you have installed it, run the ntsysv command.

ntsysv

You’ll be presented with a window that has a combination of red, blue, and gray.

Use the up/down arrow to navigate the list. Use the spacebar to check/uncheck a service. Use your tab to navigate to ‘Ok’ and ‘Cancel’. This part is mostly self explanatory.

Delete File with Dash/Hyphen in Name Within Linux/Unix

If you have a file named “-file” without the quotes, you would typically delete it using:

rm -rf -file

Except that doesn’t work. My CentOS complained to me with the following message (though not all operating systems may supply this, so this is mainly for those whose OS does not supply this tip):

rm: invalid option -- 'l'
Try `rm ./-file' to remove the file `-file'.
Try `rm --help' for more information.

The suggested tip here works well. Simply running the following command should delete the “-file” file.

rm -rf ./-file

Keep in mind this limitation does not apply only to the rm command, but a large number of commands including touch and others. It is the most annoying for the rm command, since you are trying to remove the file. For these other commands, you would also have to prepend the file name with a ./ in order for this to work.