PHP(mysqli)查找单个值

时间:2015-06-22 01:30:35

标签: php mysqli

我知道如何使用mysqli搜索是否至少有一个匹配。如何从找到的行中检索另一个值。它只需要改变1或2件事。

想象一下,我有以下数据库:

 ID     |     emailaddress     |    password
 1      |     dummy@email.com  |    DUMB1PASS
 2      |     second@email.com |    DUMB2Pass

我可以使用以下代码验证,如果,则存在电子邮件地址“dummy@email.com”。我如何查找与该行相关联的密码(即包含dummy@email.com的行)。

$email = "dummy@email.com";
$servername = "correct"; $username = "correct"; $DBpass = "correct"; $dbname = "correct";
    $conn = new mysqli($servername, $username, $DBpass, $dbname);
    if ($conn->connect_error)
        {
            die("Connection failed: " . $conn->connect_error);
        } 

    $sql = "SELECT emailaddress FROM registration WHERE emailaddress = '$email'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0)
        {
            echo "we found a match";
        } 
    else
        {
            echo "we did not find a match";
        }

我想我可以做类似的事情:

$email = "dummy@email.com";
$servername = "correct"; $username = "correct"; $DBpass = "correct"; $dbname = "correct";
    $conn = new mysqli($servername, $username, $DBpass, $dbname);
    if ($conn->connect_error)
        {
            die("Connection failed: " . $conn->connect_error);
        } 

    $sql = "SELECT password FROM registration WHERE emailaddress = '$email'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0)
        {
            echo "the value is '$result'";
        } 
    else
        {
            echo "we did not find a match";
        }

但是,它会产生此错误:

Catchable fatal error: Object of class mysqli_result could not be converted to string in MYPAGE on line XX.

我认为造成这种情况的原因可能是$ result是一个数组或其他东西。但是,我不太了解sql / php是否存在问题,或者如果是这样的话,如何从中获取结果。

我真的很感激任何帮助。

1 个答案:

答案 0 :(得分:0)

你需要先获取行,试试这个:

if ($result->num_rows) {
  $row = $result->fetch_row();
  echo 'the value is: ', $row[0];
}