简体   繁体   English

用值对MySQL行进行计数

[英]Count MySQL rows with values

I want to count how many rows in my MySQL database have two certain values. 我想计算MySQL数据库中有两个特定值的行。 My table is set up like this: 我的桌子是这样设置的:

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

I want to count how many rows have the source_id = 2 and target_id = 6 I tried this statement: 我想计算有多少行具有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;
}
?>

However, the PHP file ceases to function after the third line. 但是,PHP文件在第三行之后停止运行。

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

Your code looks a bit weird. 您的代码看起来有点怪异。 If you want to use prepared statements, that's working totally differentely: 如果要使用准备好的语句,则工作方式完全不同:

<?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;

And without prepared statements. 并且没有准备好的陈述。

<?php

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

And as a last note, if you asign anything within a condition be sure to enclose it in brackets: 最后一点,如果您在条件内指定任何东西 ,请务必将其括在方括号中:

<?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";

will give you the number of entries corresponding to what you want. 将为您提供与您想要的条目相对应的条目数。

(it will give one row with 1 column, containing the number of lines corresponding to the where close) (它将给出一行加一列,其中包含与close对应的行数)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM