MySQL在哪里包含最后一个字符%

时间:2018-03-27 15:04:50

标签: php mysql

我使用此功能排除插入同名新税的可能性:

function check_name_free($id, $name) {

if ( $id == "" ) {

    // NEW INSERT

    $sql = "SELECT Name FROM tax WHERE Name LIKE ?";
    try {
        $rs = $db->prepare($sql);
        $rs->execute(array($name));
        $ris = $rs->fetchAll(PDO::FETCH_ASSOC);
    } catch(PDOException $e) {
        die($e);
    }
} else {

    //MODIFY ACTUAL RECORD

    $sql = "SELECT Name FROM tax WHERE Name LIKE ? AND ID != ?";
    try {
        $rs = $db->prepare($sql);
        $rs->execute(array($name, $id));
        $ris = $rs->fetchAll(PDO::FETCH_ASSOC);
    } catch(PDOException $e) {
        die($e);
    }
}

if ( count($ris) > 0 )
    return false;

return true;

}

但是,在我的表单上,我将修改($_POST['action'] == "edit")一个名称为last char%的现有条目,例如 TAX 20% ,我的脚本返回false

table tax内的实际记录:

姓名:税10%

姓名:TAX 20%

姓名:TAX 21%

我的index.php

if ( isset($_POST['action']) && $_POST['action'] == "edit" ) {
   $id = $_POST['id'];
   $name = $_POST['name'];

   $free = check_name_free($id, $name);

   if ( !$free ) {
     echo "Name already in use";
     exit();
   }

 // continue edit
}

如何修改LIKE ?以在最后一个字符上使用%接受正确的$ string?

1 个答案:

答案 0 :(得分:0)

寻找mysql doc https://dev.mysql.com/doc/refman/5.7/en/string-comparison-functions.html

您可以使用SELECT CASE WHEN Status IN ('a', 'b', 'd') THEN 'I' WHEN Status IN ('e', 'f') THEN 'II' END AS "Status Group", count(*) as Count FROM Table GROUP BY 1 ORDER BY 1 ;

逃脱%
\%

或使用regexp

  SELECT 'David%' LIKE 'David\%';

在你的情况下

 select 'mystring%' regexp('%');

SELECT Name FROM tax WHERE Name like ('%21\%')