使用预准备陈述不显示任何内容

时间:2015-02-20 16:41:55

标签: php prepared-statement

如何改进下面的代码,以便我的网页真正有效?

function getCategoryConn($conn, $cat, $status) {
$result = array();
if(!$conn->connect_error) {
    $sqlstr = "SELECT cat, item, price, img, description " .
            "FROM product P, category C " . 
            "WHERE P.cat=C.cat AND P.cat=? AND C.cat=? ";
    $stmt = $conn->prepare($sqlstr);
    $stmt->bind_param("si", $cat, $status);   //line 37
    $stmt->execute();
    $stmt->bind_result($cat, $item, $price, $img, $description);
    while ($stmt->fetch()) {
        $result[$cat] = ["cat" => $cat,
                         "item" => $item,
                         "price" => $price,
                         "img" => $img,
                         "description" => $description];
    }
    $stmt->close();
}
return $result;
}

我在$ cat中有4种不同类型的数据。如何定义它以便可以显示所有4种类型的数据?

$productArr = getCategoryConn($conn, $cat, STATUS_ACTIVE);   //line 39 - the question I'm asking above

foreach ($productArr as $cat => $products) {
    if ($_GET['cat'] == $cat) {
        foreach ($products as $item => $info) {
               //foreach loop here
        } 
    }
} 

我目前有这些错误:

Notice: Undefined variable: cat in XXXXXXXXXXXX on line 39

Fatal error: Call to a member function bind_param() on a non-object in XXXXXXXXXXXX on line 37

1 个答案:

答案 0 :(得分:0)

在您的查询中,您有4个?

$sqlstr = "SELECT cat, item, price, img, description " .
        "FROM product P, category C " . 
        "WHERE P.cat=? = C.cat=? AND " .
        "P.status=? = C.cat=? ";

对于每个?,您需要告诉bind_param()变量?是什么类型。

例如,如果您有以下内容:

$this_is_int = 5;
$this_is_string = 'test';

$query = 'SELECT * FROM table WHERE id = ? and username = ?';

/*
    Binds variables to prepared statement

    i    corresponding variable has type integer
    d    corresponding variable has type double
    s    corresponding variable has type string
    b    corresponding variable is a blob and will be sent in packets
*/

// Since we have two `?` in our query, we must defined two inputs in our bind_params()

// Order of ? in the query matters!

// So in the above example, this is how bind_param(), would be set.

$stmt->bind_param('is', $this_is_int, $this_is_string)
//                 ^  relates to  ^ and ^
//           First one is `i` for int, and second one is `s` for string
//
// which relates to SELECT * FROM table WHERE id = ? and username = ?
//            The following order relates to above ^ ----- and ---- ^

所以你有这个

$stmt->bind_param("i", $cat, $status);
  1. 这里有两件事是错的,你在第一个参数中只有一个类型的setter i,但你在查询中有4个问号。

  2. 当您在查询中有4个问号时,您只有$cat$status

  3. 因此,如果$status是一个字符串,那就应该正确编写它:

    $stmt->bind_param("iisi", $cat, $cat, $status, $cat);