简体   繁体   中英

Getting PDO function to also return the row count

SO I made a function to do my PDO queries for me so I don't have to keep typing it. Here is the function.

if (!function_exists('query_db_select') ) :

function query_db_select($query, $where){
$query_params = array(
':var' => $where
);
    try {
    $stmt = $db->prepare($query);
    $stmt->execute($query_params);
    }
    catch (PDOException $ex){

    }
    $count = $stmt->rowCount();
    if ($count == 1){
    return $stmt->fetch();
    }
    return $stmt->fetchAll();


    }
endif;

So if I use this function it looks like this

$query = query_db_select("SELECT * FROM table WHERE column = :var", $something);

The question is, after I use this function, how can I possible get the row count OUTSIDE of this function? I run the query using the function in another php page, but I want to also get the row count as well as the fetch()

Also want some suggestions on how to make this function better if you got any ideas.

What you are returning is a multi-dimensional array of records. The way you can iterate through the array could change from query to query. One way to return both the row count and the result set would be as follows.

if (!function_exists('query_db_select') ) :

function query_db_select($query, $where){
$returnArray = array();
$query_params = array(
':var' => $where
);
    try {
    $stmt = $db->prepare($query);
    $stmt->execute($query_params);
    }
    catch (PDOException $ex){

    }
    $count = $stmt->rowCount();
    $returnArray['rowcount'] = $count;
    if ($count == 1){
    $returnArray['results'] = $stmt->fetch();
    return $returnArray;
    }
    $returnArray['results'] = $stmt->fetchAll();
    return $returnArray;


    }
endif;

You can later access the number of rows using $returnArray['rowCount'];/* Or whatever your variable is that gets assigned to the return value. */ $returnArray['rowCount'];/* Or whatever your variable is that gets assigned to the return value. */ outside the function call.

I believe you could do something like this:

if (!function_exists('query_db_select') ) :

function query_db_select($query, $where){
$query_params = array(
':var' => $where
);
    try {
    $stmt = $db->prepare($query);
    $stmt->execute($query_params);
    }
    catch (PDOException $ex){

    }
    $myArray = $stmt->fetchAll();
    return array("count" => count($myArray), "elements" => $myArray);


    }
endif;

I see no point in handling the result differently if there is a single element. It is the hotbed of problems.

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