PDO - 带有绑定参数的执行查询不会产生任何结果?

时间:2014-04-01 21:15:01

标签: php pdo

我正在尝试创建一个随机的PHP数组" fruits"来自数据库。

我正在使用的数据库类:

class Db
{

private static $_instance = null;
private $_pdo;

private function __construct()
{
    try {

        $this->_pdo = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME .'', DB_USER, DB_PASS);
    } catch (PDOException $e) {
        die($e->getMessage());
    }
}

public static function getInstance()
{
    if (!isset(self::$_instance)) {
        self::$_instance = new Db();
    }

    return self::$_instance;
}

public function prepare($sql)
{
    return $this->_pdo->prepare($sql);
}

}

正在使用数据库来获取" fruits"通过使用3个单独的查询来计算和检索" x"来创建给定大小的随机条目的数组。数据库中随机项的数量。

class FruitBasket
{

private $_fruitArray = array(),
        $_inputCode,
        $_db;

public function __construct($input = null)
{
    $this->_inputCode = $input;
    $this->_db = Db::getInstance();
    var_dump($this->_db);
}

public function pickFruit($count)
{
    $doubleCount = $count * 2;//double the count used in calculation with the random number
    $fruitIDs = ''; //the choosen fruits (id's)
    $i = 0;

    //#1 get total count of fruits table
    $sql = "SELECT COUNT(*) FROM `fruits`";

    if ($query = $this->_db->prepare($sql)) {

        if ($query->execute()) {

            $allFruits = $query->fetch(PDO::FETCH_NUM);

        } else {

            print_r("ERROR QUERY DID NOT EXECUTE #1");
        }

    } else {

        print_r("ERROR CHECK SQL SYNTAX #1");
    }

    //#2 calculate random number to pull from all of id's
    $sql = "SELECT id FROM `fruits` WHERE RAND()* ? <  ? ORDER BY RAND() LIMIT 0, ? ";

    if ($query = $this->_db->prepare($sql)) {

        $query->bindParam(1, $allFruits[0], PDO::PARAM_INT);
        $query->bindParam(2, $doubleCount, PDO::PARAM_INT);
        $query->bindParam(3, $count, PDO::PARAM_INT);

        if ($query->execute()) {

            while ($row = $query->fetch(PDO::FETCH_ASSOC)) {

                if ($i == 0) {

                    $fruitIDs .= "'" .  $row['id'] . "'";

                } else {

                    $fruitIDs .= ", '" . $row['id'] . "'";
                }

                $i++;
            }

        } else {

            print_r("ERROR QUERY DID NOT EXECUTE #2");
        }

    } else {

        print_r("ERROR CHECK SQL SYNTAX #2");
    }

    //#3 get the fruits
    $sql="SELECT NAME FROM `fruits` WHERE `id` IN( ? )";

    if ($query = $this->_db->prepare($sql)) {

        $query->bindParam(1, $fruitIDs, PDO::PARAM_STR);

        if ($query->execute()) {

            while ($row = $query->fetch(PDO::FETCH_ASSOC)) {

                $this->_fruitArray[] = $row['name'];
            }

        } else {

            print_r("ERROR QUERY DID NOT EXECUTE #3");
        }

    } else {

        print_r("ERROR CHECK SQL SYNTAX #3");
    }

    return $this->_fruitArray;
}
}

我正在尝试的桌子上有一堆&#34;水果&#34;在其中,表格的结构示例如下:

==================================
| ID | NAME                      |
==================================
| 01 | Apple                     |
==================================

我试图通过使用以下内容来测试这一切:

echo "<pre>";

echo "TESTING FRUIT ARRAY:</br></br>";

$basket = new FruitBasket();

echo"</br></br> PRINT_R: </br></br>";

print_r($basket->pickFruit(10));

echo "</br></br> VARDUMP: </br></br>";

var_dump($basket->pickFruit(10));

sql查询准备和执行正常,我可以做一个准备和绑定的vardump,他们返回TRUE。但是,在最后一个查询中没有返回任何内容。

执行第一个执行$ allFruits的打印语句的查询显示表中的正确总计数。

第二个查询似乎工作正常,字符串$ fruitIDs从表中获取随机ID,我可以回应这一点,并确认确实返回了正确数量的ID。 / p>

问题出现(我认为)第三个问题:

此查询不返回任何内容。就像execute一样,prepare语句在var转储上返回true,但是没有结果!

如果我手动获取从查询#2输出的ID并在mysql中自己运行,那么正确的&#34;水果&#34;姓名被退回。

我是否错误地绑定了变量?我从the PHP manual阅读了这些页面,但显然我做错了。

请帮忙! :)

1 个答案:

答案 0 :(得分:0)

感谢您的常识提供的链接和输入,使用以下内容:

Reference - frequently asked questions about PDO

Can I bind an array to an IN() condition?

我可以通过更改我的查询来解决此问题:

//#2 calculate random number to pull from all of id's
        $sql = "SELECT id FROM `fruits` WHERE RAND()* ? <  ? ORDER BY RAND() LIMIT 0, ? ";

        if ($query = $this->_db->prepare($sql)) {

            $query->bindParam(1, $allFruits[0], PDO::PARAM_INT);
            $query->bindParam(2, $doubleCount, PDO::PARAM_INT);
            $query->bindParam(3, $count, PDO::PARAM_INT);

            if ($query->execute()) {

                while ($row = $query->fetch(PDO::FETCH_ASSOC)) {

                        $fruitIDs[] = $row['id'];
                }

            } else {

                print_r("ERROR QUERY DID NOT EXECUTE #2");                }

        } else {

            print_r("ERROR CHECK SQL SYNTAX #2");
        }

        //#3 get the fruits
        $inQuery = implode(',', array_fill(0, count($fruitIDs), '?'));

        $sql="SELECT NAME FROM `fruits` WHERE `id` IN($inQuery)";

        if ($query = $this->_db->prepare($sql)) {

            if ($query->execute($fruitIDs)) {

                while ($row = $query->fetch(PDO::FETCH_NUM)) {

                     $this->_fruitArray[] = $row[0];
                }

            } else {

                print_r("ERROR QUERY DID NOT EXECUTE #3");
            }

        } else {

            print_r("ERROR CHECK SQL SYNTAX #3");
        }

        return $this->_fruitArray;
    }

我不完全理解绑定参数的安全优势或后果,或者只是将它们包含在实际的execute()中,但是现在查询正在按预期执行,所以感谢您的输入!