【问题标题】:Function that check if value exists in sql server检查值是否存在于sql server中的函数
【发布时间】:2017-07-05 06:58:42
【问题描述】:

嘿,

我需要一个 php 函数来检查表单输入的值是否已经在数据库中(sql - server - PDO),并返回 TRUE 或 FALSE。

我尝试这样做,但我卡住了,在互联网上没有找到解决方案。 你能告诉我如何威胁上述条件吗?

function check_code($code) {
GLOBAL $handler;
$code = check_input($code);
        try{
      $query2 = $handler -> prepare("SELECT code from stock where code = :code");
      $query2 -> execute(array(
                    ':code' => $code
                    )); 
return  >???<
        }
        catch(PDOException $e){
            echo $e -> getMessage();
      }  }

【问题讨论】:

    标签: php sql-server pdo


    【解决方案1】:

    返回类似row_count(result) &gt; 0 的内容

    【讨论】:

      【解决方案2】:

      我以前从未使用过sql-server,但我曾多次使用 PDO,基本上这就是检查 pdo 的方式

      <?php
      function check_code($code)
      {
          GLOBAL $handler;
      
          $code = check_input($code);
          try {
              $query2 = $handler->prepare("SELECT code from stock where code = :code");
              $query2->execute(array(':code' => $code));
              $results = $query2->fetchColumn();
              if (count($results) > 0) {
                  echo "exists";
              } else {
      
                  echo "does not exist";
              }
          }
          catch (PDOException $e) {
              echo $e->getMessage();
          }
      }
      ?>
      

      注意:避免使用全局变量...Stop using `global` in PHP

      【讨论】:

      • 我使用了您的示例,即使值不存在,它也会返回 count($results) = 1 = exists。
      • ok 尝试更改 fetchColumn() 并替换为 fetch()fetchall() @IonutP。
      猜你喜欢
      • 2012-07-29
      • 2020-08-16
      • 2010-09-15
      • 1970-01-01
      • 2022-09-30
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      相关资源
      最近更新 更多