【问题标题】:mysqli_query not working. Missing connection?mysqli_query 不工作。缺少连接?
【发布时间】:2015-03-25 17:21:12
【问题描述】:

我是新来的。我已经搜索了所有但无法获得确切答案。我在 login.php 中执行 mysql_query 但它不工作。我尝试通过在 mysql_query 之后放置一个 if 条件来进行检查,并确认查询没有将结果返回为 true。我是否未能建立与 mysql 数据库的正确连接?请指导。

//登录.php

<?php


include_once("Connection.php"); 

if(!$con) {
die  ("Cannot Connect" . mysql_error());
}


$username = $_POST['UserName'];
$password = $_POST['Password'];

$result = "SELECT * FROM log WHERE username = $username AND userpass = $password";
$sql=mysqli_query($con,$result);

if($sql == FALSE) { 
    echo "this"; // TODO: better error handling
}



else{
	
$res=mysql_fetch_array($sql);
}



$num_rows = mysql_num_rows($res);
    echo $num_rows;

if ($num_rows > 0) {

session_start();
$_SESSION['login'] = "1";
header ("location: path.html");
}

else{
	
	echo $num_rows;
	//header ("location: index.htm");
	//exit ();
}


?>
//连接.php

<?php


$con=mysqlI_connect("localhost","root","","taxisystem" );  /* Connecting to sql */
/* we have used $con to store it in variable as we will have to use it multiple times! */

/*update: Now we will use connection.php instead! :) */


?>

【问题讨论】:

  • 你得到什么错误??
  • 目前我已经放置了这个 if-else 条件并且 if 条件正在打印这个。证明 $res 不正确。另外,如果我删除了这些 if else 子句,则 mysql_fetch_array() 期望参数 1 是资源。

标签: php mysql login error-handling database-connection


【解决方案1】:

应该是——

$con=mysqli_connect("localhost","root","","taxisystem" );

在连接页面上。你把它和mysql混在一起了——

<?php


include_once("Connection.php"); 

if(!$con) {
die  ("Cannot Connect" . mysqli_error($con));
}


$username = $_POST['UserName'];
$password = $_POST['Password'];

$result = "SELECT * FROM log WHERE username = '$username' AND userpass = '$password'";
$sql=mysqli_query($con,$result);

if($sql == FALSE) { 
    echo "this"; // TODO: better error handling
}



else{

$res=mysqli_fetch_array($sql);
}



$num_rows = mysqli_num_rows($sql);
    echo $num_rows;

if ($num_rows > 0) {

session_start();
$_SESSION['login'] = "1";
header ("location: path.html");
}

else{

    echo $num_rows;
    //header ("location: index.htm");
    //exit ();
}


?>

请转义。

【讨论】:

    【解决方案2】:

    您的查询不正确。您必须在变量周围添加单引号,因为那是 char 类型。

    $result = "SELECT * FROM log WHERE username = '$username' AND userpass = '$password'";
    

    使用 sql 的更好方法是预处理语句。

    另一个问题是连接类型必须是mysqli 而不是mysqlI

    $con=mysqli_connect("localhost","root","","taxisystem" );  
    

    【讨论】:

    • 感谢 Janes 帮助我摆脱了 if else 循环。我仍然在第 25 行有错误说 mysql_fetch_array() 期望参数 1 是资源。我使用的格式不正确吗?请帮助@jens
    • @Worried_user 你必须使用mysqli_fetch_array。但是你使用mysql_fetch_array(缺少i
    猜你喜欢
    • 2011-01-28
    • 2021-09-07
    • 2012-07-12
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-19
    • 2014-02-10
    相关资源
    最近更新 更多