简体   繁体   中英

Get data from table with CakePHP 2

What I have :

I have a table named Sales and 3 colums named Seller , Buyer and Price .

In the controller, I have a function myview() where I do this SQL Query :

SELECT SUM(price) AS total, seller_name, buyer_name
FROM sales
GROUP BY seller_name, buyer_name

The function :

public function myview() {
$this->set('mysales', $this->Sales->find('all', 
  array(
     'fields' => array('SUM(price) AS total','seller_name','buyer_name'),
     'group' => array('seller_name','buyer_name')
  )
));
    }

I display the results in myview.ctp :

<table>
    <tr>
        <th>Seller</th> 
        <th>Buyer</th> 
        <th>Total</th>
        <th>PDF</th>
    </tr>

<?php

    foreach ($mysales as $thesales)
    {
    ?>
    <tr>       
        <td><?php echo $thesales['Sales']['seller_name']; ?></td> 
        <td><?php echo $thesales['Sales']['buyer_name']; ?></td> 
        <td><?php echo $thesales[0]['total']; ?></td>
        <td><input type="button" onclick="location.href='myview_pdf';" value="PDF"/></td>
    </tr>
</table>

<?php
    }
        echo $this->Js->writeBuffer();
?>

The PDF button brings you to another view named myview_pdf where it displays (for now) a blank PDF.

What I want :

When you click on the PDF button, it "recognizes" the 'seller_name' and the 'buyer_name' of the line where I clicked the button so I can do this SQL query :

SELECT price, seller_name, buyer_name
FROM sales
GROUP BY seller_name, buyer_name

And display the results into the myview_pdf.ctp

Problem :

I'm struggling : how do I know which line I clicked, how do I fetch the datas from the line, where do I write the SQL query, how do I pass the query results into myview_pdf.ctp...

Thanks for your help!

You need to make this a link first instead of a button, and pass the seller and buyer names as query strings.

<td>
 <!-- <input type="button" onclick="location.href='myview_pdf';" value="PDF"/> --> <!-- Remove this -->
 <?php echo $this->Html->link("PDF", array(
    "controller" => "<controller name>",
    "action"     => "myview_pdf",
    "?" => array(
       "seller_name" => $thesales['Sales']['seller_name'];,
       "buyer_name" => $thesales['Sales']['buyer_name'];,
    )
 )); ?>

And then in your controller, you can access the seller and buyer name from query string:

public function myview_pdf() {
     $seller_name = $this->request->query("seller_name");
     $buyer_name  = $this->request->query("buyer_name");
     /* Other code */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM