比较2条记录,但不会比较

时间:2019-02-27 09:32:27

标签: php mysql

我有一个必须控制数据库中2条记录的代码。

如果total_rows较小,则allowed必须添加用户。否则,它必须显示一条消息。

如果我使用<=可以正常工作,但可以使用所有功能,而当我使用<时则无法正常工作。

我的问题是为什么它不起作用?

PS:它没有给出错误,因为它在另一个文档中,而不是html

这是我的代码:

$allowed = "SELECT 
    `allowed_users` AS allowed 
  FROM 
    `partner_subscriptions` 
  WHERE
    `user_id` = '".$_SESSION['user_id']."'";

$row = mysqli_num_rows($allowed);
$count = "SELECT 
    COUNT(`user_id`) 
  AS 
    total_rows 
  FROM 
    users 
  WHERE 
    org_id = '".$_POST['org']."'";

$row2 = mysqli_fetch_array($count);

if ($row2['total_rows'] <= $row['allowed'])
{ 
    $q = "UPDATE 
        `organisations` 
      SET 
        `current_users` = `current_users` + 1 
      WHERE 
        `org_id`='".$_POST['org']."'";

    $sql = "UPDATE 
       `users` 
      SET 
        `active`= 1, 
        `type` = 0 
      WHERE 
        `user_id` = '" . $_POST['user'] . "'";

      if ($conn->query($sql) && $conn->query($q) === TRUE) {
            echo "New record created successfully";

    } else {

      echo "Error: " . $sql . "<br>" . $conn->error;

    }
}
else
{
    throw new Exception('Limit reached');
}

2 个答案:

答案 0 :(得分:2)

您只获得count_row而不是内容允许的

尝试使用mysqli_fetch_array

$allowed = "SELECT `allowed_users` AS allowed FROM `partner_subscriptions` 
    WHERE `user_id` = '".$_SESSION['user_id']."'";
$result1 = mysqli_query($your_conn, $allowed);
$row = mysqli_fetch_array($result1);

$count = "SELECT COUNT(`user_id`) AS total_rows FROM users WHERE org_id = '".$_POST['org']."'";
$result2 = mysqli_query($your_conn, $count);

$row2 = mysqli_fetch_array($result2);

if ($row2['total_rows'] <= $row['allowed'])

答案 1 :(得分:1)

$allowed = "SELECT `allowed_users` AS allowed FROM `partner_subscriptions` WHERE `user_id` = '".$_SESSION['user_id']."'";
$row = mysqli_num_rows($allowed);
$count = "SELECT COUNT(`user_id`) AS total_rows FROM users WHERE org_id = '".$_POST['org']."'";
$row2 = mysqli_fetch_array($count);

我在上面的代码中注意到,您从未在这里调用方法mysqli_query(),您只是在创建字符串查询,而不执行它们。这意味着PHP最有可能不初始化$row$row2

您可以通过以下两种方式声明它们:

$allowed = mysqli_query($connection, "SELECT `allowed_users` AS allowed FROM `partner_subscriptions` WHERE `user_id` = '".$_SESSION['user_id']."'");
$row = mysqli_num_rows($allowed);
$count = mysqli_query($connection, "SELECT COUNT(`user_id`) AS total_rows FROM users WHERE org_id = '".$_POST['org']."'");
$row2 = mysqli_fetch_array($count);

OR

$allowed = "SELECT `allowed_users` AS allowed FROM `partner_subscriptions` WHERE `user_id` = '".$_SESSION['user_id']."'";
$result_allowed = mysqli_query($connection, $allowed);
$row = mysqli_num_rows($allowed);

$count = "SELECT COUNT(`user_id`) AS total_rows FROM users WHERE org_id = '".$_POST['org']."'";
$result_count = mysqli_query($connection, $count);
$row2 = mysqli_fetch_array($result_count);