Zend modification. Adding MySQL FORCE INDEX hint - php

I am trying to extend the Zend library in order to get queries like this one:
SELECT * FROM item i **force index(ix)** ORDER BY date LIMIT 100;
I am working arround with this Zend forum issue solution: http://framework.zend.com/issues/browse/ZF-7570
However I have a problem. Look at the code below.
$select->forceIndex('index');
echo $select->assemble();
// I get the right SELECT query with the force index hint
$this->fecthAll($select);
// The server execute a wrong SELECT query without the force index hint
Some help?

I am not pretty sure why, but if I remove the echo clause, fetchAll executes the right query...
So that's the answer, remove echo

In my opinion, the patch you are using is broken. If you check the source, it unsets the FORCE INDEX parts when creating the query the first time.
If you check it, $select->assemble() == $select->assemble() should give false.

Related

PHP Atlas.ORM returns always the same result

I want to load data from a SQLite database in PHP using Atlas.Orm.
When I run the following snippet, I get a set of 1773 results, but each result is the same!
$atlas = Atlas::new('sqlite:[Path To Database]');
$result = $atlas->select(Stop::class)->fetchRecords();
Can anyone tell me whats wrong here?
After several hours of desperation, I found the issue by myself. The ORM needs the PRIMARY_KEY constant in the corresponding *Table class to be set, otherwise fetching records will fail like this.

PHP interprets Query Result as 0

I have come across a strange problem, which im trying to solve for quite some time now but can´t find any solution to this.
I am generating some lines with information which each of includes one checkbox. I have the following code in PHP which checks if a certrain entry exists, if so the checkbox is checked.
$sql = "SELECT COUNT(*) anz FROM jubilaeum WHERE jahr='".$Jahr."' AND mon='".$num."' AND AdrNr='".$RS1_row["AdrNr"]."' AND type='1'";
$rs_erledigt = $db->prepare($sql);
$rs_erledigt->execute();
$row = $rs_erledigt->fetch();
$anz = $row["anz"];
The Code generates me the following SQL Query:
SELECT COUNT(*) anz FROM jubilaeum WHERE jahr='2019' AND mon='5' AND AdrNr='14061' AND type='1'
PHPMyAdmin Query & Result
Now i am using a basic IF to check if there are any records found so i can check a checkbox
<input type="checkbox" name="mychk" id="mychk" value="somevalue" <?php if($anz>0) echo "checked"; ?> />
All checkboxes which have a proper entry in my DB are checked, except the very first one generated, i can swap the boxes around at free will, the first one never gets checked.
I tried to use the $row["Anz"] directly in my IF, didn´t fix the problem.
I think that PHP doesnt interpret the returned value of my query correctly, but i am clueless about how to fix this.
Did someone encounter similar problems and can help me with this?
Im new to posting in here, so please tell me if you need some more information.
Thanks in advance!
Edit: I just tried to change the Query from COUNT(*) to if(COUNT(*)>0,'ja','nein') while also changing the if to if($anz=="ja")
the value of $anz still remains empty.
I found the solution. My issue was a second fetch on my Query. After removing it, everything works fine.

Query in PHP with 'and' or 'or' as variable

I would like to do search for advanced search. The Search feature has and/or for every category. User can choose any combination of and n or. Here i give the screenshot
I store the and/or into variable call $pil, $pil1,$pil2 and $pil3. And will put them in query. it's better than validate one by one every condition of and/or
So this is my query using postgresql in PHP
$query = pg_query("SELECT evaluationdate,onlinename,channel,topik,reviewername,sourceevaluation,evaluation
from AgentPerformance
where onlinename like '%".$VEOn1."%'
".$pil." reviewername like '%".$VERev1."%'
".$pil1." channel like '%".$VEChan1."%'
".$pil2."sourceevaluation like '%".$VESource1."%'
".$pil3."evaluationdate between '".$VEStart1."' and '".$VEEnd1."'");
EDIT :
The problem now, All the variables must not be empty or the query will be error. any way to trick this?
You've missed some spaces near sourceevaluation and evaluationdate
Try with this query :
$query = pg_query("SELECT evaluationdate,onlinename,channel,topik,reviewername,sourceevaluation,evaluation
from AgentPerformance
where onlinename like '%".$VEOn1."%'
".$pil." reviewername like '%".$VERev1."%'
".$pil1." channel like '%".$VEChan1."%'
".$pil2." sourceevaluation like '%".$VESource1."%'
".$pil3." evaluationdate between '".$VEStart1."' and '".$VEEnd1."'");
Simply. Use validation for each $pil whether it is empty or not. it makes me validate 4 times, but it solves the problem. The syntax error has been solved too

Laravel: How to get last N entries from DB

I have table of dogs in my DB and I want to retrieve N latest added dogs.
Only way that I found is something like this:
Dogs:all()->where(time, <=, another_time);
Is there another way how to do it? For example something like this Dogs:latest(5);
Thank you very much for any help :)
You may try something like this:
$dogs = Dogs::orderBy('id', 'desc')->take(5)->get();
Use orderBy with Descending order and take the first n numbers of records.
Update (Since the latest method has been added):
$dogs = Dogs::latest()->take(5)->get();
My solution for cleanliness is:
Dogs::latest()->take(5)->get();
It's the same as other answers, just with using built-in methods to handle common practices.
Dogs::orderBy('created_at','desc')->take(5)->get();
You can pass a negative integer n to take the last n elements.
Dogs::all()->take(-5)
This is good because you don't use orderBy which is bad when you have a big table.
You may also try like this:
$recentPost = Article::orderBy('id', 'desc')->limit(5)->get();
It's working fine for me in Laravel 5.6
I use it this way, as I find it cleaner:
$covidUpdate = COVIDUpdate::latest()->take(25)->get();
Ive come up with a solution that helps me achieve the same result using the array_slice() method. In my code I did array_slice( PickupResults::where('playerID', $this->getPlayerID())->get()->toArray(), -5 ); with -5 I wanted the last 5 results of the query.
The Alpha's solution is very elegant, however sometimes you need to re-sort (ascending order) the results in the database using SQL (to avoid in-memory sorting at the collection level), and an SQL subquery is a good way to achieve this.
It would be nice if Laravel was smart enough to recognise we want to create a subquery if we use the following ideal code...
$dogs = Dogs::orderByDesc('id')->take(5)->orderBy('id')->get();
...but this gets compiled to a single SQL query with conflicting ORDER BY clauses instead of the subquery that is required in this situation.
Creating a subquery in Laravel is unfortunately not simply as easy as the following pseudo-code that would be really nice to use...
$dogs = DB::subQuery(
Dogs::orderByDesc('id')->take(5)
)->orderBy('id');
...but the same result can be achieved using the following code:
$dogs = DB::table('id')->select('*')->fromSub(
Dogs::orderByDesc('id')->take(5)->toBase(),
'sq'
)->orderBy('id');
This generates the required SELECT * FROM (...) AS sq ... sql subquery construct, and the code is reasonably clean in terms of readability.)
Take particular note of the use of the ->toBase() function - which is required because fromSub() doesn't like to work with Eloquent model Eloquent\Builder instances, but seems to require a Query\Builder instance). (See: https://github.com/laravel/framework/issues/35631)
I hope this helps someone else, since I just spent a couple of hours researching how to achieve this myself. (I had a complex SQL query builder expression that needed to be limited to the last few rows in certain situations).
For getting last entry from DB
$variable= Model::orderBy('id', 'DESC')->limit(1)->get();
Imagine a situation where you want to get the latest record of data from the request header that was just inserted into the database:
$noOfFilesUploaded = count( $request->pic );// e.g 4
$model = new Model;
$model->latest()->take($noOfFilesUploaded);
This way your take() helper function gets the number of array data that was just sent via the request.
You can get only ids like so:
$model->latest()->take($noOfFilesUploaded)->puck('id')
use DB;
$dogs = DB::select(DB::raw("SELECT * FROM (SELECT * FROM dogs ORDER BY id DESC LIMIT 10) Var1 ORDER BY id ASC"));
Dogs::latest()->take(1)->first();
this code return the latest record in the collection
Can use this latest():
$dogs = Dogs::latest()->take(5)->get();

Doctrine2 ODM Limit doesn't work / mongodb

I'm trying to skip and limit results, but I don't even get it to limit the results.
here's my code
$limit=5;
$fooQueryBuilder = $this->mongo->getManager()->createQueryBuilder('CustomCoreBundle:Foo');
$foos=$fooQueryBuilder->limit($limit)->getQuery()->execute();
var_dump(count($foos));
exit;
and the var_dump returns
int(321235)
and that's equal to all entities in the database, what am I doing wrong ?
$this->mongo->getManager()
is instance of
Doctrine\ODM\MongoDB\DocumentManager
and the builder is instance of
Doctrine\ODM\MongoDB\Query\Builder"
I just don't understand what's wrong, thanks for any hint
So, I found out the answer myself
it is working !
and I learned:
when you count() a cursor, no matter what the query, it returns the amount of all entities in database.
So my check to count the cursor to see if the limit is working was simply wrong
use count($result->toArray()) that solved my issue
count($result->toArray())
You can use $result->count($foundOnly = true)

Categories