如何在PDO中使用SELECT IFNULL? [英] How to use SELECT IFNULL in PDO?

查看:78
本文介绍了如何在PDO中使用SELECT IFNULL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一种方法来返回错误,如果在MySql查询中未找到结果,首先我将变量值声明为false,如果fetch()函数为true,它将将该布尔值设置为是的,那么我检查它是对还是错,但是后来我在互联网上搜索了它,因为我不太喜欢我的解决方案,所以我找到了函数IFNULL(query,'error message'); 我尝试过,但是遇到了错误,您能告诉我我的代码有什么问题吗?

i was looking for a way to return an error if no results were found in a MySql query, at first i declared a variable value false, and if the fetch() function is true it will set the value of that boolean to true, then i check if it is true or false, but then i searched for that in internet cause i didn't like my solution that much, so I found the function IFNULL(query, 'error message'); I tried it but I had an error, can you tell me what's wrong in my code?

if(isset($_POST['tosearchfor']))
        {
            $query = $db->query('SELECT IFNULL( (SELECT * FROM searchfor WHERE title LIKE \'%'.$_POST['tosearchfor'].'%) , \'Sorry, no resluts found for : <strong>'.$_POST['tosearchfor'].'strong');
            while($result = $query->fetch())
            {
                echo '<div class="result"><a class="title" href="#">'.$result['title'].'</a><span class="link"><span style="font-size:15px;position:relative;top:0.8px;padding-right:2px;">&#8227;</span>https://www.qsoft.com/'.$result['link'].'</span><span class="details">'.$result['details'].'</span></div>';
            }
        }
        else
        {
            echo 'Error : empty search';
        }

谢谢.

推荐答案

IFNULL(expr1,expr2)的默认结果值更通用" 这两个表达式中的一个,顺序为STRING,REAL或INTEGER.

The default result value of IFNULL(expr1,expr2) is the more "general" of the two expressions, in the order STRING, REAL, or INTEGER.

您不能使用IFNULL评估一组记录.像下面这样

You cannot evaluate a group of records with IFNULL. Something like below

除了使用直接替换值之外,您还可以使用以下方法来避免sql注入.

Also instead of using direct substitution values, you could use below methods to avoid sql injection.

$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');

$stmt->execute(array(':name' => $name));

if(empty($stmt)){
  return false;
}

foreach ($stmt as $row) {
    // do something with $row
}

return result;

如果此方法返回false,则没有搜索结果.

If this method return false then there is no search result.

这篇关于如何在PDO中使用SELECT IFNULL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆