I want to count how many rows in my MySQL database have two certain values. 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:
<?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.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.