开发者

Mysql to mysqli php

I am trying to convert my current code to MySQLi extension... But I have a problem with this code..

    $sql = "SELECT COUNT(*) FROM users WHERE username='$username'";
    $result = mysql_query($sql);
    if (mysql_result($result, 0) > 0) {
  $errors[] = 'The username is already taken.';
    }

What is the mysqli function of "mysql_result" ? I can't get it work.

My curren开发者_如何学编程t MySqLi code is just the connection and

    $sql = "SELECT COUNT(*) FROM users WHERE username='$username'";
    $result = $mysqli->query($sql);
    if (mysql_result($result, 0) > 0) {
  $errors[] = 'The username is already taken.';
    }

But I need to change the mysql_result, but can't find the opposite function in MySQLi..


I usually use the object-y interface to MySQLi:

<?php
$db = new mysqli($hostname, $username, $password, $database);
$result = $db->query('SQL HERE');

// OOP style
$row = $result->fetch_assoc();
$row = $result->fetch_array();

while($row = $result->fetch_row())
{
    // do something with $row
}

// procedural style, if you prefer
$row = mysqli_fetch_assoc($result);
$row = mysqli_fetch_array($result);

while($row = mysqli_fetch_row($result))
{
    // do something with $row
}
?>

Full list of result methods is here: http://www.php.net/manual/en/class.mysqli-result.php


Based on this thread, there is no such equivalent:

MySQLi equivalent of mysql_result()?

They give some possible alternatives, however.


There is no equivalent to mysql_result, but you can fetch a single row and use the first element of this row (because your query returns a table of one row and one column):

$sql = "SELECT COUNT(*) FROM users WHERE username='$username'";
$result = $mysqli->query($sql);
$arr = $result->fetch_row();
if ($arr[0] > 0) {
    $errors[] = 'The username is already taken.';
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜