The customers can have 3 different phone numbers, and I want to retrive these from the database, based on the numbers in my array phone.
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;
}
Im trying with a customer that have 2 phone numbers registred. So my array contains 2 values, which is these numbers.
Those 2 numbers appears 16 times in my ringupp table, but when I run my code above, it counts it to 204154. Why?
You can achieve this using only 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' <> '');
You need to check for nulls and add the conditions to your query based on that:
$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 + ";"
Here's an approach that checks for empty values and constructs a SQL query dynamically:
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;
}