SQLite Forum

Sqlite in PHP import data from a file
Login

Sqlite in PHP import data from a file

(1) By rp (pizzipie) on 2020-03-29 19:57:47 [source]

MySql has LOAD DATA INFILE myDataFile.sql to import data.

Sqlite3 command line has .read myDataFile.sql to import data.

How do you accomplish the same thing utilizing a PHP script?

Thanks for help, R

(2) By Simon Slavin (slavin) on 2020-03-30 09:26:29 in reply to 1 [link] [source]

You write PHP code to do it. Open the file as a text file, read it line by line, executing each line as it is read, close the file when you're done.

Take a look at the example for feof() on this page: https://www.w3schools.com/PHP/php_file_open.asp

In the above, instead of using the PHP echo command, execute the text you read as a SQLite command.

(3) By rp (pizzipie) on 2020-03-30 18:22:14 in reply to 2 [link] [source]

Thanks slavin. I've been thinking about this since last night and was coming to the same conclusion as your answer. Re: your last paragraph (In the above, instead of using the PHP echo command, execute the text you read as a SQLite command) can you give me an example of what you mean here.

My typical use here would be a line from the file like: INSERT INTO rxdata VALUES ('jerry','02/28/2020','123-A','260951528','Asprin',4.50,3)

Thanks,

R

(4) By Simon Slavin (slavin) on 2020-03-30 21:57:33 in reply to 3 [link] [source]

This depends on which PHP interface to SQLite you're using.

I prefer the SQLite3 interface:

https://www.php.net/manual/en/book.sqlite3.php

and if you're using that the simplest code would use SQLite3::exec():

https://www.php.net/manual/en/sqlite3.exec.php

You pass that method a string (in your case the line of text you just read from the file) and it executes it as a SQL command against the database you specify. Again, look at the examples on that page.

What you're doing right now is the same way I first used SQLite for a real application. You're learning three things:

  1. SQL
  2. PHP
  3. The sqlite3 module of PHP

Try to keep them straight. Don't get confused about which of the three the thing you're currently thinking about is part of. The good news is that all three put together are simpler than some programming languages. You already mentioned the sqlite3 shell tool. This is a good way to experiment with SQL commands without worrying about whether it's not working because your PHP code is faulty.

(5) By rp (pizzipie) on 2020-03-31 22:46:35 in reply to 4 [link] [source]

Thanks lots, R