Yii2 search model - yii2

On my website, when I search Alex Lau, I will show the result Alex Lau. The problem is how can I modify the code so when I search Lau Alex maybe, It will still show Alex Lau result. Right now it didn't.
$query->orFilterWhere(['like', 'fullname', $this->globalSearch])
Here is the code in my search model.
Please help me with this.
Thank you!

A better approach according to the MYSQL query using CONCAT()like below
if( $this->fullname!== null && $this->fullname !== '' ){
$searchTerms = explode(" ", $this->fullname);
if( sizeof($searchTerms) > 1 ){
$conditions[]='OR';
foreach( $searchTerms as $term ){
$conditions[] = ['like', 'fullname', new \yii\db\Expression('CONCAT(CONCAT("%","' . $term . '"),"%")')];
}
$query->orFilterWhere($conditions);
} else{
$query->orFilterWhere(
['like', 'fullname', new \yii\db\Expression('CONCAT(CONCAT("%","' . $searchTerms[0] . '"),"%")')]
);
}
}
NOTE: This works correctly if you are searching the name in the format first last or first middle last, means you can search Alex Lau John or John Alex Lau Lau John Alex

Try this
$words = explode(' ',$this->globalSearch);
if (count($words) > 1) {
foreach ($words as $word) {
$query->orFilterWhere(['like', 'fullname', $word]);
}
} else {
$query->orFilterWhere(['like', 'fullname', $this->globalSearch]);
}
Note: You need to make sure about white spaces

Related

MYSQL How can I make dropdown list?

I created a new table in workbench where I want to put a season of a soccer championship.
I don't want to write down every time the team's names, can you help me pls, how can I make like a dropdown list (or set of values, what are the only options for that column), when I begin to type "Bay..." its automatically offer "Bayern München" as the only option.
I don't know how much will this help, but I have made a dropdown list for something else and I hope my way might give you an idea:
foreach ($dbo->query($sql) as $row) //Array or records stored in $row
{
if($row[id]==10)
{
echo "<option value=$row[id] selected>$row[name]</option>";
}
else
{
echo "<option value=$row[id]>$row[name]</option>";
}
}
echo "</select>"; // Closing of list box
As the same answer above, but using short-hand ternary operator instead of if-else statement, and don't forget to use ' or " when reference to object string index.
foreach ($dbo->query($sql) as $row) //Array or records stored in $row
{
printf("<option value='%s' %s>%s</option>", $row['id'], $row['id'] == 10 ? 'selected' : '', $row['name']);
}
}
echo "</select>"; // Closing of list box

How to get the name of a course's teacher

Could you help me create a query that shows the teacher(s) of a course
Example:
Title of course: Course 1
Teacher: James Anderson
I have this query:
SELECT DISTINCT ldm_user.id,
ldm_user.firstname,
ldm_user.lastname,
ldm_course.shortname,
ldm_course.fullname,
ldm_role.id as role_id,
ldm_role_assignments.id
FROM ldm_course,ldm_user,ldm_role,ldm_context,ldm_role_assignments
WHERE ldm_course.fullname = "i-ONS001 Taller de Lectura y Redacción IV" and ldm_role_assignments.id = 4
But this is not returning the name of the teacher as expected.
This one is a little old, but I had to spend some time trying to figure it out and thought I would share what I came up with.
The basic PHP below will get the list of users enrolled in the course, comb through them and find any with the "editingteacher" role.
$moodle_site = 'YOUR_MOODLE_URL';
$moodle_token = 'YOUR_MOODLE_TOKEN';
$courseid = 7; // Enter the Moodle course ID you want to find the teacher for
$restformat = 'json';
$params = '';
$functionname = 'core_enrol_get_enrolled_users'; // Make sure function is enabled in Moodle
$serverurl = $moodle_site . '/webservice/rest/server.php' . '?wstoken=' . $moodle_token . '&wsfunction=' . $functionname . '&courseid='.$courseid;
$curl = new curl;
$restformat = ($restformat == 'json') ? '&moodlewsrestformat=' . $restformat : '';
$resp = $curl->post($serverurl . $restformat, $params);
$get_result = json_decode($resp, true);
if (!empty($resp)) {
foreach ($get_result as $array_level1) {
foreach ($array_level1["roles"] as $array_level2) {
if ($array_level2["shortname"]=='editingteacher') {
echo 'Teacher ID: '.$array_level1["id"].'<br>';
echo 'Teacher Name: '.$array_level1["firstname"].' '.$array_level1["lastname"].'<br>';
echo 'Teacher Email: '.$array_level1["email"].'<br>';
}
}
}
} else {
echo 'No users were returned.<br>';
}
Your question is incomplete, because the exact query will vary depending on your version of Moodle, whether you're using SQL or MySQL, and also we can't give you a comprehensive answer without knowing your table structures.
However, in Moodle 2.x you can use an API query (PHP) which looks something like this:
$role = $DB->get_record('role', array('shortname' => 'editingteacher'));
$context = get_context_instance(CONTEXT_COURSE, $courseid);
$teachers = get_role_users($role->id, $context);
and then doing a return $teachers; or echo $teachers; to output said results.
Like I said, without knowing your exact system details I can't give you an accurate response and a functioning query so take that with a pinch of salt; you might need to play around with it to get it to work.
Ref: https://moodle.org/mod/forum/discuss.php?d=115636

Laravel: Querying based on Input. If input is empty, get all

I have a calendar (FullCalendar) where the user can filter down results based on a few params (Tutor Secondary Tutor, Lesson, Location). When the user makes a change to the query it hits the following code.
The issue I am having is the 'OR'. What I really want is an IF input is null then get all.
If User { Get all lessons where lead_tutor_id = 1 and secondary_tutors_id = 1 }
If User and Location { Get lessons where the user is as above, but have location_id = 3 }
etc, etc.
So, is there a way I can fall back to get ALL the results IF only one or two filters are set?
$current_events = Calendar::Where(function($query) use ($start_time, $end_time, $tutor, $location, $lesson)
{
$query->whereBetween('date_from', [$start_time, $end_time])->orderBy('date_from')
->whereRaw('lead_tutor_id = ?
OR secondary_tutors_id = ?
OR location_id = ?
OR lesson_id = ?',
[
$tutor, // Input get() for user
$tutor, // Input get() for user
$location, // Input get() for location
$lesson, // Input get() for lesson
]
);
})->with('lessons', 'leadtutor', 'secondarytutor')->get();
I've been playing with Query Scopes, but this seems to fail if passing a NULL value through to it.
Any help is very much appreciated. Thanks in advance.
You can build the query on forehand, store it in a variable and use it once its build.
$query = isset($var) ? $var : '';
$query .= isset($othervar) ? $othervar : '';
whereBetween(*)->orderBy(*)->whereRaw($query)
Only thing you need to keep in mind is to insert the 'OR's in the right place . So have like a check for wether it is the first thing to be inserted or not, if not then put 'OR' in front of it.
Hope that is enough info to help you.
After the advice from Saint Genius, I have got this working:
$built_query = [];
isset($lead_tutor) ? $built_query['lead_tutor'] = 'lead_tutor_id = ' . $lead_tutor . ' ' : null;
isset($secondary_tutor) ? $built_query['secondary_tutor'] = 'secondary_tutors_id = ' . $secondary_tutor . ' ' : null;
isset($location_id) ? $built_query['location'] = 'location_id = ' . $location_id : null;
isset($lesson_id) ? $built_query['lesson'] = 'lesson_id = ' . $lesson_id : null;
// Flatten the array so we can create a query and add the word ADD in between each element.
$built_query = implode(" AND ", $built_query);
// Run the query
$current_events = Calendar::whereBetween('date_from', [$start_time, $end_time])->orderBy('date_from')->whereRaw($built_query)->with('lessons', 'leadtutor', 'secondarytutor')->get();

using PHP simple html dom get attributes name in span?

I am not if 'tags' are the right term but i have to get the "data-time" values from this span into an array. How can I use simple html dom to get them?
Here is on span I am trying to get the "data-time" out of.
include('../simpleHtmlDom/simple_html_dom.php');
// Put the Twitters username here
$user = "yadayada";
$html = file_get_html("https://twitter.com/$user");
$ret = $html->find('div[class=ProfileTweet-contents]');
$ret = $html->find('p[class=ProfileTweet-text js-tweet-text u-dir]');
/// tries to get the time code but does only gets the span
$date = $html->find('span[class=js-short-timestamp js-relative-timestamp]', 0);
$DoesNotWork = $html->find( "data-time", 0 );
echo $ret[1]; // get's a users tweet.
echo $DoesNotWork;
The result of the date
<span class="js-short-timestamp js-relative-timestamp"
data-time="1401528672"
data-long-form="true">
15h
</span>
I would think it is something like this but this code does not work.
$html->find( "data-time", 0 );
You may try this:
// Include the script
$url = 'https://twitter.com/yourusername';
$html = file_get_html($url);
$dateTimes = array();
foreach ($html->find('div.GridTimeline .js-short-timestamp') as $value) {
$dateTimes[] = $value->innertext;
}
Result of print_r($dateTimes);:
Array
(
[0] => 2h
[1] => 2h
[2] => 2h
// Truncated...
[10] => 11h
[11] => May 30
[12] => May 30
[13] => May 6
// Truncated...
)
I was able to get the date using this code, tho I think there is a better way. I think it would be best to find a simple dom code that gets the text of the date-time in line
<span class"js-short-timestamp js-relative-timestamp" date-time="89393748474">
but instead I used two "list" php lines as seen below and that worked.
$dateTimes = array();
foreach ($html->find('div.GridTimeline .js-short-timestamp') as $value) {
$dateTimes[] = $value->outertext;
}
// These are the lines I get the date-time from.
list($Gone,$Keep) = explode("data-time=\"", $dateTimes[0]);
list($Date,$Gone) = explode("\"", $Keep);
$Date = date('M d, Y', $Date);
You want to use:
$html->find( "[data-time]", 0 );
In case anyone landing here in 2021, following no 1 google search result:
Unless I misinterpreted your intention, you might achieve what you want using (with simplehtmldom):
$html->find('span[data-time]')->attr[data-time];
The official simplehtmldom documentation fails to mention that. However, https://stackoverflow.com/a/14456823/10050838 is one possible source.

how use mysql_data_seek with PDO?

I want use mysql_data_seek with PDO from google search I found that it should looks like this:
$row0 = $result->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, 0);
however it's not work, what I do wrong?
this is my code:
$query = "SELECT name,age FROM users";
$q = $db->prepare($query);
$q->execute();
$q->setFetchMode(PDO::FETCH_ASSOC);
$arrayData = $q->fetchAll();
foreach ($arrayData as $row){
echo $row['name'] ." ";
echo $row['age'] ."<br>";
}
$result = $q->fetch(PDO::FETCH_OBJ,PDO::FETCH_ORI_ABS,4);
var_dump($result);
I just want get the 5th row in object form from the last run query. I don't want run this query again (as some guys told me) I just want the results from sql buffer.
the var_dump result is: bool(false)
any ideas?
EDIT:
thanks for your answers and sorry but maybe I don't explain myself as well. I like the trick with JSON but the point is that the 5th row is example. I just want use the result of the query from the buffer with PDO exactly as I did it with mysql_data_seek in regular mysql (change the cursor). is it possible? I like all the tricks but that not what I look for.
the PDO 'cursor' default is PDO::CURSOR_FWDONLY that means that cursor can't back to zero like it happens with mysql_data_seek to allow cursor back to zero it necessary define use 'scrollable cursor'
example:
$db->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
before use it like this:
$row0 = $result->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, 0);
$result = $arrayData[4];
is all you need.
If you want the 5th row result you can do like this:
$result = json_decode(json_encode($arrayData[4]), FALSE);
var_dump($result);
or something like this:
$object = new stdClass();
foreach ($array as $key => $value)
{
$object->$key = $value;
}
Just curious! why do you need the object form?
EDIT (this will give the object form of the 5th row):
$index = 0;
$fifthRow = new stdClass();
while($row = $q->fetch())
{
if($index++==4)
$fifthRow = json_decode(json_encode($row), FALSE);
}
You could do it like this:
$c = 1;
$saved=null;
while($row = $q->fetch()){
if($c==4){
$saved = clone $row;
};
$c++;
somethingelse;
}
$saved will then contain the 4th element as an object with almost no extra overhead calculations.