客户可以拥有3个不同的电话号码,我想根据阵列电话中的号码从数据库中检索这些号码。
function statsUserRing($phone, $link)
{
$i = 0;
$p1 = preg_replace( '/[^0-9]/', '', $phone[0]);
$p2 = preg_replace( '/[^0-9]/', '', $phone[1]);
$p3 = preg_replace( '/[^0-9]/', '', $phone[2]);
while($get_stats = $link->get_object("SELECT REPLACE(telnr,'-', '') as telnr FROM ringupp WHERE telnr LIKE '%$p1%' OR telnr LIKE '%$p2%' OR telnr LIKE '%$p3%'"))
{
$i++;
}
return $i;
}
我正在尝试注册有2个电话号码的客户。所以我的数组包含2个值,即这些数字。
这两个数字在我的ringupp表中出现了16次,但是当我运行上面的代码时,它将它计为204154.为什么?
答案 0 :(得分:1)
您只能使用SQL实现此目的:
SELECT REPLACE(telnr,'-', '') as telnr
FROM ringupp
WHERE (telnr LIKE '%$p1%' AND '$p1' <> '')
OR (telnr LIKE '%$p2%' AND '$p2' <> '')
OR (telnr LIKE '%$p3%' AND '$p3' <> '');
答案 1 :(得分:0)
您需要检查空值并根据以下内容为查询添加条件:
$query = "SELECT REPLACE(telnr,'-', '') as telnr FROM ringupp";
if($p1 != null)
$conditions = "telnr LIKE '%$p1%'";
if($p2 != null)
if($conditions != "")
$conditions = $conditions + " OR ";
$conditions = $conditions . "telnr LIKE '%$p2%'";
if($p3 != null)
if($conditions != "")
$conditions = $conditions . " OR ";
$conditions = $conditions . "telnr LIKE '%$p3%'";
if($conditions != "")
$query = $query . " WHERE " . $conditions + ";"
答案 2 :(得分:0)
这是一种检查空值并动态构造SQL查询的方法:
function statsUserRing($phone, $link)
{
$i = 0;
$count = 0;
$p[0] = preg_replace( '/[^0-9]/', '', $phone[0]);
$p[1] = preg_replace( '/[^0-9]/', '', $phone[1]);
$p[2] = preg_replace( '/[^0-9]/', '', $phone[2]);
foreach ($p as $k => $v){
if (!empty($v)){
if ($count > 0){
$wherelogic .= "OR telnr LIKE '%$v%' ";
} else {
$wherelogic .= "telnr LIKE '%$v%' ";
}
$count++;
}
}
$sql = "SELECT REPLACE(telnr,'-', '') as telnr FROM ringupp WHERE ".$wherelogic;
while($get_stats = $link->get_object($sql))
{
$i++;
}
return $i;
}