How do I write a search query using Kohana PHP? - php

I have a table (product_shoppingcart) with 4 columns :
id, product_id, shoppingcart_id, product_quantity.
I'm using Kohana's ORM.
I want to write a search query which returns all the rows where the shoppingcart_id column contains 1 (for example).
I already tried:
$arr = ORM::factory('product_shoppingcart')->where('shoppingcart_id',$shoppingcartID)->find_all();
but that doesn't work.
Can anyone please help me out?

Your example code should work, but perhaps the problem is that you're not iterating over your result set?
$results = ORM::factory('product_shoppingcart')
->where('shoppingcart_id', $shoppingcartID)
->find_all();
foreach ($results as $product_shoppingcart) {
print Kohana::debug($product_shoppingcart->as_array());
}
If you have more than one row with that id, this should give you a result iterator in $results, which you then walk with the foreach loop. I have lots of examples of similar working code, if you're still not able to get it working.

Here is what it would look like:
$arr = ORM::factory('product_shoppingcart')->where(
'shoppingcart_id',"=",$shoppingcartID)->find_all();

Shouldnt your table be "product_shoppingcarts" or am I missing something?

Related

Trying to delete all rows in database that do not match array

I am trying to figure out how to delete all ids in the database that do not exist in an array. I have been trying to use NOT IN in my query but I am not sure why it wont work when running it in a script the same way it works when I manually enter it into mysql. Here is an example.
mysqli_query($con, "DELETE FROM table WHERE id NOT IN ($array)");
$array is a list of ids from a json api. I use CURL to fetch the ids and I am trying to delete all ids in the database that do not match the ids in $array.
First I use another simple CURL script to scrape the apis and insert the ids found into the database and what I am trying to do here is basically make a link/data checker.
If the ids in the database are not found in the array when rechecking them then I want them deleted.
I thought that the query above would work perfect but for some reason it doesn't. When the query is ran from a script the mysql log shows the queries being ran as this.
Example:
DELETE FROM table WHERE id NOT IN ('166')
or this when I am testing multiple values.
DELETE FROM table WHERE id NOT IN ('166', '253', '3324')
And what happens is it deletes every row in the table every time. I don't really understand because if I copy/paste the same query from the log and run it manually myself it works perfect.
I have been trying various ways of capturing the array data such as array_column, array_map, array_search and various functions I have found but the end result is always the same.
For right now, just for testing I am using these 2 bits of code for testing 2 different apis which gives me the same sql query log output as above. The functions used are just a couple random ones that I found.
//$result is the result from CURL using json_decode
function implode_r($g, $p) {
return is_array($p) ?
implode($g, array_map(__FUNCTION__, array_fill(0, count($p), $g), $p)) :
$p;
}
foreach ($result['data'] as $info){
$ids = implode_r(',', $info['id']);
mysqli_query($con, "DELETE FROM table WHERE id NOT IN ($ids)");
}
And
$arrayLength = count($result);
for($i = 0; $i < $arrayLength; $i++) {
mysqli_query($con, "DELETE FROM table WHERE id NOT IN ('".$result[$i]['id']."')");
}
If anyone knows what is going on i'd appretiate the help or any suggestions on how to achieve the same result. I am using php 7 and mysql 5.7 with innodb tables if that helps.
It probably doesn't work because your IN value is something like this
IN('1,2,3,4');
When what you want is this
IN('1','2','3','4')
OR
IN( 1,2,3,4)
To get this with implode include the quotes like this
$in = "'".implode("','", $array)."'";
NOTE whenever directly inputting variables into SQL there is security Implications to consider such as SQLInjection. if the ID's are from a canned source you're probably ok, but I like to sanitize them anyway.
You can't mix array and string.
This works:
mysqli_query($con, "DELETE FROM table WHERE id NOT IN (".implode(',', $ids).")");

laravel grouping by multiple columns

Im using laravel 5.2 and I want to group a table based on the value of two columns (configuration and type). So basically if two or more rows in the table have the same configuration and type they will be grouped.
I've tried querying like this and its not working:
$groups = Model::where('active', 1)->get()->groupBy('type_id', 'configuration_id');
Any suggestions?
EDIT: I think I'm using the wrong query. What I want to do is get the rows that have the same values in these two columns and have them grouped. Apparently group by is used to aggregate things e.g if I want a sum or something.
EDIT 2: Actually the groupby here I'm using is not part of the query it is a helper function provided by laravel to use on collections see this link Does anyone know if it groups by two feilds??
Ok I've figured it out.
The groupBy method I'm using is not a query it is a laravel function that groups collections by a certain field. You can see the documentation here. So the workaround was to do the grouping twice like this.
$groups = Model::where('active', 1)->get()->groupBy('type_id');
foreach ($groups as $group) {
$grouped[] = $group->groupBy('configuration_id');
}
Pass Columns names in array form this is working for me
$groups = Model::where('active', 1)->groupBy(['type_id', 'configuration_id','etc']);
$groups = Model::where('active', 1)->groupBy('type_id', 'configuration_id')->get();
Try like this
$groups = Model::where('active', 1)->groupBy('type_id', 'configuration_id');
$groups = Model::where('active', 1)->groupBy('type_id', 'configuration_id')->get(['type_id', 'configuration_id']);

Laravel 5 eloquent whereIn

Hope anybody can help me, I need to search for items that have category id = x in the database
Example table items
id,cats,name etc...
cats = '1,19' or maybe just '19' or maybe '1,9'
So for this example I need a to search for items that have cats with 9
I tried this but when I search for 9 it also shows 19
$items = Items::where(function($query)use($cat) {
$query->where('cats', 'like', '%,'.$cat->id.'%');
$query->orWhere('cats', 'like', '%'.$cat->id.',%');
$query->orWhere('cats', 'like', '%'.$cat->id.'%');
})->orderBy('updated_at', 'DSC')->get();
I also tried something
$items = Items::whereIn(explode(',', 'cats'), $cat->id)->get();
but it doesn't work
Appreciate any help to find the easiest and shorts way of doing this, regards
It's quite hard to understand what you want to achieve but I'll try. First of all as #particus mentioned the best way is to create pivot table when you don't need to worry about such things.
But the solution if you have list of ids in a columns separated by coma is not storing values like
1,2,3
but always adding , at the beginning and at the end, so it should be in this case:
,1,2,3,
This way, if you have in your table ,19,2,3, and you want to search for value 9, you should use look for ,9, string, for example:
$id = 9;
$items = Items::where('column', LIKE '%,'.$id.',%')->get();
Now for above string no record will be found, but if you have ,9,2,3, or just ,9, the desired record will be found.
Assuming you're using MySQL, you can use the FIND_IN_SET function.
$items = Items::whereRaw("FIND_IN_SET(".$cat->id.", cats)")->orderBy('updated_at', 'DESC')->get();
Please note, this will not use any indexes defined on the cats column. Storing array like data in a field is usually a big red flag. You would benefit by normalizing this out now, rather than trying to work around the current design.

Creating an array by looping through a mySQL database, capturing entries only once in PHP

i'm relatively new to coding and I need a little help. I'm basically trying to loop through an entry in a mySQL database and push any new entry into an array , so that it only comes up once in my array.
// SQL query
$response = $bdd->query('SELECT serie_bd FROM inventaire_bd');
//creating array to group all elements from the db so that they do not repeat
$serie_bd_groupe=array();
while($data_collected = $response->fetch())
{
if(array_key_exists($data_collected,$serie_bd_groupe)==false)
{
array_push($data_collected,$serie_bd_groupe);
}
}
Will this work? - it seems like the loop will just stay stuck after it comes accross an entry a second time because the if statement wont execute itself.
Also in the future, are their any php equivalent to jsfiddle.net so i can test code syntaxically?
Thank you for your time
Your array keys will be default integers, so you don't want to check those. Instead of this:
if(array_key_exists($data_collected,$serie_bd_groupe)==false)
you should do this:
if(!(in_array($data_collected,$serie_bd_groupe)))
http://php.net/manual/en/function.in-array.php
On the other hand, if you're expecting your collected data to be the array key rather than value, you'd do something like this, instead of your array_push:
$serie_bd_groupe[$data_collected] = 1;
then your key check would work.
If you are looking for UNIQUE values (serie_bd) from your database, update your query to include "DISTINCT" like this:
$bdd->query('SELECT DISTINCT serie_bd FROM inventaire_bd');
On the other hand, I think you are looking for http://phpfiddle.org/

Trouble retrieving data using PDO syntax, PHP

I'm brand new to the PDO syntax and I'm liking the learning curve! I'm refactoring code - migrating over from archaic mysqli_* methods.
Predictably, I've run into some snags, being a novice. One of the big ones is (forgive if this is a dumb question) retrieving data from the DB and echoing it out on the page. Here is what I have so far:
$getURLid = $_GET['id'];
$idQuery = $connection->prepare("SELECT * FROM pages WHERE page_id = :getURLid");
$idQuery->execute(array(':getURLid' => $getURLid));
$idRetrieved = $idQuery->fetchAll(); // This is the part I'm unclear on.
When I echo $idRetrieved['value'] to the page, nothing shows up. I'm missing something or misunderstanding how it works. Maybe fetchAll isn't what I should be using.
If it is, is a loop necessary to retrieve all rows? I was under the impression that fetchAll would loop through them automatically based on what I've read.
Thanks for the help.
Read the doco for PDOStatement::fetchAll closely. It returns an array of row data.
The type of data representing each row depends on your fetch mode which by default is PDO::FETCH_BOTH. This would mean each row is an array with both numeric and associative keys. If you're only going to access the data associatively, I'd recommend using PDO::FETCH_ASSOC, eg
$idRetrieved = $idQuery->fetchAll(PDO::FETCH_ASSOC);
You would then either need to loop or access each row via its index, eg
foreach ($idRetrieved as $row) {
echo $row['value'];
}
// or
echo $idRetrieved[0]['value']; // assuming there's at least one row.

Categories