I'm using a SELECT COUNT(*)
in order to verify that a user exists with PHP PDO and MySQL. I'd also like to get a specific column value. There is only ever one value/row or no value/row per user.
I'm trying to do something like this:
$stmt = $link->prepare('SELECT COUNT(*) AND column FROM table WHERE user=:user');
What I'm hoping to get back is, 1, and the column value. Where I can then bind the column value to a variable.
If not, I'll have to first do the SELECT COUNT(*)
then do another query to get the column name after verifying that the user and this column exists from the SELECT COUNT(*)
query.
You just need to think a little.
"count(*)" is not a special method "to verify that a user exists". It's just a query where you select count because you just have no idea what to select else.
But as long as you have a column to select, you don't need no counts anymore.
Therefore, just select your value, and as long as you are getting it, you can tell that a user exists
$stmt = $link->prepare('SELECT column FROM table WHERE user=:user');
$stmt->execute([$user]);
$col = $stmt->fetchColumn();
if ($col) {
// user exists
$something = $col; // use $col as you wanted
}
While selecting count() and a column without a group by operator is a tricky query, and you should avoid it in general.
SELECT count(*), column FROM table where user=:user
It's what you want no ?
Otherwise you can count the number of result in php
$pdo = new PDO('mysql:host=XXX.fr.mysql;dbname=YYYY', 'ZZZ', 'TTT', $pdo_options);
$response = $pdo->query('SELECT column FROM table');
$count = 0;
while ($data = $response->fetch())
{
$count++;
}
$reponse->closeCursor();
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.