I'm using a php function to create a user listing of entries with pagination. I need to remove entries without name so I tried this code but it doesn't work: entries without name are not removed.
$listing->entries( $order, $eLimit, $eLimStart, true, array('owner' => $userid, 'name' != null), false, $section);
The opposite works well, with this code I get all entries without name:
$listing->entries( $order, $eLimit, $eLimStart, true, array('owner' => $userid, 'name' => null), false, $section);
The name is stored like this in the DB:
- type: varchar(250)
- interclassement: utf8_general_ci
- Null: Yes
- Default: NULL
I'm using PHP Version 5.3.16.
What am I doing wrong please? Thanks a lot.
** EDIT **
The context: Joomla 2.5.9 and SobiPro 1.08. I use SobiPro API to create the listing:
$listing = SPFactory::Controller('listing');
$listing = new SPListingCtrl();
The function entries looks like this
public function entries( $eOrder, $eLimit = null, $eLimStart = null, $count = false, $conditions = array(), $entriesRecursive = false, $pid = -1 )
{
return $this->getEntries( $eOrder, $eLimit, $eLimStart, $count, $conditions, $entriesRecursive, $pid );
}
The function getEntries looks like this:
/**
* #param string $eOrder
* #param int $eLimit
* #param int $eLimStart
* #return array
*/
public function getEntries( $eOrder, $eLimit = null, $eLimStart = null, $count = false, $conditions = array(), $entriesRecursive = false, $pid = 0 )
{
/* var SPDb $db */
$db =& SPFactory::db();
$eClass = SPLoader::loadModel( 'entry' );
$entries = array();
$eDir = 'asc';
$oPrefix = null;
$conditions = is_array( $conditions ) ? $conditions : array();
/* get the ordering and the direction */
if ( strstr( $eOrder, '.' ) ) {
$eOr = explode( '.', $eOrder );
$eOrder = array_shift( $eOr );
$eDir = implode( '.', $eOr );
}
$pid = $pid ? $pid : SPRequest::sid();
/* if sort by name, then sort by the name field */
if ( $eOrder == 'name' ) {
$eOrder = SPFactory::config()->nameField()->get( 'fid' );
}
if ( $entriesRecursive ) {
$pids = $this->_model->getChilds( 'category', true );
if ( is_array( $pids ) ) {
$pids = array_keys( $pids );
}
$pids[ ] = SPRequest::sid();
$conditions[ 'sprl.pid' ] = $pids;
}
else {
$conditions[ 'sprl.pid' ] = $pid;
}
if ( $pid == -1 ) {
unset( $conditions[ 'sprl.pid' ] );
}
/* sort by field */
if ( strstr( $eOrder, 'field_' ) ) {
static $field = null;
$specificMethod = false;
if ( !$field ) {
try {
$db->select( 'fieldType', 'spdb_field', array( 'nid' => $eOrder, 'section' => Sobi::Section() ) );
$fType = $db->loadResult();
}
catch ( SPException $x ) {
Sobi::Error( $this->name(), SPLang::e( 'CANNOT_DETERMINE_FIELD_TYPE', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ );
}
if ( $fType ) {
$field = SPLoader::loadClass( 'opt.fields.' . $fType );
}
}
if ( $field && method_exists( $field, 'sortBy' ) ) {
$table = null;
$oPrefix = null;
$specificMethod = call_user_func_array( array( $field, 'sortBy' ), array( &$table, &$conditions, &$oPrefix, &$eOrder, &$eDir ) );
}
if ( !$specificMethod ) {
$table = $db->join(
array(
array( 'table' => 'spdb_field', 'as' => 'fdef', 'key' => 'fid' ),
array( 'table' => 'spdb_field_data', 'as' => 'fdata', 'key' => 'fid' ),
array( 'table' => 'spdb_object', 'as' => 'spo', 'key' => array( 'fdata.sid', 'spo.id' ) ),
array( 'table' => 'spdb_relations', 'as' => 'sprl', 'key' => array( 'fdata.sid', 'sprl.id' ) ),
)
);
$oPrefix = 'spo.';
$conditions[ 'spo.oType' ] = 'entry';
$conditions[ 'fdef.nid' ] = $eOrder;
// $eOrder = 'baseData.' . $eDir;
$eOrder = 'baseData = "", CONVERT(baseData,UNSIGNED INTEGER).' . $eDir;
}
}
else {
$table = $db->join( array(
array( 'table' => 'spdb_relations', 'as' => 'sprl', 'key' => 'id' ),
array( 'table' => 'spdb_object', 'as' => 'spo', 'key' => 'id' )
) );
$conditions[ 'spo.oType' ] = 'entry';
$eOrder = $eOrder . '.' . $eDir;
$oPrefix = 'spo.';
if ( strstr( $eOrder, 'valid' ) ) {
$eOrder = $oPrefix . $eOrder;
}
}
/* check user permissions for the visibility */
if ( Sobi::My( 'id' ) ) {
$this->userPermissionsQuery( $conditions, $oPrefix );
if( isset( $conditions[ $oPrefix . 'state' ] ) && $conditions[ $oPrefix . 'state' ] ) {
$conditions[ 'sprl.copy' ] = 0;
}
}
else {
$conditions = array_merge( $conditions, array( $oPrefix . 'state' => '1', '#VALID' => $db->valid( $oPrefix . 'validUntil', $oPrefix . 'validSince' ) ) );
$conditions[ 'sprl.copy' ] = '0';
}
try {
$db->select( $oPrefix . 'id', $table, $conditions, $eOrder, $eLimit, $eLimStart, true );
$results = $db->loadResultArray();
}
catch ( SPException $x ) {
Sobi::Error( $this->name(), SPLang::e( 'DB_REPORTS_ERR', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ );
}
Sobi::Trigger( $this->name(), 'AfterGetEntries', array( &$results, $count ) );
if ( count( $results ) && !$count ) {
$memLimit = ( int )ini_get( 'memory_limit' ) * 2097152;
foreach ( $results as $i => $sid ) {
// it needs too much memory moving the object creation to the view
//$entries[ $i ] = SPFactory::Entry( $sid );
$entries[ $i ] = $sid;
}
}
if ( $count ) {
return $results;
}
return $entries;
}
Instead of looking for non empty entries, perhaps you could do the opposite and look for entries that have something, like so:
$listing->entries( $order, $eLimit, $eLimStart, true, array('owner' => $userid, 'name' => '%'), false, $section);
This is purely a guess, however, as we would need to see the entries function to see how the various parameters are being handled.
SOLVED - Thanks everyone for your help !
$listing->entries( $order, $eLimit, $eLimStart, true, array('owner' => $userid, '!name' => null ), false, -1);
Related
I try to make my custom code to update data to my custom database table
after I send the data I get:
Warning: mysqli_real_escape_string() expects parameter 2 to be string,
array given in .../wp-includes/wp-db.php on line 1156
My table structure is:
table name: wp_wlm_user_options
column names: ID, user_id, option_name, option_value
My code is:
if (isset($_POST['submit'])) {
$user_id = $_POST['user_id'];
$table = 'wp_wlm_user_options';
$meta = array();
foreach ($wlm_user_info as $key => $value) {
$get_meta = $value['option_name'];
array_push($meta, $get_meta);
}
//var_dump($meta);
$value = array(
'custom_firstname' => $_POST['first_name'],
'custom_lastname' => $_POST['last_name'],
'custom_text_dateofbirth' => $_POST['text_dateofbirth'],
'custom_radio_gender' => $_POST['radio_gender'],
'custom_landlinephone' => $_POST['landlinephone'],
'custom_GoogleHangoutsId' => $_POST['GoogleHangoutsId']
);
$format = array(
'%s',
'%s'
);
//print_r($meta,$value);
$data = array(
'user_id' => $user_id,
'option_name' => $meta,
'option_value' => maybe_serialize($value)
);
$format = array('%d','%s','%s');
$where = array(
'user_id' => $user_id,
'option_name' => $meta
);
$x = $wpdb->update($table, $data, $where, $format);
//$x = $wpdb->update($table, $data, $where);
if($x){
echo '<h1>data has been save</h1>' ;
}
Can anyone tell me what is wrong with this?
Due to your poor information we can only guess.
You might want something like this:
if (isset($_POST['submit']))
{
$user_id = $_POST['user_id'];
$table = 'wp_wlm_user_options';
$values = array(
'custom_firstname' => $_POST['first_name' ],
'custom_lastname' => $_POST['last_name' ],
'custom_text_dateofbirth' => $_POST['text_dateofbirth'],
'custom_radio_gender' => $_POST['radio_gender' ],
'custom_landlinephone' => $_POST['landlinephone' ],
'custom_GoogleHangoutsId' => $_POST['GoogleHangoutsId']
);
$format = array('%s');
$whereformat = array('%d','%s');
foreach($values as $key => $val)
{
$data = array(
'option_value' => maybe_serialize($val)
);
$where = array(
'user_id' => $user_id,
'option_name' => $key
);
$num_rows = $wpdb->update($table, $data, $where, $format, $whereformat);
if($num_rows !== false){
echo "<h1>$key has been saved</h1>" ;
}
}
};
The code above does multiple updates mapping the data to option_name and option_value for each update() invocation. You don't need to update fields of the WHERE clause with unchanged values.
You can find the official documentation on wordpress.org
i want to SORT my data in gridview based on alphabet, my code is work if sort by ID when ID contains number, e.g 1-100 or 100-1.
How to sort from A-Z or Z-A? is it possible to custom Yii2 sort?
i have a code in controller :
public function actionItemreport()
{
$modelFunctions = new functions;
$modelFunctions->checkingUser( $this, Yii::$app->controller->id, Yii::$app->controller->action->id );
$this->transfield = array( 'icitem' => $modelFunctions->getFieldTranslationTable( 'icitem' ), 'iclink' => $modelFunctions->getFieldTranslationTable( 'iclink' ) );
$arrDays = array( '0' => $this->arrtrans[134], '1' => $this->arrtrans[135], '2' => $this->arrtrans[136], '3' => $this->arrtrans[137], '4' => $this->arrtrans[138], '5' => $this->arrtrans[139], '6' => $this->arrtrans[140] );
$arrSchedule = $this->getItemReportScheduler();
$ftpSql = "SELECT * FROM icenvinit";
$a_icenvinit = Yii::$app->db->createCommand( $ftpSql )->queryOne();
if( $a_icenvinit['hostaddr1'] != "" )
{
$arr_ftp['FTP1'] = $this->arrtrans[141];
}
if( $a_icenvinit['hostaddr2'] != "" )
{
$arr_ftp['FTP2'] = $this->arrtrans[142];
}
switch ( intval($arrSchedule['type']) )
{
case 1 : $listSchedule = "[ " . $this->arrtrans[143] . " ] : {$arrSchedule['hour']}:{$arrSchedule['minute']}";
break;
case 2 : $days = $arrDays[$arrSchedule['day']];
$listSchedule = "[ " . $this->arrtrans[144] . " ] : {$days} {$arrSchedule['hour']}:{$arrSchedule['minute']}";
break;
case 3 : $date = $arrSchedule['date'];
$listSchedule = "[ " . $this->arrtrans[145] . " ] : {$date} {$arrSchedule['hour']}:{$arrSchedule['minute']}";
break;
case 4 : $listSchedule = "[ " . $this->arrtrans[146] . " ] : Every {$arrSchedule['interval']} Hour(s)";
break;
default : $listSchedule = $this->arrtrans[147];
$listTarget = "";
break;
}
$sql = "SELECT * FROM icdbval";
$count = Yii::$app->db->createCommand( "select count(1) from icdbval" )->queryScalar();
$arrsort['attributes'] = array( 'id' => array( 'label' => $this->arrtrans[148] ) );
$arrsort['attributes'] += array( 'orgfield' => array( 'label' => $this->arrtrans[149] ) ); //, 'asc' => array('orgfield' => SORT_ASC)
$arrsort['attributes'] += array( 'status' => array( 'label' => $this->arrtrans[91] ) );
$arrsort['defaultOrder'] = array( 'id' => SORT_ASC );
$sort = $arrsort;
$a = 0;
$arrview = array();
$arrview[$a]['attribute'] = 'id';
$arrview[$a]['label'] = $this->arrtrans[148];
$arrview[$a]['encodeLabel'] = false;
$arrview[$a++]['value'] = function ( $data )
{
return $data['id'];
};
$arrview[$a]['attribute'] = 'orgfield';
$arrview[$a]['label'] = $this->arrtrans[149];
$arrview[$a]['encodeLabel'] = false;
$arrview[$a++]['value'] = function ( $data )
{
return $this->get_trans_field( $data['orgfield'] );
};
$arrview[$a]['attribute'] = 'status';
$arrview[$a]['label'] = $this->arrtrans[91];
$arrview[$a]['encodeLabel'] = false;
$arrview[$a]['format'] = 'raw';
$arrview[$a++]['value'] = function ( $data )
{
if( $data['status'] == "0" )
{
$select0 = "selected";
$select1 = "";
}
else
{
$select1 = "selected";
$select0 = "";
}
$id = $data['id'];
$ni = $this->arrtrans[150];
$in = $this->arrtrans[151];
$html = <<< "SCRIPT"
<select class="_statusselect" theval="$id">
<option value="0" $select0>$ni</option>
<option value="1" $select1>$in</option>
</select>
SCRIPT;
// return $data['status'];
return $html;
};
$columnview = $arrview;
$dataProvider = new SqlDataProvider([
'sql' => $sql,
'totalCount' => $count,
'sort' => $sort,
'pagination' => [
'pageSize' => Yii::$app->db->createCommand( "SELECT rowpage from icenvinit" )->queryScalar(),
],
]);
return $this->render( 'itemreport', ['error' => $error, 'success' => $success, 'columnview' => $columnview, 'dataProvider' => $dataProvider, 'sql' => $sql, 'count' => $count, 'listSchedule' => $listSchedule, 'arr_ftp' => $arr_ftp] );
}
and in a view :
<div class="table-responsive">
<?php Pjax::begin(['id' => 'item-report', 'timeout' => false]) ?>
<?
$js = <<< 'SCRIPT'
function changestatus( obj )
{
$( '#successalert' ).css( 'display', 'none' );
$( '#erroralert' ).css( 'display', 'none' );
$.ajax({
type :'POST',
dataType : 'json',
data : ({xval: obj.val(), id: obj.attr( 'theval' )}),
url : 'updateitemreport',
success : function( response )
{
if( response.error )
{
// $( '#successalert' ).css( 'display', 'none' );
// $( '#erroralert' ).html( response.html );
// $( '#erroralert' ).css( 'display', 'block' );
}
else
{
// $( '#erroralert' ).css( 'display', 'none' );
// $( '#successalert' ).html( response.html );
// $( '#successalert' ).css( 'display', 'block' );
}
}
});
}
$( '._statusselect' ).change( function() {
changestatus( $( this ) );
});
SCRIPT;
$this->registerJs( $js, yii\web\View::POS_READY );
?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => $columnview,
]); ?>
<?php Pjax::end(); ?>
</div>
add asc and desc in the options of the attribute eg in your orgfield attribute;
.....
$arrsort['attributes'] = array( 'id' => array( 'label' => $this->arrtrans[148] ) );
$arrsort['attributes'] += array(
'orgfield' => array( 'label' => $this->arrtrans[149],
'asc' => array('orgfield' => SORT_ASC),
'desc' => array('orgfield' => SORT_DESC),
) );
.....
I just need to make a simple string translation (url) with an array of keys and their translations.
Trying like this:
function ruta_iso( $ruta ) {
$slugs = array(
'noticia' => array(
'es' => 'noticia',
'en' => 'post'
),
'pregunta' => array(
'es' => 'pregunta',
'en' => 'question'
),
'consejo' => array(
'es' => 'consejo',
'en' => 'tip'
),
'noticias' => array(
'es' => 'noticias',
'en' => 'news'
)
);
$idioma_defecto = 'es';
$idioma = 'en' ;
if ( ($idioma != $idioma_defecto) && ($ruta == '/') ) {
return "/$idioma";
} else if( $idioma != $idioma_defecto ){
foreach($slugs as $key => $slug){
if ( ( strpos("/$key/", $ruta ) === false ) ){
}else {
$ruta = str_replace( "/$key/", '/'.$slug[$idioma].'/' , $ruta );
}
}
$ruta = "/$idioma$ruta";
} else {
}
return $ruta;
}
echo '-------Ruta Iso '.ruta_iso('/noticias/'); /* Works! */
echo ' -------Ruta Iso '.ruta_iso('/noticias/noticia/'); /* Nope.. */
Can be tested here:
http://codepad.org/3w3Vmncg
It seems to Do the job for one slug, but not if there are more than one, even:
echo ' -------Ruta Iso '.ruta_iso('/noticias/blabla/'); /* Nope.. */
So I am not sure how to try, I mean, I am not breaking the foreach, why is not every string checked?
Any toghts?
You can also try to do so:
function ruta_iso( $ruta = '') {
$slugs = array(
'noticia' => array(
'es' => 'noticia',
'en' => 'post'
),
'pregunta' => array(
'es' => 'pregunta',
'en' => 'question'
),
'consejo' => array(
'es' => 'consejo',
'en' => 'tip'
),
'noticias' => array(
'es' => 'noticias',
'en' => 'news'
)
);
$idioma_defecto = 'es';
$idioma = 'en' ;
foreach( explode('/', $ruta) as $data){
if( !empty($data) ){
if( array_key_exists($data, $slugs)){
$result[] = $slugs[$data][$idioma];
}else{
$result[] = $data;
}
}
}
$result = '/'.$idioma.'/'.implode('/', $result).'/';
return $result;
}
echo '-------Ruta Iso '.ruta_iso('/noticias/');
echo ' -------Ruta Iso '.ruta_iso('/noticias/noticia/');
echo '-------Ruta Iso '.ruta_iso('/noticias/noticia/the-new');
Result:
-------Ruta Iso /en/news/ -------Ruta Iso /en/news/post/
-------Ruta Iso /en/news/post/the-new/
The following is my code which adds documents and fires a query using Solr.
It's showing an error:
SolrInputDocument number 1 is not a valid SolrInputDocument instance
Catchable fatal error: Argument 1 passed to SolrClient::query() must be an instance of SolrParams, string given in /var/www/ps/test.php on line 85
<?php
require_once( 'bootstrap.php' );
$options = array( 'hostname' => SOLR_SERVER_HOSTNAME );
$client = new SolrClient($options);
// Create two documents to represent two auto parts.
$parts = array(
'spark_plug' => array(
'partno' => 1,
'name' => 'Spark plug',
'model' => array( 'Boxster', '924' ),
'year' => array( 1999, 2000 ),
'price' => 25.00,
'inStock' => true,
),
'windshield' => array(
'partno' => 2,
'name' => 'Windshield',
'model' => '911',
'year' => array( 1999, 2000 ),
'price' => 15.00,
'inStock' => false,
)
);
$documents = array();
foreach ( $parts as $item => $fields ) {
$part = new SolrDocument();
foreach ( $fields as $key => $value ) {
if ( is_array( $value ) ) {
foreach ( $value as $datum ) {
$part->addField( $key, $datum );
}
}
else {
$part->$key = $value;
}
}
$documents[] = $part;
}
// Load the documents into the index
try {
$client->addDocuments( $documents );
$client->commit();
$client->optimize();
}
catch ( Exception $e ) {
echo $e->getMessage();
}
// Run some queries.
$offset = 0;
$limit = 10;
$queries = array(
'partno: 1 OR partno: 2',
'model: Boxster',
'name: plug'
);
foreach ( $queries as $query ) {
$queryResponse = $client->query($query);
if ( $queryResponse->getHttpStatus() == 200 ) {
// print_r( $response->getRawResponse() );
if ( $queryResponse->response->numFound > 0 ) {
echo "$query <br />";
foreach ( $queryResponse->response->docs as $doc ) {
echo "$doc->partno $doc->name <br />";
}
echo '<br />';
}
}
else {
echo $queryResponse->getHttpStatusMessage();
}
}
?>
I'm building json sub-array structure (from CSV) using the following PHP:
$tracks = array();
foreach ($result['tracks'] as $trackdata) {
$songId = $trackdata['songId'];
$title = $trackdata['title'];
$ISRC = $trackdata['ISRC'];
$name1 = $trackdata['artists:name[1]'];
$name2 = $trackdata['artists:name[2]'];
$main1 = $trackdata['artists:main[1]'];
$main2 = $trackdata['artists:main[2]'];
$tracks['tracks'][] = array(
'songId' => $songId,
'title' => $title,
'ISRC' => $ISRC,
'artists' => array(
0 => array(
'name' => $name1,
'main' => (boolean) $main1
),
1 => array(
'name' => $name2,
'main' => (boolean) $main2
)
)
);
}
Currently, if the CSV contains empty values the json (correctly) displays the value as NULL.
What would I need to add to my PHP to stop a particular object from being part of the json if its value is empty / blank?
I'm specifically looking to not print artists:name[2] and artists:main[2] if a second artists doesn't exist in the CSV data.
Here is an example of the CSV code:
"trk-04","track 4","USAM18490006","John Smith",true,,
I've researched (and attempted to implement) if (empty... but I'm not sure where that would come in this code.
Any pointers would be great.
Thanks in advance!
You will want to avoid adding the second artist to the intermediate array that you subsequently json-encode.
$tracks = array();
foreach ($result['tracks'] as $trackdata) {
$songId = $trackdata['songId'];
$title = $trackdata['title'];
$ISRC = $trackdata['ISRC'];
$name1 = $trackdata['artists:name[1]'];
$name2 = $trackdata['artists:name[2]'];
$main1 = $trackdata['artists:main[1]'];
$main2 = $trackdata['artists:main[2]'];
$artists = array();
// First artist always exists
$artists[] = array('name' => $name1, 'main' => (boolean) $main1);
// Add second artist only if one exists with a non-null name
if(!is_null($name2)) {
$artists[] = array('name' => $name2, 'main' => (boolean) $main2);
}
$tracks['tracks'][] = array(
'songId' => $songId,
'title' => $title,
'ISRC' => $ISRC,
'artists' => $artists
);
}
You can use the empty function instead of is_null if you wish. It will consider names such as empty strings and the number 0 as not existing. is_null will only catch those which are strictly === null.
like this :
if (!empty($songId))
{
$tracks['tracks']['songId'] = $songId;
}
if (!empty($title))
{
$tracks['tracks']['title'] = $title;
}
and so on ...
$artists[0] = array(
'name' => $name1,
'main' => (boolean) $main1
);
if (!empty($name2)&&!empty($main2))
$artists[1] = array(
'name' => $name2,
'main' => (boolean) $main2
);
$tracks['tracks'][] = array(
'songId' => $songId,
'title' => $title,
'ISRC' => $ISRC,
'artists' => $artists
);
use array_filter to filter out unset date from an array
// assuming $artist is an array you want to scrub
$artist = array_filter($artist);
$track["artists"][] = $artist;
if ( ( ! isset( artists:name[2] ))
|| ( empty( artists:name[2] ))
) {
unset( $tracks['tracks'][ 'artists' ][ 1 ] );
}
Better
$n = 0;
while( ! empty( $trackdata[ 'artists:name[' . $n+1 . ']' ] )) {
$tracks['tracks'][ 'artists' ][ $n ][ 'name' ]
= $trackdata[ 'artists:name[' . $n+1 . ']' ];
$tracks['tracks'][ 'artists' ][ $n ][ 'main' ]
= $trackdata[ 'artists:main[' . $n+1 . ']' ];
$n++;
}