Search code examples
mysqlarraysredbean

Convert MySQL fetch array query to redbean PHP


I have 2 buttons which execute a post operations and set a hidden variable which is used to set the MySQL query to filter the database according to date

if result = today

    $query = "SELECT  id,customer_name,CAST( `register_date` AS DATE ) AS dateonly,status,
    DATE_FORMAT(book_date, '%m/%d/%y') FROM  table WHERE   book_date 
    BETWEEN (CURDATE() - INTERVAL 1 DAY) AND CURDATE()";


if result = week

    $query = "SELECT  id,customer_name,CAST( `register_date` AS DATE ) AS dateonly,status,
    DATE_FORMAT(book_date, '%m/%d/%y')  FROM    table
    WHERE   book_date BETWEEN (CURDATE() - INTERVAL 7 DAY) AND CURDATE()";

I then want to use something like

$result=mysql_query($query);
while ($mytable=mysql_fetch_array($result))
{
 loop and display all the information in array in a table
}

But I need the red bean equivalent of this.


Solution

  • The easiest way is to just paste the $query inside the sql function:

    $results=R::getAll($query);
    foreach($results as $row){
        echo $row['id'];
    }
    

    The next way is to manually build the query.... which may just make it look sloppier in my opinion:

    $results=R::$f->begin()->select('id, customer_name, CAST( register_date AS DATE ) AS dateonly,status, DATE_FORMAT(book_date, '%m/%d/%y')')->from('table')->where('book_date BETWEEN (CURDATE() - INTERVAL 1 DAY) AND CURDATE())->get();
    

    The final way is to grab results via redbean and handle them manually:

    $results=R::find('table','book_date BETWEEN (CURDATE() - INTERVAL 7 DAY) AND CURDATE()');
    

    Then loop through the results, configuring data along the way in php.