Skip to content Skip to sidebar Skip to footer

Store Mysql Results In Seperate Php Variables

I have a MySQL query that returns 3 random rows whenever it is ran. I want to store each row in an array, with each column of the row a different part of the array. Hopefully Im be

Solution 1:

Try:

$array = Array();

$result = mysql_query("SELECT NAME,AUTHOR,CITY FROM TESTIMONIALS ORDER BY RAND() LIMIT 3");
while ($row = mysql_fetch_array($result)) {
    $array[] = $row;
}

Solution 2:

You can use $row['COLUMNAME'] to get the column value. Note that COLUMNAME will be case-sensitive.

For example:

$result = mysql_query("SELECT NAME,AUTHOR,CITY FROM TESTIMONIALS ORDER BY RAND() LIMIT 3");
while($row = mysql_fetch_array($result)) {
    echo'Name: ' . $row['NAME'] . '<br/>';
    echo'Author: ' . $row['AUTHOR'] . '<br/>';
}

Also, read the big red notice on the php.net manual page: Use of this extension is discouraged. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information.

Solution 3:

Consider using prepared statements as mysql_ is being deprecated. It is also susceptible to SQL injection if you are careless or inexperienced and don't escape your query strings properly.

Here is the solution using mysqli_:

$link = mysqli_connect("localhost", "user", "password", "database") ordie(mysqli_error($link));
$stmt = mysqli_stmt_init($link);
$query = 'SELECT NAME,AUTHOR,CITY FROM TESTIMONIALS ORDER BY RAND() LIMIT 3';
$arrTestimonials = array();   

if (mysqli_stmt_prepare($stmt, $query)) {
    mysqli_stmt_bind_result($stmt, $out_name, $out_author, $out_city);
    mysqli_stmt_execute($stmt);

    while (mysqli_stmt_fetch($stmt)) {
        $arrTestimonials[]['name'] = $out_name;
        $arrTestimonials[]['author'] = $out_author;
        $arrTestimonials[]['city'] = $out_city;
    }
} // error preparing statement 

The array will be structured as follows:

Array
(
    [0] => Array
        (
            [name] => Name 1
            [author] => Author 1
            [city] => City 1
        )

    [1] => Array
        (
            [name] => Name 2
            [author] => Author 2
            [city] => City 2
        )

    [2] => Array
        (
            [name] => Name 3
            [author] => Author 3
            [city] => City 3
        )

)   

Post a Comment for "Store Mysql Results In Seperate Php Variables"