用值计算MySQL行数


Count MySQL rows with values

我想计算MySQL数据库中有多少行具有两个特定值。我的桌子是这样设置的:

|---------------------|
|         ids         |
|---------------------|
|source_id | target_id|
|----------|----------|
|        2 |         6|
|        2 |         6|
|        3 |         4|
|---------------------|

我想计算有多少行有source_id = 2target_id = 6我试过这样的说法:

<?php
$prep_stmt = "SELECT source_id FROM ids WHERE source_id = 2 AND target_id = 6";
if (!$result = $mysqli->query($prep_stmt)) {
    die("Failed");
} else {
    $num_rows = $result->num_rows;
    echo $num_rows;
}
?>

但是,PHP文件在第三行之后停止运行。

您的代码看起来有点奇怪如果你想使用准备好的语句,那就完全不同了:

<?php
$stmt = $mysqli->prepare("SELECT COUNT(*) FROM `ids` WHERE `source_id` = ? AND `target_id` = ?");
$stmt->bind_param("ii", $source_id, $target_id);
$stmt->execute();
$stmt->bind_result($count);
$stmt->fetch();
$stmt->close();
echo $count;

而且没有事先准备好的发言。

<?php
echo $mysqli->query("SELECT COUNT(*) FROM `ids` WHERE `source_id` = 2 AND `target_id` = 6");

最后要注意的是,如果您在一个条件内指定了任何,请确保将其括在括号中:

<?php
function fn() {
  return "something";
}
if (($foo = fn())) {
  // The condition is true if $foo isset, or in other words not null after the function was called.
}
if (!($foo = fn())) {}
if (($foo = fn()) === null) {}
// ...

SELECT COUNT(*) FROM ids WHERE source_id=2 AND target_id=6

SELECT COUNT(*) FROM ids WHERE source_id = 2 AND target_id = 6";

将为您提供与您想要的条目相对应的条目数量。

(它将给出一行1列,包含与where关闭对应的行数(