I want to set the conditionally Order_BY in rest API
e.g("B" comes before "A"and "D" comes before "C" means the out put is appear like this "BADC")
please help me if it is possible
$get_entry_list_parameters = array(
//session id
'session' => $session_id,
//The name of the module from which to retrieve records
'module_name' => 'Accounts',
//The SQL WHERE clause without the word "where".
'query' => $query,
//The SQL ORDER BY clause without the phrase "order by".
'order_by' => " How to set Conditional Order By "
);
I guess BADC that you mentioned is column's name.
That should be done with some code like this:
<?php
$order_by = $_POST['order_by']; // order_by's format is like this: B:asc;A:asc;D:desc;C:desc;
$order_by_str = ""; // to store a query statement for 'order by'
$order_by_array = explode(';', $order_by);
foreach ($order_by_array as $order_item) {
$order_item_array = explode(':', $order_item);
$order_by_str .= "," . $order_item_array[0] . " " . $order_item_array[1];
}
$order_by_str = substr($order_by_str, 1); // result for order_by
This is a known bug.
There is a bug report with a proposed fix here Defect 66206: REST V4_1 API,function get_entry_list didn't work with the order_by attribute
Applying the proposed fix worked for me.
Related
I have an associative array as follows:
$ a =
[
"2023-05-18" => 10.0
"2023-07-14" => 2.0
"2023-11-01" => 16.0
"2023-11-11" => 2.0
"2023-12-25" => 8.0
"2024-01-01" => 2.0
"2024-04-01" => 22.0
]
And in a SQL query i want to do something like:
function ($a) {
$sql = " ... some code before ...
IF (table.date IN ($a), value of date (ex 10.0), 1)
"
;
}
Not only with if with case when, or whatever the idea is to get the value in associative array according to the date (if it exist in the array);
I think the better way to do that is to concatenate the logic with your query and use a case when to handle that. something like
$s= "*\nCASE\n";
foreach ($yourArray as $dateKey => $dateValue) {
$s .= "WHEN DATE_FORMAT(table.date, '%Y-%m-%d') = '" . $dateKey . "' THEN
" . $dateValue . " \n"
;
}
$s .= "END\n";
And in you query you can directly do something like
"query do something
". $s ."
do something again "
I hope this would help
Your description of what you want is not very clear, but from the conversation and a bit of assumption I think it probably boils down to:
"list all the values from the PHP array where the date key matches at least one row from the SQL table"
If so, then here's one way you could do it:
Run a query which returns a distinct list of dates from the table where the date matches one of the keys in the array. This effectively gives you a list of dates which appear in both the array and the database.
Loop through that list to show the values matching those array keys.
Now here's some sample code. There may be a more efficient way to do it, but this is my initial thought:
$a =
[
"2023-05-18" => 10.0,
"2023-07-14" => 2.0,
"2023-11-01" => 16.0,
"2023-11-11" => 2.0,
"2023-12-25" => 8.0,
"2024-01-01" => 2.0,
"2024-04-01" => 22.0
];
$dates = array_keys($a);
$params = array_fill(0, count($dates), "?");
//sql to get all rows from database which match dates in the array
$sql = "SELECT `date` from `table` WHERE `date` IN (".implode(",", $params).")";
echo $sql; //just for debugging
//let's assume you're using PDO and have a connection object named $pdo, for the sake of argument
$stmt = $pdo->prepare($sql);
$result = $pdo->execute($dates);
$data = $result->fetchAll(PDO::FETCH_ASSOC);
//loop the returned set of matching dates
foreach ($data as $row)
{
//output values from the original array which match the dates returned from the database
echo $a[$row["date"]].PHP_EOL;
}
Related documentation:
https://www.php.net/manual/en/function.array-keys.php
https://www.php.net/manual/en/function.implode.php
https://www.php.net/manual/en/function.array-fill.php
I am trying to expand the functionality of a dictionary I am building by showing definitions for some of the terms (if a definition exists).
I take the data from the two tables as follows:
$query = $db->query("SELECT * FROM ".DICTIONARY_TABLE." " .
"LEFT JOIN ".DICTIONARY_DEFINITIONS." ON ".DICTIONARY_TABLE.".id = ".DICTIONARY_DEFINITIONS.".term_id ".
"WHERE ".DICTIONARY_TABLE.".".$source." LIKE '%".$keyword."%' ".
"AND ".DICTIONARY_TABLE.".theme_id = ".$selected_theme_id." ".
"ORDER BY ".DICTIONARY_TABLE.".id");
After that, in the while loop, I first get the theme name (from another table), then add the query results to an array:
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
// get theme name
$theme_name = "theme_".$lang;
$theme_query= $db->query("SELECT theme_id,".$theme_name." FROM ".DICTIONARY_THEMES." WHERE theme_id = ".$theme_id."");
$theme_row = $theme_query->fetch(PDO::FETCH_ASSOC);
$theme = $theme_row[$theme_name];
// add all results to an array
$results[] = array(
'english' => $row['english'],
'bulgarian' => $row['bulgarian'],
'english_abbr' => $row['english_abbr'],
'bulgarian_abbr' => $row['bulgarian_abbr'],
'theme' => $theme
);
After that, I try to check if the LEFT JOIN has actually returned any results from the definitions table, and if yes, add those to the array as well - but this is where I fail...
// check if definition exists for this term
if(isset($row['bulgarian_definition'])) {
array_push($results['bulgarian_definition'], $row['bulgarian_definition']);
}
if(isset($row['english_definition'])) {
array_push($results['english_definition'], $row['english_definition']);
}
I've tried all ways I could find to first check if the variables have been defined, and then push them to the $results array. Nothing works.
I don't seem to be able to successfully find out of english_definition and/or bulgarian_definition are set. When I run the query itself in PhpMyAdmin, it works just fine.
The only "solution" I can think of is to scrap the idea of having a separate table for the definitions and just expand the main table, but that's not a great approach I know.
Any insight as to what I am doing wrong will be greatly appreciated. Thanks!
EDIT: I've changed the way elements are added to the array:
// check if definition exists for this term
if(isset($row['bulgarian_definition'])) {
$results['bulgarian_definition'] = $row['bulgarian_definition'];
}
if(isset($row['english_definition'])) {
$results['english_definition'] = $row['english_definition'];
}
And this now does the trick. When I dump the $results array outside of the while loop, both definitions have been added.
However, I now get a large number of Warning: Illegal string offset 'theme' in... and 'english' and 'bulgarian' - this happens below, when I run the $results array in a foreach loop to start printing them:
foreach($results as $result) {
if($theme != $result['theme']) {
$theme = $result['theme'];
$search_results .= "<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']);
}
No idea yet why this happens, will keep looking.
SECOND EDIT: Decided to put the two definitions directly inside the $results array as follows:
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
// get theme name
$theme_name = "theme_".$lang;
$theme_query= $db->query("SELECT theme_id,".$theme_name." FROM ".DICTIONARY_THEMES." WHERE theme_id = ".$theme_id."");
$theme_row = $theme_query->fetch(PDO::FETCH_ASSOC);
$theme = $theme_row[$theme_name];
// add all results to an array
$results[] = array(
'english' => $row['english'],
'bulgarian' => $row['bulgarian'],
'english_abbr' => $row['english_abbr'],
'bulgarian_abbr' => $row['bulgarian_abbr'],
'theme' => $theme,
'bulgarian_definition' => $row['bulgarian_definition'],
'english_definition' => $row['english_definition']
);
}// end while
This now works just fine. When I dump the array, if no definition exists, I have 'english_definition' => null and if a definition exists, it's there. So far so good.
The new problem is that I can no longer group the results by theme - the theme of the last result found is shown. Which is a different problem altogether. What really irks me is that before I added the definitions, everything worked just fine. You can the working website here.
PROBLEM SOLVED!
Decided against pushing values to the array (as shown above).
Got rid of the extra query within the while loop that gets the theme's name, moving it instead to the query that performs the search. Thus the query itself is:
$query = $db->query("SELECT * FROM ".DICTIONARY_TABLE." " .
"JOIN ".DICTIONARY_THEMES." ON ".DICTIONARY_TABLE.".theme_id = ".DICTIONARY_THEMES.".theme_id ".
"LEFT JOIN ".DICTIONARY_DEFINITIONS." ON ".DICTIONARY_TABLE.".id = ".DICTIONARY_DEFINITIONS.".term_id ".
"WHERE ".DICTIONARY_TABLE.".".$source." LIKE '%".$keyword."%' ".
"ORDER BY ".DICTIONARY_TABLE.".theme_id, ".DICTIONARY_TABLE.".id");
And the while loop is:
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$theme_name = "theme_".$lang;
// add all results to an array
$results[] = array(
'english' => $row['english'],
'bulgarian' => $row['bulgarian'],
'english_abbr' => $row['english_abbr'],
'bulgarian_abbr' => $row['bulgarian_abbr'],
'theme' => $row[$theme_name],
'bulgarian_definition' => $row['bulgarian_definition'],
'english_definition' => $row['english_definition']
);
}// end while
The website link from above will now load the upgraded search functionality, where definitions will be shown (if they exist). One example word for anyone curious is "worm".
As it turns out, sometimes all it takes to fix a problem is to show it to people and then start thinking about it, as sometimes the solution is right in front of you. Thanks to all who participated!
EDITED: Deleted previous answer since it was incorrect. Will update this answer once I have a solution to the problem. Have not deleted this answer since I haven't found the option that does so. Though sometimes it is fun to take up space and feel important :), don't hate the player, hate the game.
A logged in user fills out a form several times. From his entries, I'm attempting to get all of his inputs for a specific field and put them into a PHP array.
For the sake of simplicity, assume the form has ID 10 with the first field called 'SomeField' and the user was logged in (and is still logged in) for all entries.
Here's my best attempt at creating an array of all SomeField entries from the user:
get_currentuserinfo();
$searchCriteria = array(
array(
'key' => 'created_by',
'value' => $current_user->user_login
),
array(
'key' => '1',
'value' => 'SomeField'
),
);
$form = GFAPI::get_entries( 10, $searchCriteria );
echo print_r($form);
Unfortunately, this print_r appears to display an empty array. I believe my searchCriteria is somehow incorrect.
I found it's easier to omit the second parameter ($searchCriteria) and simply use $form[0]['1'] for example which will display the first field of the first entry of the specified form.
I found with user23058230 great solution in the second answer I always got the latest form created, which worked well for new signups but not later on.
Assuming here that the form ID is number 1, you can search it with a for loop using the entry_id which is available in the user's login array as
$current_user->entry_id
No search query is needed other than the form you want returned - in this case form #1.
You can search other items using the keys you can see from your array dump.
Great solution which with the addition of this code solved my problem.
$form = GFAPI::get_entries( 1, '');
$what_i_want = 0;
for( $i = 0; $i < count($form); $i++ ){
if( $form[$i]['id'] == $current_user->entry_id ){
// the item I want
$what_i_want = $form[$i]['22'];
//echo " I " . $form[$i]['id'] . " F " . $form[$i]['22'] . " i " . $i . " T " . $what_i_want . '<br />';
break;
}
}
I have a members site where users are given up to 7 web page templates to display their products on. Each template has the same field names, differentiated by _1, _2... _7 at the end of each.
For example:
// Template 1 would have the following list of variables
product_name_1
product_descript_1
product_color_1
product_price_1
// Template 2 would have the following list of variables
product_name_2
product_descript_2
product_color_2
product_price_2
// through Template 7
I am able to display any variables for a specific user within a web page, by use of a query string identifying their user_id in the url, ie
http://domain.com/folder/page.php?id=78
I then $_Get any variable by simply identifying it in the PHP file, ie
$product_name_1
$product_descript_1
$product_color_1
$product_price_1
My problem is that the url must identify WHICH template, since each template identifies a specific product, ie _1, _2, ..._7. How do I use a parameter in the url, such as
http://domain.com/folder/page.php?id=78¶meter=_7
...to identify all variables ending with _7, which would appear in the web page? The parameter used in the url would identify the variables to be used in the web page, whether _1, _2, etc.
UPDATE
I have tried the various answers with only partial success, ie "Array_x" is displayed when using any particular variable along with the suggested code. There may be a conflict with the rest of the code I'm using in page.php, as follows:
$db_connection = new mysqli("", "", "");
if ($db_connection->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$id = $_GET['id'];
$query = mysql_query("SELECT * FROM table_name WHERE id = '$id' LIMIT 1") or die(mysql_error());
$row = mysql_fetch_object($query);
$prop_address=array(
"_1"=>"prop_address_1",
"_2"=>"prop_address_2",
"_3"=>"prop_address_3"
//Through to Temp 7
);
$prop_address{$_GET['parameter']}=$row->prop_address;
echo " $prop_address{$_GET['parameter']} ";
"Array_x" displays (where x=1, 2, 3, etc is used as the parameter in url, ie http://domain.com/page.php?id=72¶meter=1), instead of the actual value held in the database table for $product_name{$_GET['parameter']}. For some reason, the code is not picking up the value of the variable from the database table.
Would it be possible to use arrays so...
$product_name=array(
"1"=>"Product name for template 1",
"2"=>"Product name for template 2"
//Through to Temp 7
);
echo $product_name[$_GET["parameter"]];
You could then do the same for the other variables.
You could fill each array by doing something like:
$row = mysql_fetch_object($query);
$product_name[$_GET['parameter']]=$row->product_name;
echo $product_name[$_GET['parameter']];
I may be missing something...
$_GET['parameter'] = '_2';
$product_name{$_GET['parameter']} = 'string';
echo $product_name_2; // string
or
$_GET['parameter'] = '_2';
$var = 'product_name'.$_GET['parameter'];
$$var = 'string';
echo $product_name_2; // string
Personally, I would use array's for this type of behavior.
Update:
Although the above works and tested ok, it is a lot more work than anyone would probably desired.
In lieu of simplicity, I would suggest the approach via array's.
$templates = array(2 => array(
'product_name' => "value",
'product_descript' => "value",
'product_color' => "value",
'product_price' => "value",
);
foreach($templates[substr($_GET['parameter'],1)] as $var => $val){
$variable = $var.$_GET['parameter'];
$$variable = $val;
}
The above is backwards compatible, it uses substr to remove the leading _ from your parameter.
I couldn't get any of the answers given to work. I found an example given by a user for php variable variables in the PHP manual here and found it to work. I incorporated it into my code as follows:
$id = $_GET['id'];
$query = mysql_query("SELECT * FROM table_name WHERE id = '$id' LIMIT 1") or die(mysql_error());
$row = mysql_fetch_object($query);
for( $i = 1; $i < 8; $i++ )
{
$product_name[$_GET['parameter']] = "product_name_" . $i;
$product_descript[$_GET['parameter']] = "product_descript_" . $i;
$product_color[$_GET['parameter']] = "product_color_" . $i;
$product_price[$_GET['parameter']] = "product_price_" . $i;
}
${$product_name[1]} = "$row->product_name_1";
${$product_name[2]} = "$row->product_name_2";
${$product_name[3]} = "$row->product_name_3";
${$product_name[4]} = "$row->product_name_4";
${$product_name[5]} = "$row->product_name_5";
${$product_name[6]} = "$row->product_name_6";
${$product_name[7]} = "$row->product_name_7";
// List 7 variables and values for each field name
echo "${$prop_name[$_GET['par']]}";
The only problem is that mysql injection is possible with this code. If anyone could suggest a solution, I would greatly appreciate it.
Can someone give me an example of how I would delete a row in mysql with Zend framework when I have two conditions?
i.e: (trying to do this)
"DELETE FROM messages WHERE message_id = 1 AND user_id = 2"
My code (that is failing miserably looks like this)
// is this our message?
$condition = array(
'message_id = ' => $messageId,
'profile_id = ' => $userId
);
$n = $db->delete('messages', $condition);
Better to use this:
$condition = array(
'message_id = ?' => $messageId,
'profile_id = ?' => $userId
);
The placeholder symbols (?) get substituted with the values, escapes special characters, and applies quotes around it.
Instead of an associative array, you should just be passing in an array of criteria expressions, ala:
$condition = array(
'message_id = ' . $messageId,
'profile_id = ' . $userId
);
(and make sure you escape those values appropriately if they're coming from user input)
Use this , it is working...
$data = array(
'bannerimage'=>$bannerimage
);
$where = $table->getAdapter()->quoteInto('id = ?', 5);
$table->update($data, $where);