简体   繁体   English

如何检查字符串是否已在SQL db中

[英]How to check if a string is already in SQL db

I am creating a small plugin which gives a serial number to each post, each serial number has to be unique, I don't know how to check if the generated serial number is already in the SQL db. 我正在创建一个小插件,它为每个帖子提供一个序列号,每个序列号必须是唯一的,我不知道如何检查生成的序列号是否已经在SQL db中。

This is the key generator code: 这是密钥生成器代码:

function generateRandomString($length = 5) {
    $characters = '123456789';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return '#'.$randomString;   
$new_SN = generateRandomString(); }

How do I check if the value of $new_SN is already stored in a relevant SQL table cell - in my case the table is wp_postmeta, meta_key is serial and the meta_value is, well, the value populated by the function 如何检查$new_SN的值是否已存储在相关的SQL表单元格中-在我的情况下,该表是wp_postmeta,meta_key是串行的,而meta_value是该函数填充的值

Why are you generating a unique number? 你为什么要生成一个唯一的号码? There are lots of tools specifically designed for this purpose - since you've mentioned MySQL, it supports auto-increment integers, PHP supports uuid (uniqid()) and several hashing functions (if you don't want to use sequential numbers). 有很多专门为此目的而设计的工具 - 因为你已经提到了MySQL,它支持自动增量整数,PHP支持uuid(uniqid())和几个散列函数(如果你不想使用序列号)。 And as developerwjk says - if your generation function is at all effective then you shouldn't bother with a checking before saving the data - just add a unique index and trap duplicates when they fail to insert. 正如developerwjk所说 - 如果你的生成函数完全有效,那么在保存数据之前你不应该费心去检查 - 只需添加一个唯一的索引并在它们无法插入时捕获重复项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM