0

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 current 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..

John
  • 2,900
  • 8
  • 36
  • 65
  • Can you post your current mysqli code? – alexn Sep 26 '11 at 06:46
  • 1
    possible duplicate of [MySQLi equivalent of mysql_result()?](http://stackoverflow.com/questions/2089590/mysqli-equivalent-of-mysql-result) – alexn Sep 26 '11 at 06:48
  • edited the file now have a look – John Sep 26 '11 at 06:48
  • Does this answer your question? [MySQLi equivalent of mysql\_result()?](https://stackoverflow.com/questions/2089590/mysqli-equivalent-of-mysql-result) – Dharman Feb 26 '20 at 20:08

3 Answers3

3

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

cbednarski
  • 11,718
  • 4
  • 26
  • 33
1

Based on this thread, there is no such equivalent:

MySQLi equivalent of mysql_result()?

They give some possible alternatives, however.

Community
  • 1
  • 1
user470714
  • 2,858
  • 1
  • 28
  • 34
0

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.';
}
RavuAlHemio
  • 2,331
  • 19
  • 22