update record in database using jdatabase - joomla3.0

How do to use jdatabase to update a record in Joomla3. Here is what i have so far.
$db =& JFactory::getDBO();
$query = $db->getQuery(true);
$query->update('#__test AS h');
$query->set('h.name = 'apple', h.description= 'orange', h.url = 'bannana'');
$query->where('h.id=1');
$db->setQuery($query);
Am i missing something simple?

I just spent the day banging my head against the wall with this too. You're very close, but you just need some minor tweaks.
$query->set('h.name = 'apple', h.description= 'orange', h.url = 'bannana'');
should be (note the quotes):
$query->set('h.name = "apple", h.description= "orange", h.url = "bannana"');
Also:
$db =& JFactory::getDBO();
will throw a "Strict Standards" warning in developer mode. Just remove the ampersand.
The missing piece:
try {
$result = $db->execute();
} catch (Exception $e) {
die($e->getMessage());
}
P.S. I realize this answer is a bit late so I hope that you've solved your problem by now. I am posting this answer for those who come across it later and can't find the solution in Joomla's shitty documentation.

Related

How to Unserialize this data in wordpress

CURRENT ISSUE: I am making one plugin for listing users with there user role in WP_LIST_TABLE table.
This is my query
$this->items = $wpdb->get_results($wpdb->prepare("SELECT {$wpdb->users}.*, {$wpdb->usermeta}.meta_value as roles FROM {$wpdb->users}
LEFT JOIN {$wpdb->usermeta} ON {$wpdb->users}.ID = {$wpdb- >usermeta}.user_id
WHERE {$wpdb->usermeta}.meta_key = '{$wpdb->get_blog_prefix()}capabilities'
ORDER BY {$wpdb->users}.display_name", $per_page, $paged), ARRAY_A);
It display out like This
[roles] => a:1:{s:13:"administrator";b:1;}
How to Unserialize this data. and I want to display the First name too using this query please help me
Finally this helps me.
$input = unserialize($item['roles']);
$result = array();
foreach($input as $key => $value){
$result[] = $key;
}
$userRole = implode(",", $result);
return $userRole;
Try below code:
foreach($this->items as $value){
echo $value->COLUMN_NAME ."<br>";
}
Please change the COLUMN_NAME to whichever column you want to display. If there's a column named e_name, then write "$value->e_name".
Its tried and tested. It works for me. Let me know if it works for you!

use preg_replace_callback with array

I know this has been asked elsewhere, but I can't find the precise situation (and understand it!) so I'm hoping someone might be able to help with code here.
There's an array of changes to be made. Simplified it's:
$title = "Tom's wife is called Tomasina";
$change_to = array(
"Tom" => "Fred",
"wife" => "girlfriend",
);
$title = preg_replace_callback('(\w+)', function( $match )use( $change_to ) {
return $array[$match[1]];
}, $title);
I'm hoping to get back "Fred's girlfriend is called Tomasina" but I'm getting all sorts of stuff back depending on how I tweak the code - none of which works!
I'm pretty certain I'm missing something blindingly obvious so I apologise if I can't see it!
Thank you!
There are several issues:
Use $change_to in the anonymous function, not $array
Use regex delimiters around the pattern (e.g. /.../, /\w+/)
If there is no such an item in $change_to return the match value, else, it will get removed (the check can be performed with isset($change_to[$match[0]])).
Use
$title = "Tom's wife is called Tomasina";
$change_to = array(
"Tom" => "Fred",
"wife" => "girlfriend",
);
$title = preg_replace_callback('/\w+/', function( $match ) use ( $change_to ) {
return isset($change_to[$match[0]]) ? $change_to[$match[0]] : $match[0];
}, $title);
echo $title;
// => Fred's girlfriend is called Tomasina
See the PHP demo.
Also, if your string can contain any Unicode letters, use '/\w+/u' regex.

Hash and array with Perl

I have a .plist file that can be seen by Data::Dumper into this form
$VAR1 = {
'SPOOLS' => [
'SPOOL1',
'SPOOL2',
'SPOOL3'
],
'path' => '/usr/local/thanks/for/your/help',
'contentMatch' => [
{
'priority' => '1',
'match' => '*.hello'
},
{
'match' => '*.guys',
'priority' => '2'
}
]
};
To access my .plist file in Perl, I use this code:
my $locPlist = "conf.plist";
my $configdict = NSDictionary->dictionaryWithContentsOfFile_($locPlist);
my $plistref = Foundation::perlRefFromObjectRef($configdict);
my %plist = %{$plistref};
I know how to access the "path" with "$plist{path}" and the SPOOLS array with "$plist{SPOOLS}[0]" but:
How can I get the of SPOOLS into an array, something like my #array = $plist{SPOOLS} and how can I also get the content of "contentMatch" ?
Thanks for your help!
EDIT:
Thank you so much for your help, I was able to access the data. But is there a cleaner way to get back the content from contentMatch in a hash and access directly instead of doing that:
my $number_matches = scalar #{ $plistref->{contentMatch} } ;
my $a = 0;
my %events;
foreach ( #{ $plistref->{contentMatch} } ) {
$events{match}[$a] = $_->{match};
$events{priority}[$a] = $_->{priority};
$a = $a+1;
}
Best,
Tim.
my #spools = #{ $plistref->{SPOOLS} };
my #content_match = #{ $plistref->{contentMatch} };
Or, to dig a little deeper into the contentMatch example:
foreach ( #{ $plistref->{contentMatch} } ) {
say "match: $_->{match}";
say "priority: $_->{priority}";
}
Plenty more information about dealing with complex data structures in Perl in the Perl Data Structures Cookbook.
Update: You ask for help accessing the contentMatch data in another way. I'm not really sure what you're asking - all your sample code seems to do is to transpose an array of hashes into a hash of arrays. And I think that the array of hashes is a much better representation of of the data.
But it's your code and your data. So I think this is how I'd write what you're trying to do.
my %events;
foreach ( #{ $plistref->{contentMatch} } ) {
push #{ $events{match} }, $_->{match};
push #{ $events{priority}, $_->{priority};
}
I'd be far happier keeping it as an array of hashes, and I've already given you that code.
my #content_match = #{ $plistref->{contentMatch} };
I think that understanding how complex data structures work in Perl is crucial to becoming a competent Perl programmer. I highly recommend getting to grips with the examples in perldsc.

Perl -- unable to construct array of objects

I've tried two similar bits of syntax. This first one works:
my $obj = PI::something::ObjectManipulator->new();
$obj->setValue('HELLO');
my $objList = [$object];
This, however, doesn't:
my $objList= [];
foreach my $value (#values) {
my $obj = PI::something::ObjectManipulator->new();
$obj->setValue($value);
push #$objList, $obj;
};
What is the difference between these two way of doing things? Why doesn't the second work? (By not work, it seems to be that $objList is still empty at the end of the code.)
Assuming my $objList = [$object]; is a typo for my $objList = [$obj];, and assuming, my #values = 'HELLO';, there are no differences.
Assuming you meant "#$objList is still empty" when you said "$objList is still empty", that can only happen if the loop isn't entered (i.e. #values is empty).

Saving multiple rows in a single query

Is there anyway to have cake do a multi-row insert in a single query without writing raw SQL to do this? The saveMany and saveAssociated options will only save multiple rows in a single transaction, but that transaction contains multiple insert statements so these methods are clearly not a solution to write heavy applications.
Thanks for reading.
Yes
Though it's not a common practice to do so in app-land code, and doing so removes the possibility to use almost any application logic (validation rules, behaviors, events etc.). You can see an example of doing this in the way fixtures are loaded:
$db = ConnectionManager::getDataSource('default');
$table = "stuffs";
$fields = array('id', 'name');
$values = array(
array(1, 'one'),
array(2, 'two'),
...
);
$result = $db->insertMulti($table, $fields, $values);
You may also find this repository useful (either directly or as a basis for your code) which loads fixture files into your app database - using multi-inserts.
Yes, Big_Data is good idea for inserting bulk. But as AD7six note, it still use basic value quoting and does not return insert ids. And base on your ideas, i wrote small script to inserting bulk in a single query, using default CakePHP quoting and returning ids of inserted records.
$count = count($records);
$dbSource = $this->getDataSource();
$table = $dbSource->fullTableName($this->table);
$fields = $dbSource->prepareFields($this, array('fields' => array_keys($records[0])));
$values = array();
foreach ($records as $index => $record) {
if (!is_array($record) || !$record) {
return null;
}
foreach ($record as $column => $value) {
$values[$index][$column] = $dbSource->value($value, $this->getColumnType($column));
}
$values[$index] = '(' . implode(',', $values[$index]) . ')';
}
$query = 'INSERT INTO %s (%s) VALUES %s;';
$query = sprintf($query, $table, implode(',', $fields), implode(',', $values));
if (!$dbSource->execute($query)) {
return false;
}
$lastInsertId = $dbSource->getConnection()->lastInsertId();
$insertIds = array();
for ($i = 0; $i < $count; $i++) {
$insertIds[] = $lastInsertId + $i;
}
return $insertIds;
Someone pointed me towards the Big Data Behavior https://github.com/jmillerdesign/CakePHP_Big_Data
If you are using CakePHP 3.0 you can check the answer to this question: How to use insert in query builder insert multiple records?
If you are using CakePHP 2 you will have to use raw SQL like this:
$sql = "INSERT INTO `people` (`name`,`title`) VALUES ";
foreach($people as $person){
list($name,$title) = $person;
$sql.= "('$name','$title'),";
}
$this->query(substr($sql,0,-1));
Source: Inserting Multiple Rows with CakePHP 3
yes you can use like below
The getDataSource() method is static in CakePHP 2.x, so you should be able to use:
$db = ConnectionManager::getDataSource('default');
$db->rawQuery($some_sql);
here i am posting method to do. you have to create some SQL statement manually to insert multiple row in one time.
Please let me know if i can help you more.

Resources