什么是mysqli相当于此?

时间:2012-09-05 01:00:09

标签: php mysql mysqli

对于php / mysql来说,我似乎有点老了,老实说只是习惯了它,但现在我不断被告知使用 mysqli 而不是 mysql 所以我一直在阅读一些帖子/文章,包括关于它的php.net,但没有一个对我有意义,所以想想也许有些人会给我一个等同于我的片段我可能会开始为了更好地理解它...

这是一个简单的mysql while循环:

$query  = "SELECT * FROM foo ORDER BY id DESC LIMIT 10, 10";
$result = mysql_query($query);

while ($row = mysql_fetch_array($result)) {

$dog = $row['dog'];

  echo $dog;

}

3 个答案:

答案 0 :(得分:1)

在程序样式中使用mysqli的等价物将是:

$link = mysqli_connect("localhost", "user", "pass", "db");
$query = "SELECT * FROM foo ORDER BY id DESC LIMIT 10, 10";
$result = mysqli_query($link, $query) or die(mysqli_error($link));

while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
    $dog = $row['dog'];
    echo $dog;
}

mysqli_free_result($result);
mysqli_close($link);

答案 1 :(得分:1)

试试这个:

$query  = "SELECT * FROM foo ORDER BY id DESC LIMIT 10, 10";
$result = mysqli_query($query) or die (mysqli_error());

while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

$dog = $row['dog'];

  echo $dog;

}

答案 2 :(得分:1)

mysqli有两个不同的接口,一个非常类似于旧式的mysql接口和一个面向对象的接口。

面向对象的版本就是这样的:

/* establish connection */
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo $mysqli->connect_error;
    return;
}

/* query & fetch-loop */
$result = $mysqli->query("SELECT * FROM foo ORDER BY id DESC LIMIT 10, 10");
if (!$result) {
    echo $mysqli->error;
    return;
}
while ($row = $res->fetch_assoc()) {
    $dog = $row['dog'];
    echo $dog;
}

如您所见,代码长度与旧样式版本大致相同(只是忽略错误检查和连接的打开)。

BTW:mysqli文档也不错,你只需要跳过第一页,因为这个很奇怪。我将从这里开始:http://www.php.net/manual/en/mysqli.quickstart.connections.php