如何将简单的MySQL示例转换为MySQLi面向对象的样式?

时间:2012-06-16 21:30:53

标签: php mysql mysqli mysqli-multi-query

如何将这个简单的MySQL示例转换为MySQLi面向对象的样式:

$query = mysql_query("SELECT id, name FROM fruits WHERE `group`=''");

if ($query) {
    while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
        echo $row['name'];

        $query2   = mysql_query("SELECT name FROM fruits WHERE `group`='{$row['id']}'");

        if (mysql_num_rows($query2)) {
            echo ':';

            while ($row2 = mysql_fetch_array($query2, MYSQL_ASSOC)) {
                echo ' '. $row2['name'] . ',';
            }
            mysql_free_result($query2);

            echo '<br>';
        }
    }
    mysql_free_result($query);
}

结果:

Berries: blueberry, raspberry, strawberry,
Citrus: grapefruit, lime,
Pear

数据库结构SELECT * FROM fruits

id   | group | name
-------------------------
03E7 |       | Berries
0618 | 03E7  | blueberry
051B | 03E7  | raspberry
02AA | 03E7  | strawberry
035F |       | Citrus
07A5 | 035F  | grapefruit
0633 | 035F  | lime
05E1 |       | Pear

1 个答案:

答案 0 :(得分:1)

完整的工作代码:

<?php

$mysqli = new mysqli('localhost', 'root', '', 'test');

$query1 = 'SELECT id, name FROM fruits WHERE `group` = \'\'';// AND id = \'03E7\'
$query2 = 'SELECT name FROM fruits WHERE `group` = ?';

if ($stmt1 = $mysqli->prepare($query1)) {
    $stmt1->execute();
    $stmt1->store_result();
    $stmt1->bind_result($id, $name);

    while ($stmt1->fetch()) {
        echo $name;

        if ($stmt2 = $mysqli->prepare($query2)) {
            $stmt2->bind_param('s', $id);
            $stmt2->execute();
            $stmt2->store_result();
            $stmt2->bind_result($name);

            $count = $stmt2->num_rows;

            if ($count > 0) {
                echo ':';

                $i = 1;
                while ($stmt2->fetch()) {
                    echo ' ' . $name;

                    if($i < $count) {
                       echo ',';
                    } else {
                       echo '.';
                    }
                    $i++;
                }
                $stmt2->free_result();
                $stmt2->close();
            }
            echo '<br>';
        }
    }
    $stmt1->free_result();
    $stmt1->close();
}

?>

改进结果:

Berries: blueberry, raspberry, strawberry.
Citrus: grapefruit, lime.
Pear