Am I using multi_query() in php wrong?

77 Views Asked by At

I'm trying to get an echo of the column names (except the first column) of a table from my database. I used the code below. In my div I get the echo "Cannot get xValues". So it seems that my query doesn't work from the very start. Note however that it was my first time using multi_query(), so maybe I'm missing something. FYI, if I use msqli_query() (and remove the if statement) and I try to echo all the column names of my table without going through the creation of a temporary table to remove the first column, the code works just fine. I appreciate your assistance on this matter. Thanks

        $query = "CREATE TEMPORARY TABLE temp_tb SELECT * FROM $tableName";
        $query .= "ALTER TABLE temp_tb DROP col1";
        $query .= "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '$dbName' AND TABLE_NAME = 'temp_tb'";
        
        if ($mysqli -> multi_query($query)){
           
            while($row = $query->fetch_assoc()){
                $result1[] = $row;
            }
    
            $columnArr = array_column($result1, 'COLUMN_NAME');
     
            foreach($columnArr as $columnNames){
            $xValues = "'".$columnNames."'".",";
            echo $xValues;
            }
            
        } else{
            echo "Cannot get xValues";
        }
1

There are 1 best solutions below

2
Dharman On

To answer your question: Yes, you are using it wrong. You need to perform a blocking loop after you call multi_query.

You should ask yourself rather this question:

Why am I using multi_query?

To which an answer is that you should not use it at all! In fact you should avoid it like fire.

In your case, the code can be simply written like this:

$mysqli->query("CREATE TEMPORARY TABLE temp_tb SELECT * FROM $tableName");
$mysqli->query("ALTER TABLE temp_tb DROP col1");
$stmt = $mysqli->prepare("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = 'temp_tb'");
$stmt->bind_param('s', $dbName);
$stmt->execute();
$result1 = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

$columnArr = array_column($result1, 'COLUMN_NAME');

foreach($columnArr as $columnNames){
    $xValues = "'".$columnNames."'".",";
    echo $xValues;
}

However, I am afraid that you are trying to solve a completely different problem. I would really encourage you to reconsider whatever problem you are trying to solve, because there is probably a much better way to do it. And as always, I would recommend to use PDO instead of mysqli; it is much simpler.