John Davidson

php - Problem adding operator condition to the string

0 comments
Message:


I need to add AND or OR in-between my Query string. My conditions are as follows:


first case:


$array = [
"month" => "October",
"year" => 2020,
"information => "October 2020"
];

In this case, i need


"(MONTH(b.day) = 'October' AND YEAR(b.day) = '2020') OR b.information LIKE '%October 2020%'"


second case:


$array = [
"month" => "October",
"information => "October 2020"
];

In this case, i need


"(MONTH(b.day) = 'October') OR b.information LIKE '%October 2020%'"


I have tried following lines of code but I couldn't fix the AND OR in correctly.


    $whereStr = '';
$alias = "b.";
$orCounter = 0;
$andCounter = 0;
$dateMonth = false;

if (array_key_exists('year', $array) && array_key_exists('month', $array)) {
$dateMonth = true;
}

foreach ($array as $key => $value) {
if (0 !== $orCounter) {
$whereStr .= ' OR ';
} elseif ($andCounter > 0 && true === $dateMonth) {
$whereStr .= ' AND ';
}

if ('month' === $key || 'year' === $key) {
++$andCounter;
echo $andCounter;
$whereStr .= strtoupper($key) . '(' . $alias . 'day' . ')';
$whereStr .= "= '$value'";

if ($andCounter === 2) {
++$orCounter;
}

continue;
}

if ('type' === $key) {
$whereStr .= "$alias$key IN ($value)";
continue;
}
$whereStr .= "$alias$key LIKE '%$value%'";
++$orCounter;
}

Can anybody please help me fix this?



My Answer:
'age > 18',
'gender = "male"',
'city = "New York"'
];

$query = implode(' AND ', $array);

echo $query;

// Output: age > 18 AND gender = "male" AND city = "New York"

_second case:_

$array = [
'name = "John"',
'email = "john@example.com"',
'phone = "1234567890"'
];

$query = implode(' OR ', $array);

echo $query;

// Output: name = "John" OR email = "john@example.com" OR phone = "1234567890"

Rate this post

3 of 5 based on 9602 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us