[英]Count MySQL rows with values
我想计算MySQL数据库中有两个特定值的行。 我的桌子是这样设置的:
|---------------------|
| ids |
|---------------------|
|source_id | target_id|
|----------|----------|
| 2 | 6|
| 2 | 6|
| 3 | 4|
|---------------------|
我想计算有多少行具有source_id = 2
和target_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文件在第三行之后停止运行。
SELECT COUNT(*) FROM ids WHERE source_id=2 AND target_id=6
您的代码看起来有点怪异。 如果要使用准备好的语句,则工作方式完全不同:
<?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";
将为您提供与您想要的条目相对应的条目数。
(它将给出一行加一列,其中包含与close对应的行数)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.