如何用mysqli解决期望参数问题

时间:2017-01-17 19:25:47

标签: php mysqli

我在script1.php收到此错误。

这是我到目前为止所尝试的。以下是我的script1.php代码,然后转到welcome.php

<?php
$link = mysqli_connect("localhost", "root", "", "demo");
echo "jay";

// Check connection
if ($link === false)
{
    die("ERROR: Could not connect. " . mysqli_connect_error());
    session_start();
}

$uname1 = ($_POST['username']);
$pass1 = ($_POST['password']);

$sql = "SELECT id FROM persons WHERE usernamesignup = '$uname1' and passwordsignup= '$pass1'";
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$active = $row['active'];

$count = mysqli_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row

if ($count == 1)
{
    echo " jayesh vyas";
    session_register("myusername");
    $_SESSION['login_user'] = $myusername;

    header("location: welcome.php");
} else
{
    $error = "Your Login Name or Password is invalid";
}
?>

welcome.php代码如下:

<?php
include('session.php');
?>
<html">

<head>
    <title>Welcome </title>
</head>

<body>
<h1>Welcome <?php echo $login_session; ?></h1>
<h2><a href="logout.php">Sign Out</a></h2>
</body>

</html>

所以每当我执行script1.php时,它会向我显示一些警告:

  

警告:mysql_fetch_array()期望参数1是资源,   在C:\ xampp \ htdocs \ LoginRegistrationForm \ script1.php中给出的布尔值   第17行

     

警告:mysqli_num_rows()期望参数1为mysqli_result,   在C:\ xampp \ htdocs \ LoginRegistrationForm \ script1.php中给出的布尔值   第20行

我很欣赏我做错了什么并解决了这个问题?

1 个答案:

答案 0 :(得分:0)

mysqli_query会因错误而返回false而非resource,类似于mysqli_connect

  

失败时返回 FALSE 。对于成功的SELECT,SHOW,DESCRIBE或EXPLAIN查询,mysqli_query()将返回一个mysqli_result对象。对于其他成功的查询,mysqli_query()将返回 TRUE

要解决此问题,请将mysqli_query包裹在if条件中,以确保没有发生错误,并在开发环境中输出错误。

由于您的查询是接受用户输入,我还建议使用预准备语句,以帮助降低SQL注入的风险。

$sql = 'SELECT `id` FROM `persons` WHERE `usernamesignup` = ? AND `passwordsignup` = ?';
if (!$stmt = mysqli_prepare($link, $sql)) {
    die(mysqli_error($link));
}
mysqli_stmt_bind_param($stmt, 'ss', $uname1, $pass1);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $id);
mysqli_stmt_fetch($stmt);

echo $id;

mysqli_stmt_close($stmt);
mysqli_close($link);

作为旁注,您还应将session_start();移出if ($link === FALSE)区块。