HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Function to get rows from database

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
rowsfunctiondatabasegetfrom

Problem

I have a function that returns rows from my database, and it works fine, but I was told that it was poorly written, and there is a lot of unnecessary code in it. I'm wondering if there is a simpler, easier way to rewrite this function.

function gd($query) {

    global $connect;
    $fetch = mysqli_query($connect, $query);
    $count = mysqli_num_rows($fetch);

    while ($row=mysqli_fetch_array($fetch,MYSQLI_NUM)) {

        $count --;
        $arrayCount = count($myArray);

        $tempArrayCount = 0;
        while($tempArrayCount < $arrayCount){
            $array[$count][$tempArrayCount]= $row[$tempArrayCount];
            $tempArrayCount++;
        } //end of while($tempArrayCount < $arrayCount)

    } //end of while ($row=mysqli_fetch_array($fetch,MYSQLI_NUM)) 

    return $array;

} //end of function gd($query)

Solution

Your code will work, of course, but you go to a lot of trouble to grind the result set into an array when that capability is already available. Mysqli would provide the fetch_all() function if you had the mysqlnd drivers available; fortunately, PDO has provided it since PHP 5.1.

You will need to create a PDO connection with

$dsn = "mysql:host=" . $hostname . ";dbname=" . $dbname . ";";
$dbh = new PDO($dsn, $dbuser, $dbpass);


then your function would be

function gd($query)
{
    global $dbh;
    $result = $dbh->query($query);
    $array = $result->fetchAll(PDO::FETCH_NUM);  // fetchAll() does the same as most of your original code
    return $array;
}

Code Snippets

$dsn = "mysql:host=" . $hostname . ";dbname=" . $dbname . ";";
$dbh = new PDO($dsn, $dbuser, $dbpass);
function gd($query)
{
    global $dbh;
    $result = $dbh->query($query);
    $array = $result->fetchAll(PDO::FETCH_NUM);  // fetchAll() does the same as most of your original code
    return $array;
}

Context

StackExchange Code Review Q#113549, answer score: 8

Revisions (0)

No revisions yet.