0

I am trying to do some sql querying on cvs file in php. I found this

Writing a PHP file to read from CSV and execute SQL Query

but I was unable to change it for the SELECT statement

my attempt:

<?php
$fin = fopen('./file.csv','r') or die('cant open file');
$conn = mysql_connect('localhost', 'name', 'pw');
If (!$conn) {
    die ('Could not connect: ' . mysql_error());
}
@mysql_select_db('name') or die ('Unable to select database');
mysql_query("SET NAMES 'utf8'", $conn);
mysql_query("SET CHARACTER SET 'utf8'", $conn);

echo "Connection succeeded <br />\n";

while (($data=fgetcsv($fin,1000,","))!==FALSE) {
    $query = "SELECT * FROM file";
    $result = mysql_query($query);

    while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
      print_r($row);
    }

    }
fclose($fin);
mysql_close();
?>

lets say I have an file.csv and I want to execute something like this: Select col1,col2 from file.cv where c3='whatever'

OR is there some other, more elegant way how to querying cvs in php?

Thank you!

Community
  • 1
  • 1
user_pruser
  • 422
  • 2
  • 13
  • any reason not to read it in to a db table? –  Dec 16 '15 at 20:11
  • editing csv on the spot is much more convenient for me. – user_pruser Dec 16 '15 at 20:14
  • the query is just select every thing -im really confused what you actually want –  Dec 16 '15 at 20:15
  • Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Dec 16 '15 at 20:17
  • I want to do an regular sql select statement on cvs file in php, like: Select col1,col2 from file.cv where c3='whatever' – user_pruser Dec 16 '15 at 20:18

2 Answers2

0

You cannot query a CSV file with SQL style queries. There are some command line tools available that you might be able to wrap with PHP, but you cannot do it directly.

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
0

as said, not possible. Instead read csv contents into an array and iterate over the array.