-2

How to prepare csv file so I could use it for running queries.. Do you have any ideas or maybe links that could be helpful I have mysql database and i run certain sql query on this database lets say "select * from some_database where id=1", and thats everything clear and ok, but, now, i export csv from database and i want to open in and read with php and to sort datas similar as in mysql query. Can someone help me and give me some ideas, points in what way to go

  • Possible duplicate of [How to import CSV file to MySQL table](https://stackoverflow.com/questions/3635166/how-to-import-csv-file-to-mysql-table) – Calimero Sep 23 '17 at 19:39
  • What kind of 'queries' are you thinking of? – KIKO Software Sep 23 '17 at 19:40
  • @Calimero I dont think my question is duplicatedet because I want to imort already prepared csv*(generated from database) and than run some queries using php script – Milica Pavlovic Sep 23 '17 at 20:27
  • I have mysql database and i run certain sql query on this database lets say "select * from some_database where id=1", and thats everything clear and ok, but, now, i export csv from database and i want to open in and read with php and to sort datas similar as in mysql query – Milica Pavlovic Sep 23 '17 at 20:28
  • you should perform your queries against the database then, it's a lot easier. – Calimero Sep 23 '17 at 20:30

1 Answers1

0
<?php

$csv =<<<CSV
23, Foo, Bar, foo@example.com
47, Baz, Qux, baz@example.com
CSV;

$items = explode("\n", $csv);
$items = array_map('str_getcsv', $items);

$get_by_id = function ($id) use ($items) {
    foreach($items as $item)
        if($item[0] == $id)
            return $item;
};

var_export($get_by_id('47'));

Output:

array (
  0 => '47',
  1 => ' Baz',
  2 => ' Qux',
  3 => ' baz@example.com',
)
Progrock
  • 7,373
  • 1
  • 19
  • 25