简体   繁体   中英

php & mysql: Proper handling of all types of queries

I would like to make one universal function for database queries. The function I have below works perfectly for SELECT queries. However I would like to have it working properly for INSERT, UPDATE, DROP and other queries not returning anything. Can someone tell me why using mysqli_fetch_all for such queries prints warning? How to properly handle it? How to obtain status of such queries?

function cms_query($sql_query)
{
    // Object returned by mysqli_connect
    global $cms_db;

    // Perform query
    $result = mysqli_query($cms_db, $sql_query);
    if(!$result) {
        print("ERROR\nFAILED_TO_QUERY\n");
        return;
    }

    // Obtain results
    $rows = mysqli_fetch_all($result, MYSQL_ASSOC);
    if(!$rows) {
        print("OK\n0\n0\n");
        return;
    }

    // Print result array keys
    $keys = array_keys($rows[0]);
    print("OK\n" . count($keys) . "\n");
    foreach($keys as $key)
        print($key . "\n");

    // Print result rows
    print(count($rows) . "\n");
    foreach($rows as $row)
        foreach($row as $value)
            print($value . "\n");
}

Well, it's a good idea per se to have such a function, but there is one thing that your function desperately lacking - the support for prepared statements .

So, to make your function work in its current form, it's not a big deal:

function cms_query($sql_query)
{
    // Object returned by mysqli_connect
    global $cms_db;

    // Perform query
    $result = mysqli_query($cms_db, $sql_query);
    if(!$result) {
        trigger_error(mysqli_error($cms_db));
    }

    // if it was a DML query
    if (if $result === true)
    {
        return;
    }

    // Obtain results
    return mysqli_fetch_all($result, MYSQL_ASSOC);
}

but you have to understand that such a function should support prepared statements. And for sake of such a support it's better to use PDO. I wrote such a function, or rather, a PDO wrapper which I strongly recommend for you to consider. Note the Examples part of the article - as you can see, this function can run any kind of query.

From the manual :

mysqli_query

Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.

So, when you do a data modification query (INSERT for example), you get boolean value. When you try to pass it as argument for mysqli_fetch_all() you get an error, because this function expects an instance of mysqli_result class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM