mysql检查值是否大于0

时间:2014-06-03 17:12:33

标签: php mysql

这是我的代码。实际上它运行没有错误,但它总是进入第一个条件,即使mysql中的值大于0,例如是10。

<?php
session_start();
$loginuser = $_SESSION['result'];
$con=mysqli_connect("localhost","root","","leavecalendar");
// Check connection
if (mysqli_connect_errno())
 {
 echo "Failed to connect to MySQL: " . mysqli_connect_error();
 }
$sql="SELECT leavecount from employee WHERE username = $loginuser[username]";
$resource = mysql_query($sql);
if ($resource == 0) {
echo "ajsdjsdasjd";   <----always enters here
 }
else
{
header("insert.php");
} 

mysqli_close($con);
?>

2 个答案:

答案 0 :(得分:0)

首先,你正在混合api。不要混用mysqli_*mysql_*。坚持使用mysqli_*

$con = mysqli_connect("localhost","root","","leavecalendar"); // mysqli
$resource = mysql_query($sql); // mysql

其次,由于您现在使用mysqli_*,只需使用预准备语句。

$sql="SELECT leavecount from employee WHERE username = $loginuser[username]";

第三,不要将结果集与零进行比较,而是检查结果返回的行数。

$resource = mysqli_query($con, $sql);
if ($resource == 0) {

考虑这个例子:

session_start();
if(isset($_SESSION['result'])) {
    $mysqli = mysqli_connect("localhost","root","","leavecalendar");
    $loginuser = $_SESSION['result'];
    $stmt = $mysqli->prepare("SELECT leavecount from employee WHERE username = ?");
    $stmt->bind_param("s", $loginuser);
    $stmt->execute();

    if($stmt->num_rows > 0) {
        // if it has results
        header("Location: insert.php");
    } else {
        // if it has NO results
    }
} 

答案 1 :(得分:-1)

  • 问题

1)您无法使用

mysql_query($query)

对于mysqli

2)

"SELECT leavecount from employee WHERE username = $loginuser[username]"

用户名应为单引号或双引号。 例如:"SELECT leavecount from employee WHERE username = 'dineshrawat'";

  • <强>解决方案

    <?php
    session_start();
    $loginuser = $_SESSION['result'];
    $con=mysqli_connect("localhost","root","","leavecalendar");
    // Check connection
    if (mysqli_connect_errno())
     {
     echo "Failed to connect to MySQL: " . mysqli_connect_error();
     }
    $sql="SELECT leavecount from employee WHERE username = $loginuser[username]";
    $resource = mysqli_query($con, $sql);
    
    if ($resource == 0) { // If there is no record in result set
    echo "No record found";
     }
    else
    {
    header("insert.php");
    } 
    
    mysqli_close($con);
    ?>