0

I want to create a function that automatically makes a connection to the database and performs the given queries but I can't get it to work and it gives no errors. I think I'm not outputting in the correct way my goal is to output a array that stores all the returned values from the queries.

Here is my code so far hope you can help:

public function db_query() {
    $ini = parse_ini_file($_SERVER['DOCUMENT_ROOT'] . '/app.ini');
    $mysqli = new mysqli($ini['db_location'], $ini['db_user'], $ini['db_password'], $ini['db_name']);

    // create string of queries separated by ;
    $query = "SELECT name FROM mailbox;";
    $query .= "SELECT port FROM mailbox";

    // execute query - $result is false if the first query failed
    $result = mysqli_multi_query($mysqli, $query);

    if ($result) {
        do {
            // grab the result of the next query
            if (($result = mysqli_store_result($mysqli, 0)) === false && mysqli_error($mysqli) != '') {
                echo "Query failed: " . mysqli_error($mysqli);
                while ($row = $result->fetch_row()) {
                    echo $row[0];
                }
            }
        } while (mysqli_more_results($mysqli) && mysqli_next_result($mysqli)); // while there are more results
    } else {
        echo "First query failed..." . mysqli_error($mysqli);
    }
}

Note: I did not add the parameter for the query just for testing purposes.

3
  • 3
    SELECT name, port FROM mailbox is enough Commented Feb 3, 2020 at 11:47
  • I added multiple queries to 1 table to test the function Commented Feb 3, 2020 at 11:50
  • 1
    Inside your do { loop you are only echoing anything in the case where the store_result operation fails. If it succeeds, nothing is echoed. Commented Feb 3, 2020 at 11:53

1 Answer 1

2
public function db_query($mysqli) {

    $return = [];
    $result = mysqli_query($mysqli, "SELECT name FROM mailbox");
    while ($row = $result->fetch_row()) {
        $return[] = $row[0];
    }
    $result = mysqli_query($mysqli, "SELECT port FROM mailbox");
    while ($row = $result->fetch_row()) {
        $return[] =  $row[0];
    }
    return $return;
}

simple, clean, efficient, always works

Sign up to request clarification or add additional context in comments.

4 Comments

In addition, check the $result before entering the while loop.
No, you should never check the result manually. Configure mysqli to report errors instead
This should have been only one query. Why execute it twice?
@Dharman beause it's only for test

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.