0

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.

  1. 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).
  2. Next, I'm trying to loop through all files from directory and ping mysql database with select queries
  3. 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);
    
       ?> 
    
Baobab1988
  • 685
  • 13
  • 33
  • What language is this? – Dharman Feb 03 '20 at 16:07
  • @Dharman, First part is actually part of my shell script while the other is regular php script. I added this to demonstrate what I’m looking for in terms of getting all my file names with no extensions in a loop so then I could run multiple queries and get results from MySQL. Would you be able to help? Thanks! – Baobab1988 Feb 03 '20 at 16:23
  • edited my code to be 100% php. However it gives me only an empty page when I run this on my server. Any ideas? – Baobab1988 Feb 03 '20 at 19:13
  • This code has plenty of problems. See [mysqli_fetch_assoc() expects parameter / Call to a member function bind_param() errors. How to get the actual mysql error and fix it?](https://stackoverflow.com/q/22662488/1839439) I would recommend to use PDO instead of mysqli. It looks like you copied some extremely bad example from the internet. Don't use it – Dharman Feb 03 '20 at 19:47

0 Answers0