I'm trying to write a script that would return all the records with same IDs from all tables in the same mysql database as json data.
- Below I'm trying to first get all table names from my local directory (it is because all the tables in my mysql database are created based on all those file names in this directory).
- Next, I'm trying to loop through all files from directory and ping mysql database with select queries
Transform query results into json data.
<?php $db_hostname = 'localhost'; $db_database = ''; $db_username = ''; $db_password = ''; $db_server = mysqli_connect($db_hostname, $db_username,$db_password); if (!$db_server) die("Unable to connect to MySQL:". mysql_error()); mysqli_select_db($db_database) or die("Unable to select database:". mysql_error()); date_default_timezone_set("Europe/Dublin"); // Go to the correct directory $directory= '/path/to/my/data/'; chdir ($directory ) ; // Loop through the file names and remove the .csv extension foreach (glob("*.csv") as $filename) { $filename = substr($filename,0,strlen($filename)-4); echo $filename . "\n"; $counter = $counter + 1; } // If there are no files, exit the script if ( $counter == 0) {exit();} // Now for each filename with no extension run mysql query foreach ($filename as $table_name) { $db_server = mysqli_connect($db_hostname, $db_username,$db_password); mysqli_select_db($db_database) or die("Unable to select database:". mysql_error()); $myQuery = 'SELECT * FROM $table_name WHERE id="1";' } // get results into json $result = mysqli_query($db_server,$myQuery); $data = array(); foreach ($result as $row) { $data[] = $row; } mysqli_close($db_server); echo json_encode($data); ?>