mysql_select_db()期望参数2是登录表单的资源

时间:2015-03-23 10:13:05

标签: php

我的代码有问题。我知道这与另一个线程重复。但我真的需要帮助来纠正这段代码。因为如果用户存在,我已尝试过多种方式来显示“echo'User Found'”。它是登录表单。 这是代码:

<?php
$hostname_localhost ="*****";
$database_localhost ="*****";
$username_localhost ="*****";
$password_localhost ="*****";
$localhost = mysqli_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);

mysql_select_db($database_localhost, $localhost);

$username = $_POST['kode_user2'];
$password = $_POST['password'];
$query_search = "select * from user2 where kode_user2 = '".$username."' AND password = '".$password. "'";
$query_exec = mysql_query($query_search,$localhost) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
if($rows == 0) { 
echo "No Such User Found"; 
}
else  {
echo "User Found"; 
}
?>

当我想要跑步时,它会显示:

  

警告:mysql_select_db()期望参数2是资源,对象   在第10行的/home/u466318196/public_html/loginDatabase2.php中给出

     

警告:mysql_query()期望参数2是资源,对象   在第15行的/home/u466318196/public_html/loginDatabase2.php中给出

任何人都可以提供帮助吗?

2 个答案:

答案 0 :(得分:1)

用以下代码替换您的代码:

<?php
$hostname_localhost ="*****";
$database_localhost ="*****";
$username_localhost ="*****";
$password_localhost ="*****";
$conn = mysqli_connect($hostname_localhost,$username_localhost,$password_localhost, $database_localhost) or die(mysqli_error($conn));


$username = mysqli_real_escape_string($conn, $_POST['kode_user2']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$query_search = "select * from user2 where kode_user2 = '".$username."' AND password = '".$password. "'";
$query_exec = mysqli_query($conn, $query_search) or die(mysqli_error($conn));
$rows = mysqli_num_rows($query_exec);
//echo $rows;
if($rows == 0) { 
   echo "No Such User Found"; 
}
else  {
   echo "User Found"; 
}
?>

答案 1 :(得分:0)

正如其他人在评论中所说,你必须在mysqli_ * API和mysql_ * API之间保持一致。 2不要混合在一起。此外,您可以忽略任何以mysql_开头的函数,因为它们已被弃用且不应使用。

注意你使用mysql_select_db(),mysql_error(),mysql_query(),mysql_num_rows()等等。所有这些都必须用mysqli中的等价物替换。

然后你应该准备你的语句并绑定它,而不是仅仅将查询构造为字符串。

看看这个,从http://php.net/manual/en/mysqli.prepare.php -

复制/修改
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$username = $_POST['kode_user2'];
$password = $_POST['password'];

/* create a prepared statement */
if ($stmt = mysqli_prepare($link, "select * from user2 where kode_user2 =  ? AND password = ?")) {

    /* bind parameters for markers */
    mysqli_stmt_bind_param($stmt, "ss", $username, $password);

    /* execute query */
    mysqli_stmt_execute($stmt);

    $result = mysqli_stmt_get_result($stmt);
    if ($row = mysqli_fetch_assoc($result)) {
        # Here you know you got a result...
    }

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>