【问题标题】:getting undesired result by prepare statement mysqli php通过准备语句mysqli php得到不想要的结果
【发布时间】:2014-01-09 15:33:18
【问题描述】:

您好,我是 PHP 新手,我正在尝试编写登录准备语句,但如下代码所示,我的查询没有得到任何行,而是得到 field_count

如果我说的话

SELECT * FROM users WHERE UserName = 'DemoUser'

在直接数据库中,我得到一行,但这里 $stmt->num_rows 为零。我错过了什么。

// in connections.php
$dbh = new mysqli($host, $username, $password, $database);

include('connections.php');
include('config.php');
include('comman_functions.php');

if(isset($_POST['password']) && $_POST['password']!=''
    && isset($_POST['username']) && $_POST['username']!=''
    && isset($_POST['location']) && $_POST['location']!='') {

    $username = "DemoUser";
    $stmt = $dbh->prepare("SELECT * FROM users WHERE UserName =? ");
    $stmt->bind_param("s", $username);
    $stmt->execute();  
    error_log($stmt->num_rows); 
    if($stmt->num_rows>0){
    $row = $stmt->fetch();
    error_log("logged in!!!");

    $stmt->close();

    } else {
        $_SESSION['error'] = 'Invalid Username or Password';
        header('Location:index.php');
    }
} else {
    $_SESSION['error'] = 'Please provide Username and Password';
    header('Location:index.php');
}

【问题讨论】:

标签: php mysql mysqli


【解决方案1】:

试试这个!

你需要在$stmt->execute();之后添加$stmt->bind_result();

$dbh = new mysqli($host, $username, $password, $database);// in connections.php



<?php
  include('connections.php');
  include('config.php');
  include('comman_functions.php');

  if(isset($_POST['password']) && $_POST['password']!='' && isset($_POST['username']) && $_POST['username']!='' && isset($_POST['location']) && $_POST['location']!=''){

    $username = "DemoUser";
    $stmt = $dbh->prepare("SELECT * FROM users WHERE UserName =? ");
      $stmt->bind_param("s", $username);
      $stmt->execute();  
      $stmt->bind_result();
      error_log($stmt->num_rows); 
    if($stmt->num_rows>0){
      $row = $stmt->fetch();
        error_log("logged in!!!");

      $stmt->close();

    }else{
      $_SESSION['error'] = 'Invalid Username or Password';
      header('Location:index.php');
    }
  }else{
    $_SESSION['error'] = 'Please provide Username and Password';
    header('Location:index.php');
  }

?>

【讨论】:

  • 感谢先生,但我正在使用 $dbh = new mysqli($host, $username, $password, $database);行数是 PDO 函数
  • 嘿,我刚刚尝试了你所说的......但仍然没有从数据库中获取数据,但能够从 $stmt->field_count 中找到列号的计数
【解决方案2】:

如果您在完成这 num_rows 时遇到问题,您必须先声明 -&gt;store_result()

<?php
$mysqli = new mysqli("localhost","root", "", "tables");

$query = $mysqli->prepare("SELECT * FROM table1");
$query->execute();
$query->store_result();

$rows = $query->num_rows;

echo $rows;

【讨论】:

  • 嘿,我正在获取行数,但无法从该对象获取()数据:(
猜你喜欢
  • 1970-01-01
  • 2015-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-04
  • 2015-03-01
相关资源
最近更新 更多