Kevin P Patel
Kevin P Patel

Reputation: 45

How to fetch multiple data from database and store in one variable?

I want to fetch multiple row and store in one variable.Here is my function for fetch data.

I want to fetch all row which type is service. and display all data in php.

Get value function

public function getvalue() {
    $db = connectionstart();
    $sql = ("SELECT * FROM user_posts WHERE type='service' LIMIT 3");
    $result = mysql_evaluate($db, $sql);

    connectionclose($db);
    return $result;
}

mysql_evaluate function

function mysql_evaluate($db, $sql) {
    $result = mysql_query($sql, $db) or die(mysql_error());
    if (mysql_num_rows($result) == 0)
        return $default_value;
    else
        return mysql_result($result, 0);
}

Upvotes: 2

Views: 9499

Answers (3)

Ravi Hirani
Ravi Hirani

Reputation: 6539

Write your function as below:-

public function getvalue() {
    $db = connectionstart();
     // No need of bracket here
    $sql = "SELECT * FROM user_posts WHERE type='service' LIMIT 3";
    $result = mysql_query($sql);
    // declare an array
    $data = [];
    if($result){
        // loop
        while($row = mysql_fetch_array($result)) {
                 // store data in an array
                 $data[] = $row; 

         }    
    }

    return $data;
}

Hope it will help you :)

Upvotes: 1

Wilkoklak
Wilkoklak

Reputation: 89

Try this article on w3schools.com, especially the part with $row=$result->fetch_assoc()

Upvotes: 0

Ayaz Ali Shah
Ayaz Ali Shah

Reputation: 3531

You should try with array store technique

//  First Store data in $data
$data = array();
$result = mysql_evaluate($db, $sql, $defaultvalue);
foreach ($result  as $row) {
    $data [] = $row;
}
// Your all data will be store in $data variable
print_r($data);

Upvotes: 0

Related Questions