How to load objects from sql queries in Joomla 2.5? - sql

Using the Andrew Eddie's tutorials here I am working on building some custom code for menus. Here we go:
$query ->select('id, menutype, title')
->from('#__menu_types')
->where('menutype='.$somemenu);
$db->setQuery($query);
I don't know how to load one object value like I used to do it with Joomla 1.5:
$result = $db->loadObject();
$thetitle = $result->title; // I need this value and I always get error "Notice: Trying to get property of non-object" at this line
How can I SUCCESSFULLY get the value of $thetitle please?

That should work. I see no problem with your code.
The error you are getting is consistent with not having found a match in the database.
Since you do not appear to have any error handling it might even be an SQL error.
Try and add this:
if ($error = $db->getErrorMsg()) {
throw new Exception($error);
}

The correct query is
$query ->select('id, menutype, title')
->from('#__menu_types')
->where('menutype='.$db->quote($somemenu));
$db->setQuery($query);
Now I can get the values of the query correctly.

Related

Laravel: toSql function not displaying query correctly

I am trying to diedump the query on my index screen using this line of code:
dd(DB::table('members')->where('name', '=', 'Tycho')->toSql());
Now the problem is that when I am displaying the query on my screen I get this:
"select * from `members` where `name` = ?"
My final goal of these lines of code is that I can save offline queries and execute them when the application is online. Unless someone has a solution for this, I'll have to save the queries in a database.
You are seeing the ? placeholders as Laravel uses Prepared Statements.
See Ijas Ameenudeen's answer on another SO question which details how to add a toRawSql() macro on the Eloquent builder which will replace the placeholders with the bindings that you supplied to the original query.
This is because you are using the toSql method, you can use the getBindings method to get the values / bindings.
oneliner:
$query = DB::table('members')->where('name', '=', 'Tycho')->toSql();
// will give the raw query with bindings.
$sqlWithBindings = str_replace_array('?', $query->getBindings(), $query->toSql());
You can try this:
DB::enableQueryLog();
DB::table('members')->where('name', '=', 'Tycho')->get();
echo "<pre>";
print_r(DB::getQueryLog());

CodeIgniter4 Model returning data results

I am starting to dabble in CI4's rc... trying to get a head of the game. I noticed that the Model is completely rewritten.
Going through their documentation, I need some guidance on how to initiate the equivalent DB query builder in CI4.
I was able to leverage return $this->findAll(), etc...
however, need to be able to be able to query w/ complex joins and also be able to return single records etc...
When trying something like
return $this->orderBy('import_date', 'desc')
->findColumn('import_date')
->first();
but getting error:
Call to a member function first() on array
Any help or guidance is appreciated.
Suppose you have a model instantiated as
$userModel = new \App\Models\UserModel;
Now you can use it to get a query builder like.
$builder = $userModel->builder();
Use this builder to query anything for e.g.
$user = $builder->first();
Coming to your error.
return $this->orderBy('import_date', 'desc')
->findColumn('import_date');
findColumn always returns an array or null. So you can't use it as object. Instead you should do following.
return $this->orderBy('import_date', 'desc')->first();

Check if an existing value is in a database

I was wondering how I would go about checking to see if a table contains a value in a certain column.
I need to check if the column 'e-mail' contains an e-mail someone is trying to register with, and if something exists, do nothing, however, if nothing exists, insert the data into the database.
All I need to do is check if the e-mail column contains the value the user is registering with.
I'm using the RedBeanPHP ORM, I can do this without using it but I need to use that for program guidelines.
I've tried finding them but if they don't exist it returns an error within the redbean PHP file. Here's the error:Fatal error: Call to a member function find() on a non-object in /home/aeterna/www/user/rb.php on line 2433
Here's the code that I'm using when trying this:
function searchDatabase($email) {
return R::findOne('users', 'email LIKE "' . $email . '"');
}
My approach on the function would be
function searchDatabase($email) {
$data = array('email' => $email);
$user = R::findOne('users', 'email LIKE :email, $data);
if (!empty($user)) {
// do stuff here
} // end if
} // end function
It's a bit more clean and in your function
Seems like you are not connected to a database.
Have you done R::setup() before R::find()?
RedBeanPHP raises this error if it can't find the R::$redbean instance, the facade static functions just route calls to the $redbean object (to hide all object oriented fuzzyness for people who dont like that sort of thing).
However you need to bootstrap the facade using R::setup(). Normally you can start using RB with just two lines:
require('rb.php'); //cant make this any simpler :(
R::setup(); //this could be done in rb.php but people would not like that ;)
//and then go...
R::find( ... );
I recommend to check whether the $redbean object is available or whether for some reason the code flow has skipped the R::setup() boostrap method.
Edited to account for your updated question:
According to the error message, the error is happening inside the function find() in rb.php on line 2433. I'm guessing that rb.php is the RedBean package.
Make sure you've included rb.php in your script and set up your database, according to the instructions in the RedBean Manual.
As a starting point, look at what it's trying to do on line 2433 in rb.php. It appears to be calling a method on an invalid object. Figure out where that object is being created and why it's invalid. Maybe the find function was supplied with bad parameters.
Feel free to update your question by pasting the entirety of the find() function in rb.php and please indicate which line is 2433. If the function is too lengthy, you can paste it on a site like pastebin.com and link to it from here.
Your error sounds like you haven't done R::setup() yet.
My approach to performing the check you want would be something like this:
$count = count(R::find('users', 'email LIKE :email', array(':email' => $email)));
if($count === 0)
{
$user = R::dispense('users');
$user->name = $name;
$user->email = $email;
$user->dob = $dob;
R::store($user);
}
I don't know if it is this basic or not, but with SQL (using PHP for variables), a query could look like
$lookup = 'customerID';
$result = mysql_fetch_array(mysql_query("SELECT columnName IN tableName WHERE id='".$lookup."' LIMIT 1"));
$exists = is_null($result['columnName'])?false:true;
If you're just trying to find a single value in a database, you should always limit your result to 1, that way, if it is found in the first record, your query will stop.
Hope this helps

Does CDbcommand method queryAll() in yii return indexed entries only?

I am trying to retrieve data from a simple mySql table tbl_u_type which has just two columns, 'tid' and 'type'.
I want to use a direct SQL query instead of the Model logic. I used:
$command = Yii::app()->db->createCommand();
$userArray = $command->select('type')->from('tbl_u_type')->queryAll();
return $userArray;
But in the dropdown list it automatically shows an index number along with the required entry. Is there any way I can avoid the index number?
To make an array of data usable in a dropdown, use the CHtml::listData() method. If I understand the question right, this should get you going. Something like this:
$command = Yii::app()->db->createCommand();
$userArray = $command->select('tid, type')->from('tbl_u_type')->queryAll();
echo CHtml::dropdownlist('my_dropdown','',CHtml::listData($userArray,'tid','type'));
You can also do this with the Model if you have one set up for the tbl_u_type table:
$users = UType::model()->findall();
echo CHtml::dropdownlist('my_dropdown','',CHtml::listData($users ,'tid','type'));
I hope that gets you on the right track. I didn't test my code here, as usual, so watch out for that. ;) Good luck!

Cannot add new Workitems using TFS API

Hi I am trying to add new workitems to the TFS repository using the API, but when I validate the workitem before it is saved, it returns an error. I previously got exceptions regarding the field definitions for a bug namely, Symptom, Steps to Reproduce and Triage. (Error code TF 26027). The code snippet is shown below: Can anyone tell me what's wrong here?
switch (workItemType)
{
case "Bug":
{
workItem.Title = values["Title"].ToString();
workItem.State = values["State"].ToString();
workItem.Reason = values["Reason"].ToString();
workItem.Fields["Priority"].Value = values["Priority"].ToString();
workItem.Fields["Severity"].Value = values["Severity"].ToString();
//workItem.Fields["Triage"].Value = values["Triage"].ToString();
workItem.Fields["Assigned To"].Value = values["Assigned To"].ToString();
//workItem.Fields["Symptom"].Value = values["Symptom"].ToString();
//workItem.Fields["Steps to Reproduce"].Value = values["Steps to Reproduce"].ToString();
// Validate the Work Item fields.
ArrayList result = workItem.Validate();
// If any invalid fields are returned, report an error.
if (result.Count > 0)
MessageBox.Show("An Error occurred while adding the Bug to the repository.");
else
workItem.Save();
}
break;
To find the available field definitions, you can iterate over the collection (FieldDefinitions). The Name and ReferenceName properties are the values you can index by into the collection.
the Field "Symptom" cannot be empty
Just reading the error message it looks like you are defining a field called "somefield" in your work item. I'm thinking that you have some old code hanging around elsewhere, maybe above the code snippet you posted, where you are defining a value for workItem.Fields["somefield"]
Old question, but hopefully helps someone. The field name is "Repro Steps"
.Fields["Repro Steps"].Value