Getting multidimensional array from mysql database

I am currently using Mysqli to fetch data from a Mysql database, the use of the code im hard to understand and as far as I understand, depreciated functions or are depreciated by themselves. If I could get some insight and maybe some updated methods of my Qoal for fetching data from mysql database.

mysqli prepared statements

What I have so far:

$param = 1;
$mysqli = new mysqli("127.0.0.1", "user", "password", "databaseName");
$mysqli->query('SELECT reply_id FROM replies WHERE reply_topic = ? ORDER BY reply_date ASC');
$mysqli->bind_param('i',$param)
$mysqli->execute();
$row = bind_result_array($mysqli);

while($mysqli->fetch()){
    $set[$row['']] = getCopy($row);
}
$mysqli->free_result();
return $set;




function bind_result_array($stmt)
{
    $meta = $stmt->result_metadata();
    $result = array();
    while ($field = $meta->fetch_field())
    {
        $result[$field->name] = NULL;
        $params[] = &$result[$field->name];
    }

    call_user_func_array(array($stmt, 'bind_result'), $params);
    return $result;
}

function getCopy($row)
{
    return array_map(create_function('$a', 'return $a;'), $row);
}

      

+3


source to share


1 answer


First you need to clear the call in the database. $mysqli->query

sent request before parameter binding, etc.

Replace as follows:

$stmt = $mysqli->prepare('SELECT reply_id FROM replies WHERE reply_topic = ? ORDER BY reply_date ASC');
$stmt->bind_param('i',$param)
$stmt->execute();

      

$mysqli->prepare

returns a new object for which you want to bind values ​​and execute them. It avoids SQL injection !

None of this is discounted. mysqli_

is exactly what you should be using.



Since all you need is an array of results, you can use the following code to do this - no custom functions are required.

$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
        $set[] = $row['reply_id'];
}

      

For each row, while

each field is stored in an array with the column name as the key. Thus, $row['reply_id']

contains the value of a column reply_id

in the database. Above, I have stored this value in a named array $set

and when it iterates over the next row of the result, it also stores the next value for that array.

You can manipulate the result before or after saving it to a new array as you see fit.

Hope it helps.

+2


source







All Articles