Active Record WHERE Query not getting a field - php

I am trying a "Keyword" search. I am looking in the fields ARTWORK_title and ARTWORK_keywords. The ARTWORK_keywords field is where the user can enter multiple tags to search on.
I have built a query up and feel this is the right way, But I am just not getting ARTWORK_title passed back through in the DB Query.
My PHP Function is as follows....
$my_keywords = explode(",", $search_string);
$searchfields = array('ARTWORK_title', 'ARTWORK_keywords');
$this->db->select('*');
$this->db->from('artwork');
$this->db->where('ARTWORK_status', '1');
//$where_string = '(';
foreach($my_keywords as $keyword)
{
foreach($searchfields as $field)
{
$where_string = $field . ' LIKE \'%' . $keyword . '%\' ';
}
//$where_string .= substr($where_string, 4) . ')';
$this->db->where($where_string);
}
However when profiling the SQL Query I am getting the following MySQL Query back....
SELECT *
FROM (artwork)
WHERE ARTWORK_status = '1'
AND ARTWORK_keywords LIKE '%Blue%'
AND ARTWORK_keywords LIKE '%Orange%'
It is just not getting the ARTWORK_title field in the query at all.
Any ideas where I am going wrong?
Many Thanks in advance.

You are erasing the $where_string value with each iteration.
Modify it like this:
$where_string = '';
$counter = 0;
foreach($my_keywords as $keyword)
{
foreach($searchfields as $field)
{
if ($counter > 0) {
$where_string .= ' AND ';
}
$where_string .= $field . ' LIKE \'%' . $keyword . '%\' ';
$counter++;
}
}

Related

Explode function or from other reasons?

I have a code in php it takes a well formatted string such as 'field,operator,value' and produces a WHERE statment to MySQL database query.
if the two fields names below end with the same characters such as 'id' like 'id' and 'classid' it produces strange behavior. such as the following test.php file:
<?php
$where = $_GET['where'];
$tokens = multiexplode(array("^", "~", "(", ")"), $where);
$where= str_replace("~"," OR ",$where);
$where = str_replace("^", " AND ", $where);
foreach ($tokens as $item) {
if (!empty($item)) {
$where = str_replace($item, getOperand($item), $where);
}
}
echo 'WHERE '.$where;
function multiexplode($delimiters, $string)
{
$unifydelimters = str_replace($delimiters, $delimiters[0], $string);
$conditions = explode($delimiters[0], $unifydelimters);
return $conditions;
}
function getOperand($item)
{
$extokens = explode (",", $item);
switch (trim($extokens[1])) {
case 'eq':
return trim($extokens[0]) . " = '" . trim($extokens[2]) . "' ";
break;
case 'neq':
return trim($extokens[0]) . " != '" . trim($extokens[2]) . "' ";
break;
default:
return "";
break;
}
}
If you test it in the browser like this:
http://localhost/test/test.php?where=id,eq,1^classid,eq,1X
Where X is any number from 0 to infnity it will echo the following line:
note that both fields id and classid end with 'id'
id = '1' AND classid='1' X
But if tested with the following urls it works fine:
http://localhost/test/test.php?where=id,eq,1^classid,eq,MX where M>1 and X is any number
http://localhost/test/test.php?where=id,eq,1^class,eq,1X , X is any digit
http://localhost/test/test.php?where=id,neq,1^classid,eq,1X,, X is any digit
Any idea why this is happenning??
Thanks,

unable to generate multiple random words at a time using order by rand using php mysql

Hi friends am trying to produce random words using order by rand but unable to produce.Here is my code
for($i=0;$i< 10;$i++) {
$result = mysqli_query($conn,"SELECT * FROM questions ORDER BY RAND() LIMIT 2");
if (!$result) {
/*die('Invalid query: ' . mysql_error());*/
die("Query failed".mysqli_error());
}
while ($row = mysqli_fetch_array($result)) {
$meta_descriptions = '{' $row['fact'] . ' ' . '|' $row['fact'] . '|' . $row['fact']}';
echo $meta_descriptions;
}
}
My questions table has one column that is column fact. i t has three values like
apple
ball
cat
Am getting output as
ball |ball| ball only
I want it to be random like
ball|cat|apple
How can I generate it
See this statement inside your while() loop,
$meta_descriptions = '{' $row['fact'] . ' ' . $row['fact'] . '}';
You're using same column value two times in each iteration of while() loop. Simply change your while() code section in the following way,
$meta_descriptions = '';
while ($row = mysqli_fetch_array($result)) {
$meta_descriptions .= $row['fact'] . '|';
}
$meta_descriptions = rtrim($meta_descriptions, '|');
echo $meta_descriptions;
Alternative method:
Create an empty array in the beginning. In each iteration of while() loop, push $row['fact'] value to this array. And finally apply implode() function on this array to get the desired result.
So your code should be like this:
$meta_descriptions = array();
while ($row = mysqli_fetch_array($result)) {
$meta_descriptions[] = $row['fact'];
}
$meta_descriptions = implode('|', $meta_descriptions);
echo $meta_descriptions;
change inside your while loop.
$meta_descriptions = '{';
$descriptions = array();
while ($row = mysqli_fetch_array($result)) {
$descriptions[] = $row['fact'];
}
$meta_descriptions .= implode(" | ",descriptions);
$meta_descriptions .= '}';
echo $meta_descriptions;

PDO: UPDATE not working

I wrote some code to update a mySQL table via php/PDO.
But it is not working and I just can't figure out where my mistake is.
The execute() returns true, but the changes never actually show up in the table.
My code looks pretty much like this:
$columnObject = array(
"emailAddress"=>"aaa#aaa.com",
"passwordHash"=>"56bj5g63j4g57g567g5k75jh7gk4g74j5hg67",
"name"=>"qweqweqwe",
"lastActivity"=>4128649814
);
$knownColumnName = "emailAddress";
$knownColumnData = "aaa#aaa.com";
foreach ($columnObject as $columnName => $columnData) {
$pdoUpdateString .= $columnName . "=:" . $columnName . ",";
$pdoExecuteObject[$columnName] = $columnData;
}
$pdoUpdateString = rtrim($pdoUpdateString, ",");
$pdoExecuteObject['knownColumn'] = $knownColumnData;
$q = $this->hCon->prepare('UPDATE ' . $this->name . ' SET ' . $pdoUpdateString . ' WHERE ' . $knownColumnName . '=:knownColumn');
$q->execute($pdoExecuteObject);

How can I use the '%' wildcard with a LIKE statement in PDO SQL?

I have been trying for a while now to get my code to query my MYSQL database for blog post tags, unsucessfully. This is the code in its current form:
$tags = explode(", ", $filter);
$insert = "";
foreach ($tags as $key => $tag) {
if ($key === 0) {
$insert .= "where tags like :tag_{$key}";
}
else {
$insert .= " or tags like :tag_{$key}";
}
}
$query = $inDatabase->prepare("select * from blog_posts
{$insert}
order by :order");
foreach ($tags as $key => $tag) {
$query->bindParam("tag_{$key}", '%' . $tag . '%');
}
$query->bindParam(":order", $order);
$query->execute();
return $query->fetch(PDO::FETCH_ASSOC);
I have tried:
$query->bindParam("tag_{$key}", "%$tag%");
$insert .= "where tags like '%' || :tag{$key} || '%'
$insert .= "where tags like %?%"; [...] $query->bindParam($key, $tag);
but all with no luck, I keep getting this error: Cannot pass parameter 2 by reference, and always ocurrs on the line where the tag parameters are bound to their corresponding variables (e.g., $query->bindParam("tag_{$key}", '%' . $tag . '%');).
Any ideas?
Just change bindParam to bindValue. That's what error message telling you.

How to avoid repetition of one of several items in array (category name)

I know there are similar questions here and I have read some of the posts and answers, experimented with some of them, but whether it is my limited knowledge of PHP or the peculiarity of my case, I need to ask this.
I am building a dictionary (id, english, bulgarian, theme_id) and would like to group the search results according to theme_id. I am using ORDER BY theme_id, id in my query but I end up displaying the theme with each of the results, while I would like to categorize them as follows:
THEME 1
- result 1
- result 2
THEME 2
- result 3
- result 4
.....
Here is the relevant part of my code:
while($row = mysql_fetch_array($result)) {
//$id = $row['id'];
$english = $row['english'];
$bulgarian = $row['bulgarian'];
$theme_id = $row['theme_id'];
$theme_name = "theme_".$lang;
$theme_query= mysql_query("SELECT theme_id,".$theme_name." FROM ".DICTIONARY_THEMES." WHERE theme_id = ".$theme_id."");
$theme_row = mysql_fetch_array($theme_query);
$theme = $theme_row[$theme_name];
if($source == "english") {
foreach($keywords as $keyword) {
$english = preg_replace("|($keyword)|Ui", "<span style=\"color:#780223\">".$keyword."</span>", $english);
}
$print .= "<li class=\"results-row\">".$theme.": ".$english." = ".$bulgarian."</li>";
}
elseif($source == "bulgarian") {
foreach($keywords as $keyword) {
$bulgarian = preg_replace("|($keyword)|Ui", "<span style=\"color:#780223;\">".$keyword."</span>", $bulgarian);
}
$print .= "<li class=\"results-row\">".$theme.": ".$bulgarian." = ".$english."</li>";
}
}//end while
EDIT: SOLVED, a friend has helped improve my code.
while($row = mysql_fetch_array($result)) {
$english = $row['english'];
$bulgarian = $row['bulgarian'];
$theme_id = $row['theme_id'];
$theme_name = "theme_".$lang;
$theme_query= mysql_query("SELECT theme_id,".$theme_name." FROM ".DICTIONARY_THEMES." WHERE theme_id = ".$theme_id."");
$theme_row = mysql_fetch_array($theme_query);
$theme = $theme_row[$theme_name];
// add all results to an array
$results[] = array(
'english' => $english,
'bulgarian' => $bulgarian,
'theme' => $theme
);
}//end while
$theme = null;
foreach ($results as $result) {
if ($theme != $result['theme']) {
$theme = $result['theme'];
$print .= "<h3>" . $result['theme'] . "</h3>";
}
if ($source == "english") {
foreach ($keywords as $keyword) {
$result['english'] = preg_replace("|($keyword)|Ui", "<span style=\"color:#780223\">" . $keyword . "</span>", $result['english']);
}
$print .= "<li class=\"results-row\">" . $result['english'] . " = " . $result['bulgarian'] . "</li>";
} elseif ($source == "bulgarian") {
foreach ($keywords as $keyword) {
$result['bulgarian'] = preg_replace("|($keyword)|Ui", "<span style=\"color:#780223;\">" . $keyword . "</span>", $result['bulgarian']);
}
$print .= "<li class=\"results-row\">" . $result['bulgarian'] . " = " . $result['english'] . "</li>";
}
}
Based on your code, you should first add all items to an array and afterwards print that array in a separate function/block.
Right after your second MySQL query, put something like
$output[$theme_id] = mysql_fetch_array( $theme_query );
and move all the following code out of the outer result-while-loop (while($row = mysql_fetch_array($result))).
But in fact I would try to put a MySQL query together, to have an ordered, grouped result with all the selected themes in all languages and without querying the database inside a loop.
Or you use something existing, for example this singleton Lexicon class.

Categories