extract data in a database in joomla - joomla2.5

I tried to extract a specific data in a table but my code does work:
$db =& JFactory::getDBO();
$query = "SELECT * FROM #_contact_details WHERE user_id = 43;";
$db->setQuery($query);
$results = $db->loadObjectList();
$results = $results["name"];
results does not give anything.
anyone have an idea?
thank you in advance

The $result is an array of stdClass Object. If you want to access the value You've to use:
$results = $results[0]->name;
Hope this helps!

$results is not giving anything because loadObjectList() returns array of object so the result(structure) would be for one row similar to this-
print_r($results)
Array
(
[0] => stdClass Object
(
[name] => "test"
)
)
so you can read data like this $results = $results[0]->name;
You can read here
Hope this will help.

Related

Doctrine: Check if any value in the db is a substring of input

I want to check if there is anything in the database that is a substring of a value, in this case $name.
I have checked here, but SUBSTRING requires me to set a start index as parameter.
LIKE with wildcards also doesn't seem to help, as it does exactly the opposite of what I want: it checks if the input is a substring of a db-value.
So what I want is to check if a db-value is a substring of the variable $name. So far I tried this:
$qb = $this->getEntityManager()->createQueryBuilder();
$qb
->select('d')
->from('MyBundle:MyEntity', 'd')
->where(
$qb->expr()->eq($qb->expr()->substring('d.name',1), ':name')
)
->setParameter('name', $name);
But this is not quite it yet. Can anyone help me out with this?
There is LOCATE function in doctrine but I couldn't make it work so I think you can just use LIKE for such basic requirement.
public function findLeague($name)
{
$qb = $this->createQueryBuilder('l');
$qb
->select('l')
->where($qb->expr()->like('l.name', ':name'))
->setParameter('name', '%' . $name . '%');
$qb = $qb->getQuery()->getResult();
return $qb;
}
It would return:
'1','Spanish Liga'
'3','German Bundes Liga'
'6','French Ligue One'
'7','Lig'

Illegal string offset 'order_status_id' in opencart

I am getting error Illegal string offset 'order_status_id' when I want to get loop data in view
Here's the code:
controller.php
if (isset($_POST["email"])) {
$email = $_POST["email"];
}
$this->load->model('order/myorder');
$data['data1'] = $this->model_order_myorder->getOrder($email) ;
view.php
foreach ($data1 as $row) {
echo echo $row->order_id;
}
model.php
class ModelOrderMyorder extends Model {
public function getOrder($email) {
$sql = "SELECT * FROM ".DB_PREFIX."order, ".DB_PREFIX."order_product WHERE ".DB_PREFIX."order.email = '$email'";
$query = $this->db->query($sql);
return $query ;
}
}
Still not getting it showing Trying to get property of non-object in view.
First off, if you want to iterate through all the order products for a given email (which is what I think you want) you should change the getOrder() method to return:
return $query->rows;
Then in the controller you need to change:
$data['data1'] = $this->model_order_myorder->getOrder($email) ;
to
$this->data['data1'] = $this->model_order_myorder->getOrder($email);
Finally, in your view, you'll be accessing an array not an object so you should lose the extra echo (assuming this is a typo) and change:
echo echo $row->order_id;
and get the index as:
echo $row['order_id']
Also, in addition to the above, I'll suggest you utilize some of the methods and code conventions found in Opencart:
When accessing the $_POST global you can use the sanitized
version $this->request->post
Your query fails to backtick the order table which can result
in errors in you didn't set a prefix. And you are not escaping
$email which is a good idea for a number of reasons. Also, it makes
things easy if you give your tables an alias. Finally, a join on the
tables... so I might consider rewriting that query like this:
$sql = "SELECT * FROM `" . DB_PREFIX . "order` o LEFT JOIN " . DB_PREFIX . "order_product op USING (order_id) WHERE o.email = '" . $this->db->escape($email) . "'";
To be honest, I'm not sure what results you're expecting from that query but bear in mind that if there are multiple products for an given order you will end up with multiple rows returned.
Just a few tips.. hopefully this is useful to you.

Parse CSV based on random header layout perl

I am trying some code using Tie::Handle::CSV, however I suppose this could be done using other modules or none at all.
What I want to do is take a file of random layout and match it to what I predict the headers will be. Then I want to arrange it to my table structure.
DATA
First Name,last name,date of birth
Jim,Johansen,08/25/1989
OR
2nd Name,1st Name,D.O.B
Johansen,Jim,08/25/1989
OR
2nd Name,1st Name,D.O.B,city,county
Johansen,Jim,08/25/1989,milwaukee,N/A
As you can see, I have varying data structures. I want it to arrange them to my schema, even if the fields I request are empty. The way I want to do this is by searching my input with my column variables.
Here is what I am trying.
Code
use Tie::Handle::CSV;
my $name1 =qr/First Name|Name|1st Name/i;
my $name2 =qr/Last Name|Maiden Name|2nd Name/i;
my $date_of_birth =qr/date of birth|D.O.B/i;
my $city =qr/city|town/i;
my $csv_fh = Tie::Handle::CSV->new('list.txt', header => 1);
while (my $csv_line = <$csv_fh>)
{
print $csv_line->{'$date_of_birth'}.",".$csv_line->{'$name1'}." ".$csv_line->{'$name2'}.",".$csv_line->{'$city'}.\n"; ##note I am searching for the column {$'colummn regex'} instead of {'column'} to see if my input file matches any of the header options.
}
close $csv_fh;
My output is blank since this module is not understanding the regex I am implimenting. However, my output would contain the columns specified if I used their literal names, i.e.
The out put I want would be:
Scenario 1
Date of Birth,Name,City ##my implemented header
08/25/1989,Jim Johansen, ##noting also that if there is no 'city' in the input data, leave blank.
Scenario 2
Date of Birth,Name,City ##my implemented header
08/25/1989,Jim Johansen,
Scenario 3
Date of Birth,Name,City ##my implemented header
08/25/1989,Jim Johansen,milwaukee
Perhaps there is a better option than a module or even my regex variables. Has anyone had to parse csvs in ever changing layouts?
You never use $name1, $name2, etc, much less in a match (or substitution) operator, so you ever execute any regex match.
my $field_names = $csv_fh->header();
my ($name1_header) = grep /First Name|^Name$|1st Name/i, #$field_names;
my ($name2_header) = grep /Last Name|Maiden Name|2nd Name/i, #$field_names;
my ($dob_header ) = grep /date of birth|D\.O\.B/i, #$field_names;
my ($city_header ) = grep /city|town/i, #$field_names;
my #recognized_fields = ( $name1_header, $name2_header, $dob_header, $city_header );
my %recognized_fields = map { $_ => 1 } #recognized_fields;
my #other_headers = grep !$recognized_fields{$_}, #$field_names;
while (my $row = <$csv_fh>) {
my $name1 = $name1_header ? $row->{$name1_header} : undef;
my $name2 = $name2_header ? $row->{$name2_header} : undef;
my $dob = $dob_header ? $row->{$dob_header } : undef;
my $city = $city_header ? $row->{$city_header } : undef;
my #other_fields = #$row{#other_headers};
...
}

How to get the *total* number of results from a paginated `findBy` in Doctrine2?

I'm trying to see if there is a way to do pagination with Doctrine2 without writing custom DQL. I've found that the findBy() function returns the result set that I want, however I'm missing one piece of information to properly paginate on the UI, namely the total number of records that the result could have returned.
I'm really hoping that this is possible, since it's a "simple" one liner.
$transactions = \Icarus\Entity\ServicePlan\Transaction::getRepository()->findBy(array('user' => $userId, 'device' => $device), null, $transactionsPerPage, $currentPage);
Does anyone know how/if I can get this information from the findBy() function?
Short anwser, no. You're essentially running this query:
SELECT * FROM transaction WHERE user = $userId AND device = "$device" LIMIT $currentPage, $transactionPerPage;
By specifying a limit, the query is only going to return the amount of rows from your offset inside that limit. So if $transactionPerPage = 10, the total rows returned by that query will be 10.
Assuming the total count is somewhat static, I would suggest first running a count on the total matching documents on the first page request and caching that result ( or storing in sessions ), so you only need to grab the total count once.
edit: Example of count query, using just normal php sessions:
if ( !isset( $_SESSION['transactionCount'] ) )
{
$transactionCount = $em->createQuery('SELECT COUNT(*) FROM \Icarus\Entity\ServicePlan\Transaction WHERE user = ?1 AND device = ?2')
->setParameters( array( 1 => $userId, 2 => $device ) )
->getSingleScalarResult();
$_SESSION['transactionCount'] = $transactionCount;
}
edit2: If you really dont want to use DQL, you can run your .findBy() with out the offset and limit, and do a sizeof on the results:
$transactions = \Icarus\Entity\ServicePlan\Transaction::getRepository()->findBy(array('user' => $userId, 'device' => $device) );
$totalTransactions = sizeof( $transactions );
But the performance on this wont be as good, as you are actually fetching all the objects.
Did you try this ?
$queryBuilder->select('p.id, p.name')
->from('\Api\Project\Entity\Project', 'p')
->where('p.status = :status')
->setParameter('status', 1)
->orderBy('p.createdDate', 'asc')
->setFirstResult($page)
->setMaxResults($limit);

How to use the in statement in DQL in Doctrine 2.0

I have the following query that uses an IN statement.
$ids = array(1,2,3);
$query = 'select o from Organisation o where o.id in (:ids)';
$this->_entityManager->createQuery($query)
->setParameter('ids', implode(', ', $ids))
Doctrine is not returning any results, I think it is because of something wrong in the conversion that Doctrine does for the passed parameter $ids which is an array.
How to make it work?
Try passing the array itself to ->setParameter(...) instead of imploding it into a string.
I used this (setParameter didn't seem to work for me):
$em->createQuery('SELECT users FROM Entities\User users WHERE users.id IN (:ids)')
->setParameters(array('ids' => $ids));
http://redbeardtechnologies.wordpress.com/2011/07/01/doctrine-2-dql-in-statement/
I solved this:
$con = $this->getEntityManager();
$query = $con->createQuery("SELECT cl
FROM BackendBundle:classifieds cl
INNER JOIN BackendBundle:locations lo WITH cl.locationId = lo.id
INNER JOIN BackendBundle:municipality mu WITH lo.municipalId = mu.id
WHERE cl.verified = false AND mu.id = ".$munId." AND cl.locationId NOT IN (:ids) ");
$query->setParameters(array('ids' => $locsIds));
return $query->getResult();
I'm struggling with the IN statement too, using the $query->expr()->in() construct...
Try:
$em->createQuery(“SELECT users FROM Entities\User users WHERE users.id IN (':ids')”)
->setParameters(array(‘ids’ => $ids));
I think the simple quotes around your parameters in the IN() part are necessary...