How to output records in HTML table from moodle database? - moodle

I want to display data from moodle database in HTML table, but for every record separate table is being displayed:
Code:
$rec=$DB->get_records_sql('SELECT * FROM `mdl_schedules`');
$table = new html_table();
$table->head = array('Date','Time', 'A' , 'B', 'C','D', 'E', 'F');
foreach ($rec as $records) {
$id = $records->id;
$scheduledatet = $records->scheduledate;
$scheduletime = $records->scheduletime;
$session = $records->s;
$venue = $records->v;
$trainer = $records->t;
$category = $records->c;
$course = $records->course;
$link = $records->link;
$table->data = array(array($scheduledatet, $scheduletime, $a,$b,$c,$d,$e,'View'));
echo html_writer::table($table);
}
Any reference or help will be much appreciated.

The echo should be outside the loop :)
}
echo html_writer::table($table);
But you will probably want to use flexible_table instead so you can use pagination.
Have a look in /admin/localplugins.php for an example.

I know this is old, but the reason you're only getting one record is you're not adding to the $table->data array. This is the code you want:
$rec=$DB->get_records('schedules');
$table = new html_table();
$table->head = array('Date','Time', 'A' , 'B', 'C','D', 'E', 'F');
foreach ($rec as $records) {
$id = $records->id;
$scheduledatet = $records->scheduledate;
$scheduletime = $records->scheduletime;
$session = $records->s;
$venue = $records->v;
$trainer = $records->t;
$category = $records->c;
$course = $records->course;
$link = $records->link;
$table->data[] = array($scheduledatet, $scheduletime, $a,$b,$c,$d,$e,'View');
}
echo html_writer::table($table);
I also changed up your query a bit. If you're just getting all of the records from a table, $DB->get_records('TABLE_NAME_WITHOUT_PREFIX'); is the way to go.

Related

How correctly to use the snippet() function?

My first Sphinx app almost works!
I successfully save path,title,content as attributes in index!
But I decided go to SphinxQL PDO from AP:
I found snippets() example thanks to barryhunter again but don't see how use it.
This is my working code, except snippets():
$conn = new PDO('mysql:host=ununtu;port=9306;charset=utf8', '', '');
if(isset($_GET['query']) and strlen($_GET['query']) > 1)
{
$query = $_GET['query'];
$sql= "SELECT * FROM `test1` WHERE MATCH('$query')";
foreach ($conn->query($sql) as $info) {
//snippet. don't works
$docs = array();
foreach () {
$docs[] = "'".mysql_real_escape_string(strip_tags($info['content']))."'";
}
$result = mysql_query("CALL SNIPPETS((".implode(',',$docs)."),'test1','" . mysql_real_escape_string($query) . "')",$conn);
$reply = array();
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$reply[] = $row['snippet'];
}
// path, title out. works
$path = rawurlencode($info["path"]); $title = $info["title"];
$output = '<a href=' . $path . '>' . $title . '</a>'; $output = str_replace('%2F', '/', $output);
print( $output . "<br><br>");
}
}
I have got such structure from Sphinx index:
Array
(
[0] => Array
(
[id] => 244
[path] => DOC7000/zdorovie1.doc
[title] => zdorovie1.doc
[content] => Stuff content
I little bit confused with array of docs.
Also I don't see advice: "So its should be MUCH more efficient, to compile the documents and call buildExcepts just once.
But even more interesting, is as you sourcing the the text from a sphinx attribute, can use the SNIPPETS() sphinx function (in setSelect()!) in the main query. SO you dont have to receive the full text, just to send back to sphinx. ie sphinx will fetch the text from attribute internally. even more efficient!
"
Tell me please how I should change code for calling snippet() once for docs array, but output path (link), title for every doc.
Well because your data comes from sphinx, you can just use the SNIPPET() function (not CALL SNIPPETS()!)
$query = $conn->quote($_GET['query']);
$sql= "SELECT *,SNIPPET(content,$query) AS `snippet` FROM `test1` WHERE MATCH($query)";
foreach ($conn->query($sql) as $info) {
$path = rawurlencode($info["path"]); $title = $info["title"];
$output = '<a href=' . $path . '>' . $title . '</a>'; $output = str_replace('%2F', '/', $output);
print("$output<br>{$info['snippet']}<br><br>");
}
the highlighted text is right there in the main query, dont need to mess around with bundling the data back up to send to sphinx.
Also shows you should be escaping the raw query from user.
(the example you found does that, because the full text comes fom MySQL - not sphinx - so it has no option but to mess around sending data back and forth!)
Just for completeness, if REALLY want to use CALL SNIPPETS() would be something like
<?php
$query =$conn->quote($_GET['query']);
//make query request
$sql= "SELECT * FROM `test1` WHERE MATCH($query)";
$result = $conn->query($sql);
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
//build list of docs to send
$docs = array();
foreach ($rows as $info) {
$docs[] = $conn->quote(strip_tags($info['content']));
}
//make snippet reqest
$sql = "CALL SNIPPETS((".implode(',',$docs)."),'test1',$query)";
//decode reply
$reply = array();
foreach ($conn->query($sql) as $row) {
$reply[] = $row['snippet'];
}
//output results using $rows, and cross referencing with $reply
foreach ($rows as $idx => $info) {
// path, title out. works
$path = rawurlencode($info["path"]); $title = $info["title"];
$output = '<a href=' . $path . '>' . $title . '</a>'; $output = str_replace('%2F', '/', $output);
$snippet = $reply[$idx];
print("$output<br>$snippet<br><br>");
}
Shows putting the rows into an array, because need to lopp though the data TWICE. Once to 'bundle' up the docs array to send. Then again to acully display rules, when have $rows AND $reply both available.

Query each line of a multiple line text area

This fails when dealing with 2n $line when doing a query 'isbn' field. But it works perfectly if I query 'id' field. I have tested data using data strictly from the table. Any idea why is this happening? Or how can I debug this?
$massife = $this->Massives->patchEntity($massife, $this->request->getData());
$massiveTable = \Cake\ORM\TableRegistry::get('MassiveErrors', array('table' => 'massive_errors'));
$lines = explode("\n", $massife->data);
$documents = $this->loadModel('Documents');
foreach($lines as $line){
$document = $documents->find('all')->where(['isbn' => $line]);
$row = $document->first();
$massiveError = $massiveTable->newEntity();
if(!empty($row)){
$massiveError->document_id = $row->id;
$massiveTable->save($massiveError);
}
Should be using:
preg_split('/\r\n|\r|\n/',$massife->data)
instead of:
explode("\n", $massife->data)

Returning an array using PDO

I'm trying to use PDO using the following code, I want to select the array of values for the context_list, but it returns one record, any ideas where I'm going wrong?
try {
$sql2 = "SELECT area_easting, area_northing, context_number FROM excavation.contexts";
$sth = $conn->prepare($sql2);
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC))
{
$easting_list = $row['area_easting'];
$northing_list = $row['area_northing'];
$context_list = $row['context_number'];
}
}
catch(PDOException $e )
{
echo "Error: ".$e;
}
echo "context list: ";
echo $context_list;
A partial solution:
This worked:
$query = $conn->prepare("SELECT area_easting, area_northing, context_number FROM excavation.contexts");
$query->execute();
while($r = $query->fetch(PDO::FETCH_OBJ)){
echo $r->area_easting, '|';
echo $r->area_northing;
echo '<br/>';
}
But Now I need to make the $r->area_easting accessible to the session, but that's another question.
Your query may return several records (provided they actually exist in the table).
Your code loops through all the records (with the while loop) but the values ($easting_list, $northing_list and $context_list) are overwritten in the loop.
I suggest the following changes to your code:
$easting_list = array();
$northing_list = array();
$context_list = array();
try {
$sql2 = "SELECT area_easting, area_northing, context_number FROM excavation.contexts";
$sth = $conn->prepare($sql2);
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC))
{
$easting_list[] = $row['area_easting'];
$northing_list[] = $row['area_northing'];
$context_list[] = $row['context_number'];
}
}
catch(PDOException $e )
{
echo "Error: ".$e;
}
echo "context list: ";
echo implode(', ', $context_list);
Now all the values are stored in 3 arrays. explode is used to print a comma-separated list of all values in $context_list array.

How can set up the table correctly for receiving the string converted from dates?

I have a problem and don't know how to solve it. After i run the code i didn't receive corectly a period of time. I put the code here.
I think something is wrong with table from database (i use PhpMyAdmin 4.2.0 module from EasyPhp). I put an image too to see what happens. The dates marked with red need to be at the end of table.
<?php
function data_range($first, $last, $step = '+1 day', $output - format = 'd-m-Y')
{
$dates = array();
$current = strtotime($first);
$last = strtotime($last);
while ($current <= $last)
{
$dates[] = date($output_format, $current);
$current = strtotime($step, $current);
}
foreach($dates as $zile)
{
$krr = explode('-', $zile);
var_dump($krr);
$result2 = implode('/', $krr);
echo $result2 . "<br/>";
$sql4 = "INSERT INTO studenti3 (data) VALUES ('$result2')";
$rez4 = mysql_query($sql4);
}
var_dump($dates);
}
$first = "06-04-2015";
$last = "07-05-2015";
$step = "+1day";
$output_format = 'd-m-Y';
date_range($first, $last, $step, $output_format); ?>

Prepare content does not work for Sourcerer and DirectPHP

In my Joomla website, I need to execute some custom SQL queries, that have to select different titles from related categories.
Problem I have it works like option Prepare Content is turned off, so all of my content is outside HTML tags.
Module content looks like this:
{source}
<?php
$var_result = '';
$var_categories = array();
$var_category_list = array();
$db =& JFactory::getDBO();
$query = 'select * from jneg_categories where parent_id = 9';
$db->setQuery($query,0,300);
$res = $db->loadObjectList();
foreach ( $res as $row ) {
$var_categories[($row->id)] = $row->title;
$var_category_list[] = $row->id;
}
$var_category_list = implode($var_category_list, ', ');
$sql = "select * from jneg_content where catid IN (".$var_category_list.") order by `catid`";
$db->setQuery($sql,0,30000);
$res = $db->loadObjectList();
$var_current_cat = 0;
foreach ( $res as $row ) {
if ($current_cat != $row->catid) {
$current_cat = $row->catid;
echo '<h2>'.$categories[($row->catid)] . '</h2>';
echo '<br>';
}
echo $row->title;
echo '<br>';
}
?>
{/source}
Can you help me how to get proper HTML as a result of this code please.
Sourcer or other php rendering plugins don't run in html modules unless you go under the module 'options' and select 'prepare content'...
...or you can use this module and just include your php file directly:
https://github.com/idea34/mod_show
Ok, I did it with Jumi plugin - http://2glux.com/projects/jumi/usage-for-j15
Thank you anyway.