PHP with mongodb datatable error - php

I Got error in the datatable in mongodb please give solution...
If Anyone have reference source code send me it will helpful for me....................................................................................................................................................................................
Notice: Undefined index: iColumns in D:\xampp\htdocs\mongo\test3.php on line 47
Notice: Undefined index: sEcho in D:\xampp\htdocs\mongo\test3.php on line 129
{"sEcho":0,"iTotalRecords":9,"iTotalDisplayRecords":9,"aaData":[{"_id":
{"$id":"5936e5e783b236680c00002a"},"name":"Mitra","age":21,"gender":"M","course":"BTECH","marks":77}
Source Code:
<?php
mb_internal_encoding('UTF-8');
$database = 'university';
$collection = 'students';
/**
* MongoDB connection
*/
try{
// Connecting to server
$m = new MongoClient( );
}catch(MongoConnectionException $connectionException){
print $connectionException;
exit;
}
$m_collection = $m->$database->$collection;
/**
* Define the document fields to return to DataTables (as in http://us.php.net/manual/en/mongocollection.find.php).
* If empty, the whole document will be returned.
*/
$fields = array();
// Input method (use $_GET, $_POST or $_REQUEST)
$input = & $_REQUEST;
/**
* Handle requested DataProps
*/
// Number of columns being displayed (useful for getting individual column search info)
$iColumns = $input['iColumns'];
// Get mDataProp values assigned for each table column
$dataProps = array();
for ($i = 0; $i < $iColumns; $i++) {
$var = 'mDataProp_'.$i;
if (!empty($input[$var]) && $input[$var] != 'null') {
$dataProps[$i] = $input[$var];
}
}
/**
* Filtering
* NOTE this does not match the built-in DataTables filtering which does it
* word by word on any field. It's possible to do here, but concerned about efficiency
* on very large collections.
*/
$searchTermsAny = array();
$searchTermsAll = array();
if ( !empty($input['sSearch']) ) {
$sSearch = $input['sSearch'];
for ( $i=0 ; $i < $iColumns ; $i++ ) {
if ($input['bSearchable_'.$i] == 'true') {
if ($input['bRegex'] == 'true') {
$sRegex = str_replace('/', '\/', $sSearch);
} else {
$sRegex = preg_quote($sSearch, '/');
}
$searchTermsAny[] = array(
$dataProps[$i] => new MongoRegex( '/'.$sRegex.'/i' )
);
}
}
}
// Individual column filtering
for ( $i=0 ; $i < $iColumns ; $i++ ) {
if ( $input['bSearchable_'.$i] == 'true' && $input['sSearch_'.$i] != '' ) {
if ($input['bRegex_'.$i] == 'true') {
$sRegex = str_replace('/', '\/', $input['sSearch_'.$i]);
} else {
$sRegex = preg_quote($input['sSearch_'.$i], '/');
}
$searchTermsAll[ $dataProps[$i] ] = new MongoRegex( '/'.$sRegex.'/i' );
}
}
$searchTerms = $searchTermsAll;
if (!empty($searchTermsAny)) {
$searchTerms['$or'] = $searchTermsAny;
}
$cursor = $m_collection->find($searchTerms, $fields);
/**
* Paging
*/
if ( isset( $input['iDisplayStart'] ) && $input['iDisplayLength'] != '-1' ) {
$cursor->limit( $input['iDisplayLength'] )->skip( $input['iDisplayStart'] );
}
/**
* Ordering
*/
if ( isset($input['iSortCol_0']) ) {
$sort_fields = array();
for ( $i=0 ; $i<intval( $input['iSortingCols'] ) ; $i++ ) {
if ( $input[ 'bSortable_'.intval($input['iSortCol_'.$i]) ] == 'true' ) {
$field = $dataProps[ intval( $input['iSortCol_'.$i] ) ];
$order = ( $input['sSortDir_'.$i]=='desc' ? -1 : 1 );
$sort_fields[$field] = $order;
}
}
$cursor->sort($sort_fields);
}
/**
* Output
*/
$output = array(
"sEcho" => intval($input['sEcho']),
"iTotalRecords" => $m_collection->count(),
"iTotalDisplayRecords" => $cursor->count(),
"aaData" => array(),
);
foreach ( $cursor as $doc ) {
$output['aaData'][] = $doc;
}
echo json_encode( $output );

Those are not errors, are Notices:
$iColumns = $input['iColumns'];
$input has no key named iColumns.
"sEcho" => intval($input['sEcho']),
Same thing here: $input has no key named sEcho
Make sure that $_REQUEST contains both keys.
Or you could disable Error Reporting for notices.
EDIT:
You use:
$input = & $_REQUEST;
you should provably use $_GET or $_POST depending how you send the date to the server and ensure iColumns and sEcho are sent.
If your frontend has a form and you are posting the data, you could validate the input fields so those two variables are required OR give them a default value.
If you want to default it (for example) to 10:
$iColumns = isset($input['iColumns']) ? isset($input['iColumns']) : 10;
and (not sure what sEcho index is used for:
$sEcho = isset($input['sEcho'] ? intval($input['sEcho']) : 10;
$output = array(
"sEcho" => $sEcho,
"iTotalRecords" => $m_collection->count(),
"iTotalDisplayRecords" => $cursor->count(),
"aaData" => array(),
);
That should not give you any notices.
Other Option, disable reporting of notices:
[root#server ]$ vi /etc/php.ini
error_reporting = E_ALL & ~E_NOTICE
Or, in the top of your php file:
error_reporting(E_ALL & ~E_NOTICE);

Related

"Cannot get return value of a generator that hasn't returned " php backtracking

I am trying to do backtracking to solved a problem but I get this error:
Error: genator hasn´t returned
Fisrt I will introduce the main problem that the software must resolve:
I have been trying to create the software for a hospital, this
software must create a schedule with the doctors for each day. Each
day must have 5 assigned doctors, one for a specialty called "trauma",
another for "ucr" and another for "box13".
Before assigning doctors, the user must enter the number of holes of
each type that doctor can do that month. So I know how many "trauma",
"ucr" or "box13" have any doctor that month.
Aaah! one more thing, you can not assign a doctor two days in a row.
So I decided to create a backtracking algorithm, the problem is that I am getting a Generator object at the end of the execution but I don´t get a valid return.
function bt($ps){
if($ps->is_solution()){
return $ps->get_solution();
}
else{
yield from $ps->successors();
}
}
class Briker_vc_PS{
public function __construct( $decisiones, $diasTotalFinal, $fechaInicio, $box13, $ucr, $trauma, $numGuardiasAsig){
$this->decisiones= $decisiones;
$this->diasTotalFinal = $diasTotalFinal;
$this->fechaInicio = $fechaInicio;
$this->box13 = $box13;
$this->ucr = $ucr;
$this->trauma = $trauma;
$this->numGuardiasAsig = $numGuardiasAsig;
}
public function is_solution(){
return $this->numGuardiasAsig == $this->diasTotalFinal*5;
}
public function get_solution(){
return $this->decisiones;
}
public function state(){
return $this->decisiones[$this->fechaInicio];
}
public function successors(){
if( array_key_exists( $this->fechaInicio, $this->decisiones) == false ){
$this->decisiones[$this->fechaInicio] = [];
}
if( array_key_exists( 'ids', $this->decisiones[$this->fechaInicio]) == false ){
$this->decisiones[$this->fechaInicio]['ids'] = [];
}
if( array_key_exists( $this->fechaInicio ,$this->decisiones) and array_key_exists( 'box13' ,$this->decisiones) and array_key_exists( 'trauma' ,$this->decisiones) and array_key_exists( 'ucr' ,$this->decisiones)){
if( (count($this->decisiones['trauma'])==1) and (count($this->decisiones['ucr'])==2) and (count($this->decisiones['box13'])==2) ){
$this->fechaInicio = date("Y-m-d",strtotime($this->fechaInicio." +1 day"));
$this->decisiones[$this->fechaInicio]['date'] = $this->fechaInicio;
}
}
$anterior = date("Y-m-d",strtotime($this->fechaInicio." -1 day"));
$Lista=[];
if( array_key_exists( 'trauma' ,$this->decisiones) == false ){
foreach($this->trauma as $key => $val){
if( (in_array($key, $this->decisiones[$this->fechaInicio]['ids']) == false) and (in_array($key, $this->decisiones[$anterior]['ids']) == false) ){
$decisions= $this->decisiones;
$decisions[$this->fechaInicio]['trauma'] = [$key];
$auxtra= $this->trauma;
if($auxtra[$key] -1 == 0){
unset($auxtra[$key]);
}else{
$auxtra[$key] = $auxtra[$key] -1;
}
$num = $this->numGuardiasAsig +1 ;
$decisions[$this->fechaInicio]['ids'][] = $key;
yield from bt(new Briker_vc_PS( $decisions, $this->diasTotalFinal, $this->fechaInicio, $this->box13, $this->ucr, $auxtra, $num));
}
}
}
if( (array_key_exists( 'box13' ,$this->decisiones) == false) or (count($this->decisiones['box13'])<2) ){
foreach($this->box13 as $key => $val){
if( (in_array($key, $this->decisiones[$this->fechaInicio]['ids']) == false) and (in_array($key, $this->decisiones[$anterior]['ids']) == false) ){
$decisions= $this->decisiones;
if(array_key_exists( 'box13' ,$this->decisiones) == false){
$decisions[$this->fechaInicio]['box13'] = array();
}
$decisions[$this->fechaInicio]['box13'][] = $key;
$auxbox13= $this->box13;
if($auxbox13[$key] -1 == 0){
unset($auxbox13[$key]);
}else{
$auxbox13[$key] = $auxbox13[$key] -1;
}
$num = $this->numGuardiasAsig +1 ;
$decisions[$this->fechaInicio]['ids'][] = $key;
yield from bt( new Briker_vc_PS( $decisions, $this->diasTotalFinal, $this->fechaInicio, $auxbox13, $this->ucr, $this->trauma, $num));
}
}
}
if( (array_key_exists( 'ucr' ,$this->decisiones) == false) or (count($this->decisiones['ucr'])<2) ){
foreach($this->ucr as $key => $val){
if( (in_array($key, $this->decisiones[$this->fechaInicio]['ids']) == false) and (in_array($key, $this->decisiones[$anterior]['ids']) == false) ){
$decisions= $this->decisiones;
if(array_key_exists( 'ucr' ,$this->decisiones) == false){
$decisions[$this->fechaInicio]['ucr'] = array();
}
$decisions[$this->fechaInicio]['ucr'][] = $key;
$auxucr= $this->ucr;
if($auxucr[$key] -1 == 0){
unset($auxucr[$key]);
}else{
$auxucr[$key] = $auxucr[$key] -1;
}
$decisions[$this->fechaInicio]['ids'][] = $key;
$num = $this->numGuardiasAsig +1 ;
yield from bt(new Briker_vc_PS( $decisions, $this->diasTotalFinal, $this->fechaInicio, $this->box13, $auxucr, $this->trauma, $num));
}
}
}
}
protected $GuardiasMedico;
protected $decisiones;
}
And this is the main program
$month = $_REQUEST['mes'];
$year = $_REQUEST['any'];
$fecha_inicio = "01-".$month."-".$year;
// fisrt i get the number of "trauma", "ucr" and "box13" for each doctor
// And i create a array with it with key the doctor_id
$db = new SQLite3($dbname);
$result = $db->query('SELECT m.id, m.nombre, m.apellido, mgm.ucr, mgm.trauma, mgm.box13 FROM medico AS m INNER JOIN MedicoGuardiaMes AS mgm ON m.id = mgm.doctor_id WHERE m.borrado = 0 AND mgm.mes = '.$month.' AND mgm.any = '.$year);
$box13 = [];
$ucr = [];
$trauma = [];
while($res = $result->fetchArray()){
$box13[$res['id']] = $res['box13'];
$ucr[$res['id']] = $res['ucr'];
$trauma[$res['id']] = $res['trauma'];
}
// I create the solution array and add the last day from the previous month
$dataBaseDecisiones = [];
$anterior = date("Y-m-d",strtotime($fecha_inicio." -1 day"));
$dataBaseDecisiones[$anterior] = [];
$dataBaseDecisiones[$anterior]['ids'] = [];
$diasTotalFinal=cal_days_in_month(CAL_GREGORIAN, $month, $year);
// Finally I create the initial object and starts the backtracking
$initial_ps = new Briker_vc_PS($dataBaseDecisiones, $diasTotalFinal, $fecha_inicio, $box13, $ucr, $trauma, $numGuardiasAsig);
var_dump( bt($initial_ps)->getReturn() );
I don´t know why this code is not working or if I am using yield the right way.
The problem that is reported happens because of the last line in your code:
bt($initial_ps)->getReturn();
When bt executes the else part it performs a recursive search until there is a return, and then it yields that value. But that does not finish the iterator's results and this yielded value is not considered the iterator's return value. So getReturn() triggers the exception you got.
You don't explain what you intend to get as output in that var_dump. If you want to output all the yielded results, then collect all those results first, for instance with iterator_to_array:
$iter = bt($initial_ps);
print_r(iterator_to_array($iter));
And only then you can execute:
print_r($iter->getReturn());

Invalid argument supplied for foreach() since updating my Customizr theme

I just updated my Customizr child theme and I'm getting the following error on my dashboard:
Warning: Invalid argument supplied for foreach() in /home/beaufort/public_html/wp-content/themes/customizr/inc/class-fire-utils.php on line 653
This is what is on line 653:
foreach ( $_font_groups as $_group_slug => $_font_list ) {
and this is what follows:
if ( 'list' == $_what ) {
$_to_return[$_group_slug] = array();
$_to_return[$_group_slug]['list'] = array();
$_to_return[$_group_slug]['name'] = $_font_list['name'];
}
I am clueless when it comes to php so your help would be much appreicated!
Many thanks
/**
* #return an array of font name / code OR a string of the font css code
* #parameter string name or google compliant suffix for href link
*
* #package Customizr
* #since Customizr 3.2.9
*/
function tc_get_font( $_what = 'list' , $_requested = null ) {
$_to_return = ( 'list' == $_what ) ? array() : false;
$_font_groups = apply_filters(
'tc_font_pairs',
TC_init::$instance -> font_pairs
);
foreach ( $_font_groups as $_group_slug => $_font_list ) {
if ( 'list' == $_what ) {
$_to_return[$_group_slug] = array();
$_to_return[$_group_slug]['list'] = array();
$_to_return[$_group_slug]['name'] = $_font_list['name'];
}
foreach ( $_font_list['list'] as $slug => $data ) {
switch ($_requested) {
case 'name':
if ( 'list' == $_what )
$_to_return[$_group_slug]['list'][$slug] = $data[0];
break;
case 'code':
if ( 'list' == $_what )
$_to_return[$_group_slug]['list'][$slug] = $data[1];
break;
default:
if ( 'list' == $_what )
$_to_return[$_group_slug]['list'][$slug] = $data;
else if ( $slug == $_requested ) {
return $data[1];
}
break;
}
}
}
return $_to_return;
}
Before line 653 add if (is_array($_font_groups)) {
Then, add a closing bracket } above return $_to_return;

$session data returns only 0

I'm trying to put a script together that will do some math for the user.
That works fine however when i try to put it in a session and try to show the value to the user it will only return 0 if its set to 0.
Does anybody know where i did wrong?
<?php
session_start();
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
$class1 = filter_var($_POST['class1'], FILTER_SANITIZE_STRING);
$class2 = filter_var($_POST['class2'], FILTER_SANITIZE_STRING);
$class3 = filter_var($_POST['class3'], FILTER_SANITIZE_STRING);
$class4 = filter_var($_POST['class4'], FILTER_SANITIZE_STRING);
$class5 = filter_var($_POST['class5'], FILTER_SANITIZE_STRING);
$class1C = $class1 * 35;
$class2C = $class2 * 5;
$class3C = $class3 * 7.5;
$class4C = $class4 * 26;
$class5C = $class5 * 2.5;
$totaal1 = $class1C + $class2C + $class3C + $class4C + $class5C;
$res = array($class1C, $class2C, $class3C, $class4C, $class5C, $totaal1);
foreach($res as $name => $var) {
$_SESSION[$name] = $var;
}
$result = array("error" => false, "html" => null);
$result["error"] = false;
$result["html"] = "<h3>Session information: var_dump($_SESSION[$class1C]) ($_SESSION[$class2C]) ($_SESSION[$totaal1])</h3>";
} else {
$result["error"] = true;
$result["html"] = "<h3>Error</h3>";
}
echo json_encode($result);
exit;
?>
You cannot call var_dump inside the double quoted string, and var_dump does not return anything: it only display things.
Even if you could, $class1C is not a valid index for $_SESSION
Keeping the same logic as your code, you may change your line to the following:
$result["html"] = "<h3>Session information:";
ob_start();
var_dump($_SESSION[0]); // contains $class1C
echo $_SESSION[1]; // contains $class2C
echo $_SESSION[5]; // contains $totaal1
$result["html"] .= ob_get_clean();
$result["html"] .= "</h3>";
EDIT:
If you want to use the indexes 'class2C', 'totaal1' etc.. you need to init $res as follow:
$res = array(
'class1C' => $class1C,
'class2C' => $class2C,
'class3C' => $class3C,
'class4C' => $class4C,
'class5C' => $class5C,
'totaal1' => $totaal1
);
Then, your loop to set $_SESSION will set correct indexes, and you will be able to use $_SESSION['class1C'] to get proper values.

PHP Array Nominal Indexes with Strings

I have a PHP application that takes a CSV in input; in the first column I have both category and subcategory splitted by a '|'. I have to put this stuff in a Open Cart DB, which has the same table for Category and Subcategory (a column "parent_id" indicates the category_id of the Category).
I thought to build a class with all the fields needed as follows:
class Categorie {
public $category_id;
public $parent_id;
public $image;
public $top;
public $column;
public $sort_order;
public $status;
public $date_modified;
public $date_added;
public $language_id;
public $name;
public $description;
public $meta_description;
public $meta_keywords;
}
Then I analyze the data:
$categorie = array();
while ( ( $riga_file = fgetcsv( $file, 100000, "\t" ) ) !== false )
{
$array_el = count( $riga_file );
for( $el_cur = 0; $el_cur < $array_el; $el_cur++ )
{
switch ( $el_cur )
{
case 0:
$colonne = explode( "|", $riga_file[$el_corr] );
$categoria = new Categorie();
$categoria->image = "";
$categoria->top = 1;
$categoria->column = 1;
// ... bla adding description data
if( $categorie[$colonne[0]] == NULL ) // (1)
{
$categoria->name = $colonne[0];
$categoria->category_id = $id_categoria;
$categoria->parent_id = 0;
$categorie[$colonne[0]] = $categoria;
$id_categoria++;
}
if( $colonne[1] != NULL ) // (2)
{
$categoria->name = $colonne[1];
if( $categorie[$colonne[1]] == NULL )
{
$categoria->category_id = $id_categoria;
$categoria->parent_id = $categorie[$colonne[0]]->category_id;
$categorie[$colonne[1]] = $categorie;
$id_categoria++;
}
}
break;
}
I should have an array filled with a collection of unique objects like:
// OUT(3)
Category 1
Subcategory 1
Category 2
Subcategory 2...
If I put echoes of $categoria (not $categorie) inside (1) and (2), I see exactly what I wrote down in OUT(3), which leads me to think that my "engine" is correct. The problems come when I try to search into the array:
echo "<table border='1'>";
foreach( $categorie as $value )
{
echo "<tr>
<td>$value->category_id</td>
<td>$value->parent_id</td>
<td>$value->name</td>
</tr>";
}
echo "</table>";
because I don't get Categories at all, and most but not all Subcategories.
Am I doing something wrong with "search engine" or I misunderstood something with PHP Arrays (probably because I come from C++ and this php is f**king my mind)?
I solved the problem, or better: problems.
1) I mispelled a variable: in (2) I wrote:
$categorie[$colonne[1]] = $categorie;
The correct writing is:
$categorie[$colonne[1]] = $categoria;
2) The bigger problem was from my "unknowing" of PHP, in fact, fixed the problem 1, I got an output like:
subcategory1
subcategory1
subcategory2
subcategory2
and so on. This lead me to guess that when I do:
$categorie[$colonne[1]] = $categoria;
PHP doesn't copy the values inside, but uses addresses instead. Follows the right code:
switch ( $el_corr )
{
case 0: // Categorie e sottocategorie
$colonne = explode( "|", $riga_file[$el_corr] );
$categoria = new Categorie();
$categoria->image = "";
$categoria->top = 1;
$categoria->column = 1;
$categoria->sort_order = 0;
$categoria->status = 1;
// Category_Description Campi
$categoria->language_id = 1;
$categoria->name = $colonne[0];
$categoria->description = "";
$categoria->meta_description = "";
$categoria->meta_keywords = "";
////////////////////////
if( $categorie[$colonne[0]] == NULL )
//if( !trova_categorie( $colonne[0], $categorie ) )
{
$categoria->name = $colonne[0];
$categoria->category_id = $id_categoria;
$categoria->parent_id = 0;
$categorie[$colonne[0]] = $categoria;
$id_categoria++;
}
$categoria = new Categorie();
$categoria->image = "";
$categoria->top = 1;
$categoria->column = 1;
$categoria->sort_order = 0;
$categoria->status = 1;
// Category_Description Campi
$categoria->language_id = 1;
$categoria->name = $colonne[0];
$categoria->description = "";
$categoria->meta_description = "";
$categoria->meta_keywords = "";
if( $colonne[1] != NULL )
{
$categoria->name = $colonne[1];
if( $categorie[$colonne[1]] == NULL )
//if( !trova_categorie( $colonne[1], $categorie ) )
{
$categoria->category_id = $id_categoria;
$categoria->parent_id = $categorie[$colonne[0]]->category_id;
$categorie[$colonne[1]] = $categoria;
$id_categoria++;
}
}
break;
}

How can i show sphinx search result in PHP

How is that possible to show sphinx search result via PHP
i have installed sphinx and configured but i am unable to get the result via PHP
Check the Sphinx Library : Sphinx Documentation
The Below Code Is Used To Get The Full Content From Sphinx Search Result
Now Currently We Need To Give The Id In $SQL line
<?php
echo "Welcome To Sphinx Search Site </br>";
$q = "html";
$sphx = sphinx_search("html", 0, 20);
$sphx['122'];
$ids = 122;
$sql = "SELECT post_title , post_content FROM wp_posts WHERE ID = '122'";
db();
if( !($r = mysql_query($sql)))
die("[MYSQL]".mysql_error() . mysql_errno() );
$max = $sphx['total'];
$num_rows = $sphx['docs'];
echo "<b>Displaying {$num_rows} results of {$max}</b><br /><br />";
while($row = mysql_fetch_assoc($r) ) {
echo "{$row['post_title']} <br />{$row['post_content']}<br /><hr />";
}
mysql_free_result($r);
/*
* SPHINX Search
*/
/*
* Search sites by Keywords using sphinx; with an option to search sites tags only
* #param string $q te keyword
* #param int $i id of the first result to return
* #param int $max max results to return
* #param bollen $url set to true to return matches from the 'url' column only
*
* #return string $ids comma seperated list of ids
*/
function sphinx_search($q, $i, $limit, $post_type=true){
require_once 'sphinxapi.php';
$ids = '33500';
$cl = new SphinxClient();
$cl->SetServer( "192.168.0.89" , 9667);
$cl->SetMatchMode( SPH_MATCH_EXTENDED );
$cl->SetSortMode ( SPH_SORT_RELEVANCE );
$cl->SetFieldWeights(array('post_title' => 300));
$cl->SetLimits( $i , $limit);
$q = $cl->EscapeString( $q);
//search url only
$q = $post_type ? "#post_type {$q}" : $q;
$result = $cl->Query( $q, 'sites sitesDelta' );
if ( $result === false )
error_log( '[SPHINX]Query failed: ' . $cl->GetLastError() );
elseif ( $cl->GetLastWarning() )
error_log( '[SPHINX]WARNING: ' . $cl->GetLastWarning() );
if ( !empty($result["matches"]) ){
foreach ( $result["matches"] as $doc => $docinfo )
$ids .= "$doc,";
$ids = substr( $ids, 0, -1 );
}else
return false;
return array( 'ids' => $ids, 'total' => $result['total'], 'docs' => count($result["matches"]) );
}
/*
* Connect to MySQL
*/
function db(){
if( !empty($GLOBALS['db']) ) return true;
if( !$GLOBALS['db'] = mysql_connect('localhost', 'root', '' ) ) {
die("[MYSQL]".mysql_error() . mysql_errno() );
}
elseif(!mysql_select_db('sphinxiirmulti')) {
die("[MYSQL]".mysql_error() . mysql_errno() );
}
}
?>

Categories