Php 比较从mySql查询返回的字符串
我正在从数据库中查询大量代码,在用户可以向数据库中输入其他代码之前,需要进行一些验证 示例代码如下所示: TD-BR-010212-xxxxxxxx 其中TD表示促销,BR表示地点,数字表示日期,其余为随机数 我的问题是,在将代码输入数据库之前,我想检查该代码的日期和地点是否已经存在,因为不应该允许他们输入来自同一地点和日期的代码 我假设它是一个循环中的某个东西,就像我已经做过的那样:Php 比较从mySql查询返回的字符串,php,mysql,string,Php,Mysql,String,我正在从数据库中查询大量代码,在用户可以向数据库中输入其他代码之前,需要进行一些验证 示例代码如下所示: TD-BR-010212-xxxxxxxx 其中TD表示促销,BR表示地点,数字表示日期,其余为随机数 我的问题是,在将代码输入数据库之前,我想检查该代码的日期和地点是否已经存在,因为不应该允许他们输入来自同一地点和日期的代码 我假设它是一个循环中的某个东西,就像我已经做过的那样: $location_part_of_td = $code[2].$code[3]; $date_part_of
$location_part_of_td = $code[2].$code[3];
$date_part_of_td = $code[4].$code[5].$code[6].$code[7].$code[8].$code[9];
$trade_day_result = mysql_query('SELECT * from wp_scloyalty WHERE promotion_type = trade-day') or die(mysql_error()); // Pulls all trade day codes from the database and checks the date part of the code.
// the date part exists with the same area part, user cant redeem.
while($info = mysql_fetch_array( $trade_day_result ))
{
$code = $info["product"];
}
但是我只是不确定检查字符串的最佳方法。您可以使用类似MySQL的子句在数据库中获取与代码相似的条目 例如:
$code_exists = mysql_query(
"SELECT 'a' FROM table_name WHERE column_name LIKE 'TD-BR-010212-%'"
);
if(mysql_num_rows($code_exists) > 0) {
// The specified place/date is taken
} else {
// No promotion at place BR on the specified date.
}
“%”在类似SQL的子句中用作通配符。解决此问题有两种方法。假设您有权更改表 将唯一约束添加到两列的表基 或者选择所有的位置和日期,查看是否返回任何结果。 SQL:
从表中选择COUNT(*)作为计数器,其中列='TD-BR-010212-%'
并检查计数器返回值是否大于0 我会在SELECT和pull条目中使用LIKE语句,它们以相同的促销、地点和日期开头。不幸的是,我不知道你的桌子是什么样子,所以请容忍我:
$promo_query = "SELECT * FROM wp_sclocalty WHERE column_name LIKE 'TD-BR-010212-%'";
$promo_result = mysql_query($promo_query);
if(mysql_num_rows($promo_result) == 0) {
// the promo code has NOT been used
} else {
// the promo code HAS been used
}
如果可以,在保存每行中的数据时,如果将代码拆分为不同的字段,将获得更好的性能和更容易的编码。这样,您就可以编写专门检查代码各部分组件值的查询,甚至可以在数据库中设置规则(如UNIQUE),以确保某些部分保持唯一性 具体来说,我建议:
create table your_table (
[... your other columns ...]
promotion char(2),
place char(2),
pr_date date,
pr_ident varchar(50)
)
您的第一行是([…]、'TD'、'BR'、'2012-01-02、'xxxxxxxx')。而且查询不需要解包格式化字符串——您可以说“wherepromotion='TD'和placein('BR','XX')…”。简单,嗯?试试这个查询
$part_code=substr($code, 0)
$records =mysql_query("select id from tableName where SUBSTRING(code,1,12)= $part_code");
if(mysql_num_rows($records) > 0)
{
// Duplicate exit
}
else
{
// insert code in DB
}
如果它以地点和日期开头,你就可以创建一个带有前缀的唯一索引。谢谢你的回复。正是出于这个原因,我已经制作了一个促销类型的专栏,但没有其他专栏。好主意,我试试看。