使用准备好的语句返回布尔值的mysqli子查询

时间:2018-10-27 08:36:01

标签: php mysql mysqli

所以我准备了一个已经可以在mysql(tested in phpmyadmin)中运行的查询,但是我在使用mysqli类获取结果时遇到了问题,因为我认为查询是正确的,所以我很奇怪无法获取结果。谁能在以下代码中指出我的错误。

<?php

include_once __DIR__ . '/includes/init.php';

$sql = 'SELECT 
                    `purchase_order`.`id`, 
                    `purchase_order`.`po_date` AS po_date, 
                    `purchase_order`.`po_number`, 
                    `purchase_order`.`customer_id` AS customer_id , 
                    `customer`.`name` AS customer_name, 
                    `purchase_order`.`status` AS po_status, 
                    `purchase_order_items`.`product_id`, 
                    `purchase_order_items`.`po_item_name`, 
                    `product`.`weight` as product_weight,
                    `product`.`pending` as product_pending,
                    `product`.`company_owner` as company_owner,
                    `purchase_order_items`.`uom`, 
                    `purchase_order_items`.`po_item_type`, 
                    `purchase_order_items`.`order_sequence`, 
                    `purchase_order_items`.`pending_balance`, 
                    `purchase_order_items`.`quantity`, 
                    `purchase_order_items`.`notes`, 
                    `purchase_order_items`.`status` AS po_item_status,
                    `purchase_order_items`.`id` AS po_item_id
                  FROM (SELECT id, po_date, po_number, customer_id, status
            FROM purchase_order  GROUP BY  id   DESC  LIMIT ?, ? ) as purchase_order  
                  INNER JOIN customer ON `customer`.`id` = `purchase_order`.`customer_id`  
                  INNER JOIN purchase_order_items ON `purchase_order_items`.`po_id` = `purchase_order`.`id` 
                  INNER JOIN product ON `purchase_order_items`.`product_id` = `product`.`id` 
                   GROUP BY  id';

$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$statement = $mysqli->prepare($sql);
$statement->execute();
$offset = 0;
$perpage = 10;
$statement->bind_param('ii', $offset, $perpage);
$result = $statement->get_result();
while ($row = $result->fetch_assoc())
{
    echo '<pre>';
    print_r($row);
    echo '</pre>';
}

先谢谢了。

1 个答案:

答案 0 :(得分:0)

您准备/绑定并执行语句和值的顺序不正确...

$statement = $mysqli->prepare($sql);
$offset = 0;
$perpage = 10;
$statement->bind_param('ii', $offset, $perpage);
$statement->execute();

您需要在bind_param()之前使用execute(),以便它知道要使用的值。