Need help with Zend_db update - zend-framework

Currently I'm working with Zend framework and I need help with Zend_db update in Zend_Db_Table_Abstract class.
Here is my SQL statement
UPDATE user
SET password = '$password',
`enter code here` WHERE email = '$email'
Here is my code in zend_db
public function updatePassword($password,$email)
{
$data = array(
'password' => $password
);
$where = "email = '". $email ."'";
$this->update($data, 'email = '.$email);
}
This only work if I update using int id as my where clause but I wanted to use a email string as a where clause.
Can someone please help me the best way to achieve this?
I wanted to be secure and avoid SQL Injection attack
Thanks so much in advance.

You approach only works with integer values, because the way you concat the where string does not escape the value. So if you do
'email = '.$email
It will product an sql string like this if you use the string "hello world"
WHERE email = hello world
This is an invalid SQL statement so the update does not happen. What you want to produce is a where clause like this
WHERE email = 'hello world'
There are multiple ways to do this, but the safest way to do that via Zend Framework is described in the reference manual under "Example #24 Updating Rows Using an Array of Arrays".
$data = array(
'password' => $password
);
$where['email = ?'] = $email;
$this->update($data, $where);

This code might help you :
public function updateDetails($data, $emailId)
{
$where = array('email = ?' => $emailId);
$this->update($data, $where);
}
Please let me know if you still face the problem.....?

Related

WordPress API passing email argument issue

Using a WordPress REST API custom endpoint, I am attempting to get user data (or at least the user id) with the following code in the functions.php file:
function getUser(WP_REST_Request $request) {
global $wpdb;
$email = $request->get_param( 'email' );
$query = "SELECT * FROM wp_users WHERE user_email = $email";
$result = $wpdb->get_results($query);
return $result;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'myapi/v1', '/getcustomer/(?P<email>[^/]+)', array(
'methods' => 'GET',
'callback' => 'getUser'
) );
} );
Testing the function with the endpoint /wp-json/myapi/v1/getcustomer/joe#anymail.com it returns with empty brackets [ ]. Am I missing something here? Any help would be greatly appreciated.
There are multiple issues with your code:
You should encode your user emails or send it via POST method.
Your current query is open to SQL Injection
Your value must be enclosed in quotes. Now it translates to .. WHERE user_email = joe#anymail.com and that is SQL syntax error.
So your code should look like this:
$query = "SELECT * FROM wp_users WHERE user_email = %s";
$result = $wpdb->get_results($wpdb->prepare($query, $email));

Can't Relate Contact and Opportunity in SuiteCRM / SugarCRM CE

I'm working on a script to import data into SuiteCRM / SugarCRM CE. I need to create a Contact and an Opportunity. I then need to relate the two.
I have a many to many relationship between Contacts and Opportunities. Each contact should be able to create multiple opportunities. Each opportunity should be able to be assigned to multiple contacts.
When I run the code it says "1 Relationship(s) created", but when I check Suite there's nothing listed under the contact or opportunity subpanels.
FYI, I renamed the Opportunities module "Gigs" and am using this API Wrapper: github.com/asakusuma/SugarCRM-REST-API-Wrapper-Class
Here's the code:
<?php
// Load Composer Dependencies for Sugar API Wrapper
require_once('vendor/autoload.php');
// Create Sugar Object
$sugar = new \Asakusuma\SugarWrapper\Rest;
// Set Sugar Connection Items
$sugar->setUrl('https://example.com/suitecrm/service/v2/rest.php');
$sugar->setUsername('User');
$sugar->setPassword('Pass');
// Connect to Sugar
$sugar->connect();
// Did something go wrong with the connection? Report it.
$error = $sugar->get_error();
if($error !== FALSE) {
return $error['name'];
}
// Ok... We're going to try and create a test entry in Sugar/Suite
// Create a Contact
$modules = 'Contacts';
// Set Values
$values = array(
'contact_type_c' => 'Prospect',
'lead_source' => 'Website',
'first_name' => 'Test',
'last_name' => 'Contact',
'phone_mobile' => '(123) 456-7890',
'email1' => 'test#test.com'
);
// Put it in Suite
$result = $sugar->set($modules, $values);
$contactID = $result['id'];
// Ok, now let's create a Opportunity
$modules = "Opportunities";
$values = array(
'name' => 'My Test Gig',
'sales_stage' => 'New Inquiry',
'amount' => '400'
);
$result = $sugar->set($modules, $values);
$gigID = $result['id'];
// Lastly, let's relate the two - HERE'S WHERE I HAVE PROBLEMS!
// Set Relationship
$moduleName = 'Contacts';
$moduleID = $contactID;
$linkFieldName = 'opportunities';
$relatedIDs = array($gigID);
$nameValueList = array(); // Passing empty array because we don't have any fields that need it
$delete = 0;
$result = $sugar->set_relationship($moduleName, $moduleID, $linkFieldName, $relatedIDs, $nameValueList, $delete);
echo $result['created'] . " relationship(s) made";
?>
The Contact and Opportunity are created just fine. It's the relationship that's not happening.
Ugh... Ok, I get it.
I looked at the API documentation and was passing $relatedIDs back as an array. What I didn't realize is that the API was doing this as well. So what got passed into Suite was a multidimensional array instead of a single array.

silverstripe dataobject searchable

I´m trying to have certain DataObjects (News) displayed in the default SearchResult Page. So the result should display normal Pages and News.
Is there an easy way to accomplish that in Silverstripe 3?
Or is it recommended to code it completely custom - I mean a custom controller/action which handles the search request and creates a result list, which I display then in a custom template?
I found this, but obviously search is disabled right now:
https://github.com/arambalakjian/DataObjects-as-Pages
Thx and regards,
Florian
I usually but together a custom search function after enabling FulltextSearchable. So in _config.php I would have
FulltextSearchable::enable();
Object::add_extension('NewsStory', "FulltextSearchable('Name,Content')");
replacing Name and Content with whatever DBField you want to be searchable. And each searchable DataObject have this in their class to enable search indexes (pretty sure this needs to be added and run dev/build before enabling the extension, and only works on MySQL DB).
static $create_table_options = array(
'MySQLDatabase' => 'ENGINE=MyISAM'
);
then in my PageController I have my custom searchForm and results functions.
Here is the search function that returns the search form, called with $search in the template:
public function search()
{
if($this->request && $this->request->requestVar('Search')) {
$searchText = $this->request->requestVar('Search');
}else{
$searchText = 'Search';
}
$f = new TextField('Search', false, $searchText);
$fields = new FieldList(
$f
);
$actions = new FieldList(
new FormAction('results', 'Go')
);
$form = new Form(
$this,
'search',
$fields,
$actions
);
//$form->disableSecurityToken();
$form->setFormMethod('GET');
$form->setTemplate('SearchForm');
return $form;
}
and here the custom results function to handle the queries...
function results($data, $form, $request)
{
$keyword = trim($request->requestVar('Search'));
$keyword = Convert::raw2sql($keyword);
$keywordHTML = htmlentities($keyword, ENT_NOQUOTES, 'UTF-8');
$pages = new ArrayList();
$news = new ArrayList();
$mode = ' IN BOOLEAN MODE';
//$mode = ' WITH QUERY EXPANSION';
//$mode = '';
$siteTreeClasses = array('Page');
$siteTreeMatch = "MATCH( Title, MenuTitle, Content, MetaTitle, MetaDescription, MetaKeywords ) AGAINST ('$keyword'$mode)
+ MATCH( Title, MenuTitle, Content, MetaTitle, MetaDescription, MetaKeywords ) AGAINST ('$keywordHTML'$mode)";
$newsItemMatch = "MATCH( Name, Content ) AGAINST ('$keyword'$mode)
+ MATCH( Name, Content ) AGAINST ('$keywordHTML'$mode)";
//Standard pages
foreach ( $siteTreeClasses as $c )
{
$query = DataList::create($c)
->where($siteTreeMatch);
$query = $query->dataQuery()->query();
$query->addSelect(array('Relevance' => $siteTreeMatch));
$records = DB::query($query->sql());
$objects = array();
foreach( $records as $record )
{
if ( in_array($record['ClassName'], $siteTreeClasses) )
$objects[] = new $record['ClassName']($record);
}
$pages->merge($objects);
}
//news
$query = DataList::create('NewsStory')->where($newsItemMatch);
$query = $query->dataQuery()->query();
$query->addSelect(array('Relevance' => $newsItemMatch));
$records = DB::query($query->sql());
$objects = array();
foreach( $records as $record ) $objects[] = new $record['ClassName']($record);
$news->merge($objects);
//sorting results
$pages->sort(array(
'Relevance' => 'DESC',
'Title' => 'ASC'
));
$news->sort(array(
'Relevance' => 'DESC',
'Date' => 'DESC'
));
//output
$data = array(
'Pages' => $pages,
'News' => $news,
'Query' => $keyword
);
return $this->customise($data)->renderWith(array('Search','Page'));
}
I add all the Page classes I want to be searched and that extend SiteTree in the $siteTreeClasses array, and the News parts can be pretty much copied for any other DataObjectI need searchable.
I am not saying this is the best solution and this can definitely be improved on, but it works for me and this might be a good stating point.
I have adapted #colymba's solution into a silverstripe module: https://github.com/burnbright/silverstripe-pagesearch
It allows setting the pagetype in the url.
You'll need to substantially overwrite SearchForm->getResults().
It uses Database->searchEngine(), but those are tailored towards SiteTree and Page classes.
The "proper" solution is to feed the data into a search engine like Solr or Sphinx.
We have the SS3-compatible "fulltextsearch" module for this purpose:
https://github.com/silverstripe-labs/silverstripe-fulltextsearch
It's going to take some upfront setup, and is only feasible if you can either host Solr yourself, or are prepared to pay for a SaaS provider. Once you've got it running though, the possibilities are endless, its a great tool!

CakePHP - Using a different model in current model

I am creating a custom validation function in my model in CakePHP. After reading similar questions I have understood that I could be using ClassRegistry::init('Model'); to load a foreign model in my current model. But it doesn't say much more on the syntax and how to actually use it afterwards. This is what I have tried, but nothing "is happening" when I am trying to print the array to see if it contains the right stuff. Basically I want to pull out the User data to use it in my validation.
class Booking extends AppModel {
public $name = 'Booking';
public $validate = array(
'start_time' => array(
'noOptionViolation' => array(
'rule' => 'noOptionViolation',
'allowEmpty' => false
)
),
);
public function noOptionViolation ($start_time) {
$this->User = ClassRegistry::init('User');
$allUsers = $this->User->find('all');
print_r($allUsers);
}
Is this correct syntax? Can I use all the methods of $this->User just like I would in a controller?
You can use import as detailed on this post:
https://stackoverflow.com/a/13140816/1081396
App::import('Model', 'SystemSettings.SystemSetting');
$settings = new SystemSetting();
$mySettings = $settings->getSettings();
In your example it would be like:
App::import('Model', 'Users.User');
$user = new User();
$allUsers = $user->find('all');
print_r($allUsers);
You could better use the import at the beginning of the model.
You could use this too to load Models
$this->loadModel('User');
and access all functions by
$this->User

Yii CJuiAutoComplete data from Ajax request

I have a task form for an application I am building which allows me to specify what contact it is assigned to. I had set up a dependent dropdown in Yii with the following code:
echo $form->dropDownList($model,'associationType',
array('none'=>'None','contact'=>'Contact','sale'=>'Sale','account'=>'Account',
'project'=>'Project','case'=>'Case'),
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('tasks/parseType'), //url to call.
//Style: CController::createUrl('currentController/methodToCall')
'update'=>'#auto_complete', //selector to update
)
));
What I'm trying to do is use the CJuiAutoComplete widget with the dropDown specifying which array to grab. So the drop down is selected to contacts, it should get a list of contacts etc.
Here is what I have for the CJui widget
$this->widget('zii.widgets.jui.CJuiAutoComplete', array(
'name'=>'auto_select',
'source' => $names,
'options'=>array(
'minLength'=>'2',
'select'=>'js:function( event, ui ) {
$("#'.CHtml::activeId($model,'associationId').'").val(ui.item.id);
return false;
}',
),
));
The variable $names is just a placeholder for now, but in my controller method I pass it a JSON encoded array with id and name. Controller code:
public function actionParseType() {
//if(isset($_POST['TaskChild']['associationType'])){
//$type=$_POST['TaskChild']['associationType'];
$type='sale';
$sql = 'SELECT id, name FROM x2_'.$type.'s';
$cmd = Yii::app()->db->createCommand($sql);
$res = $cmd->queryAll();
echo CJSON::encode($res);
//}
}
Right now I'm forcing it to use "Sale" but I don't get anything when I call the method, and was wondering how I might go about fixing this. I'm still a little new to Yii so I've been mostly reading wiki/forum posts on how these kinds of thing are done. Any help is greatly appreciated, thanks!
Try something like this in your controller action:
$sql = 'SELECT people_id as id, CONCAT(first_name," ",last_name) as value, first_name as label FROM people WHERE first_name LIKE :qterm ORDER BY first_name ASC';
$command = Yii::app()->db->createCommand($sql);
$qterm = $_GET['term'].'%';
$command->bindParam(":qterm", $qterm, PDO::PARAM_STR);
$result = $command->queryAll();
echo CJSON::encode($result); exit;
Then you can check it by using this in your widget 'options' array: 'select'=>'js:function(event, ui) { console.log(ui.item.id +":"+ui.item.value); }'