如何从mysqli获得与mysql_result()相同的结果?

时间:2014-08-15 16:48:30

标签: php mysql mysqli

我正在尝试将mysql_result()的结果与mysqli相同。

我想用这个。

function user_id_from_username() {
    $username = sanitize($username);
    return mysql_result(mysql_query("SELECT id FROM users WHERE username = '$username'"), 0, 'id');
}

进入mysqli

mysql_result()函数有string mysql_result ( resource $result , int $row [, mixed $field = 0 ] )个参数。

那么如何与mysqli中的相同?如果mysqli中有任何函数,其中包含mysql_result()函数等所有参数,可以在mysqli中使用。

我知道mysql扩展会贬低这就是我想使用mysqli的原因。

已更新

我知道如何将db连接传递给它,这不是问题。我也尝试过这个。和它的工作。

function user_active($username) {
    global $con;
    $username = sanitize($username);
    $result = mysqli_query($con,"SELECT `id` FROM `users` WHERE `username` = '$username' AND `active` = 1");
    return (mysqli_num_rows($result) == 1) ? true : false;
}
提前多多感谢。

2 个答案:

答案 0 :(得分:3)

没有相应的mysqli_result()函数,但这应该等同于基于mysql的代码:

function user_id_from_username() {
  $username = sanitize($username);
  $result = mysqli_query("SELECT id FROM users WHERE username = '$username'");
  $row = mysqli_fetch_row($result);
  return $row[0];
}

但是你真的应该检查你的函数调用的返回值,所以我更喜欢这样的东西:

function user_id_from_username() {
  $username = sanitize($username);
  $id = false;  // Return false on database error, or user not found.

  if ($result = mysqli_query("SELECT id FROM users WHERE username = '$username'")) {
    if ($row = mysqli_fetch_row($result)) {
      $id = $row[0];
    }
    mysqli_free_result($result); // Always free your resources.
  }

  return $id;
}

答案 1 :(得分:0)

简单方法:

$link = mysqli_connect('host', 'username', 'password' ,'database');

$name = mysqli_real_escape_string($link,$parameter);

$result = mysqli_query($link,"Query $parameter");
mysqli_close($link);

最佳方式:

$query = $link->prepare('SELECT FROM tblExample(fldExampleID,fldExampleName) WHERE fldExampleID = ?');
$query->bind_param('s', $email);
$result = $query->execute();
$link->close();

示例:

//Preparing the query
$query = $link->prepare('SELECT id FROM users WHERE username = ?');
//Replacing the ? by $username , s representing that my parameter is a string
$query->bind_param('s', $username);

//Execting the query
$result = $query->execute();

if($result != null){
    $userId;

    //Looping into the result set, if the result set has no row, won't go inside the loop 
    while($row = mysqli_fetch_assoc( $result )){ 
        $userId= $row["id"];
    }


    //Closing connection
    $link->close();
    return $userId;
}


else{
    //Closing connection
    $link->close();
    return "No userId found for username ".$username;
}

http://php.net//manual/en/pdo.prepared-statements.php