PHP mysqli query to check if a row exist [duplicat

2019-02-26 07:35发布

This question already has an answer here:

I have a mysql table, I want to check if a row exists where columnA=$a and $columnB=$b. I dont need to select anything from there. What should be efficient query for that? Currently Im doing like,

if ($stmt = mysqli->prepare("SELECT * FROM TABLE WHERE columnA=? && columnB= ? LIMIT 1")) {
    $stmt->bind_param("ss", $a, $b);
    $stmt->execute();
    $stmt->store_result();
    $count=$stmt->num_rows;
    $stmt->close();
    }
    return ($count > 0 ? true : false);

标签: php mysqli
3条回答
放荡不羁爱自由
2楼-- · 2019-02-26 07:53

Select just one field from the row instead of all of them (*). Even though you're not using them, mysql still has to fetch them from storage and get them ready for transmission.

SELECT columnA FROM table WHERE ...

Otherwise there's not much else you can do to improve things, other than putting indexes on columnA and columnB to make the searching go faster.

查看更多
Deceive 欺骗
3楼-- · 2019-02-26 08:02

Try with this:

if ($stmt = $mysqli->prepare("SELECT COUNT(*) FROM TABLE WHERE columnA=? && columnB=?")) {
    $stmt->bind_param("ss", $a, $b);
    $stmt->execute();
    $stmt->bind_result($count);
    $stmt->fetch();
    $stmt->close();
}

return ($count > 0 ? true : false);

Now you should be able to get it done

查看更多
仙女界的扛把子
4楼-- · 2019-02-26 08:03

That is efficient query if you want to improve that query you should select one column only to speed up the query.

if ($stmt = mysqli->prepare("SELECT id FROM TABLE WHERE columnA=? && columnB= ? LIMIT 1")) {
查看更多
登录 后发表回答