Codeigniter how to not select duplicated id's - php

I've got a database and the fetched array looks something like this (if i was creating the arrays my self)
<?php
$array[] = array('id' => 1, 'message' => 'test');
$array[] = array('id' => 1, 'message' => 'test');
$array[] = array('id' => 2, 'message' => 'test');
$array[] = array('id' => 5, 'message' => 'test');
$array[] = array('id' => 1, 'message' => 'test');
$array[] = array('id' => 8, 'message' => 'test');
$array[] = array('id' => 5, 'message' => 'test');
$array[] = array('id' => 1, 'message' => 'test');
?>
As you can see, there is a few arrays with the ID 1, and i wanna select the last 5 items but if there is a duplicate, i wanna skip it, and move on. Is there any easy solution for this?

Are you using the Active Record Class?
If so add this line to your query, before your get your results:
$this->db->distinct();
For current and future reference CI has and is praised for it's brilliant Documentation!
It is always worth taking a look there too:
http://codeigniter.com/user_guide/database/active_record.html
If you don't use the Active Record Class, do as suggested above :).

you should use a query like this:
"SELECT DISTINCT id,message FROM your_table LIMIT 0,5"

MySQL Method:
Reference this article # w3schools: http://www.w3schools.com/sql/sql_distinct.asp
SELECT
DISTINCT(table.id),
table.message
FROM
db.messages
If you are adamant on doing this outside of the prefferred method of using MySQL you can use PHPS array_unique() function..
http://php.net/manual/en/function.array-unique.php
<?php
$result = array_unique($array);
print_r($result);

Related

Trying to merge two results of SQL queries - ToDoList App

I am trying to merge two results of two queries in MYSQL using PHP, but I am puzzled how to do it! I am using PDO. I am programming for a hobby and am trying to make a to do list app just like a Trello board. However, I just can't figure out how to merge two results from different tables in a database.
The idea is as follows:
I have a table called 'task_lists' with the content:
'list_id => 1, list_name = 'listOne'
'list_id => 2, list_name = 'listTwo'
And a table called 'tasks':
task_id => 1, list_id => 1, task_name => 'taskOfListOne', duration => 5, is_done => 1
task_id => 2, list_id => 1, task_name => 'anotherTaskOfListOne', duration => 5, is_done => 1
task_id => 3, list_id => 2, task_name => 'taskOfListTwo', duration => 10, is_done => 0
And I am trying to create an array that is merged between the two results as something like:
(I know this is a rough picture of how the array is supposed to look like)
$result = [array]
[list_id] = 1, [list_name] = 'listOne' =>
[array][list_id] = 1, ['task_name] = taskOfListOne,[duration] = 5, ['is_done'] => 1
[array][list_id] = 1, ['task_name] = anotherTaskOfListOne,[duration] = 5, ['is_done'] => 1
[list_id] = 2, [list_name] = 'listTwo' =>
[array][list_id] = 2, ['task_name] = taskOfListTwo,[duration] = 5, ['is_done'] => 1
Is this even possible? I have tried a Union sql query and methods like nested foreach statements, but none of them worked for me. Am I missing something here?
PS: Sorry for my bad english.
Have you tried a left join?
SELECT TL.`list_id`, TL.`list_name`, T.`task_name`, T.`duration`
FROM task_lists AS TL
LEFT JOIN tasks as T ON TL.`list_id` = T.`list_id`
And then in PHP you build the array in the format you want.
Later edit:
Simple PHP example to parse SQL data as you asked (to remove duplicated info):
<?php
// $mysql_rows -> here is your query result, fetched as associative array
$filtered_array = array();
foreach ($mysql_rows as $row){
// Initiate record if is not already initiated
if (!isset($filtered_array[ $row['list_id'] ])){
$filtered_array[ $row['list_id'] ] = array(
'list_id' => $row['list_id'],
'list_name' => $row['list_name'],
'tasks' => array()
);
}
// Add tasks
$filtered_array[ $row['list_id'] ]['tasks'][] = array(
'task_name' => $row['task_name'],
'duration' => $row['duration'],
'is_done ' => $row['is_done ']
);
}
// Optional: if you want to remove list_id from $filtered_array key names, uncomment the next line
// $filtered_array = array_values($filtered_array);
?>

Laravel - Access a value from DB::table()->insert

I'm building an Insert query using Faker and I wonder whether it is possible to use a value to-be-inserted in another value.
Here is an example, not accurate for my situation but explains well:
DB::table('debts')->insert([
'name' => $faker->company,
'debt' => $faker->randomFloat($nbMaxDecimals = 2, $min = 20000, $max = 10000000),
'debt_paid' => 'debt' / rand ( 2 , 8 ),
'notes' => $faker->paragraph($nbSentences = 3, $variableNbSentences = true),
]);
As you can see, in the row of debt_paid I want to access the value of 'debt' that was randomly defined a row above. This is because debt_paid needs to be logical and without the value of debt it might be non-sense.
I know that defining 'debt' as a variable before the insert would solve it, but I wonder whether there's a more elegant solution.
So do that outside the insert
$dbt = $faker->randomFloat($nbMaxDecimals = 2, $min = 20000, $max = 10000000);
DB::table('debts')->insert([
'name' => $faker->company,
'debt' => $dbt,
'debt_paid' => $dbt / rand ( 2 , 8 ),
'notes' => $faker->paragraph($nbSentences = 3, $variableNbSentences = true),
]);

How to get multiple auto incremented id in laravel database [duplicate]

I am inserting multiple rows at the same time, say 2 rows
$multiple_rows = [
['email' => 'taylor#example.com', 'votes' => 0],
['email' => 'dayle#example.com', 'votes' => 0]
];
DB::table('users')->insert($multiple_rows);
How can I get those inserted ids.
I am doing it, this way for now.
foreach($multiple_rows as $row){
DB::table('users')->insert($row);
$record_ids[] = DB::getPdo()->lastInsertId();
}
Any other good way to do it, without inserting single row each time.
You could do something like the following:
$latestUser = DB::table('users')->select('id')->orderBy('id', 'DESC')->first();
$multiple_rows = [
['email' => 'taylor#example.com', 'votes' => 0],
['email' => 'dayle#example.com', 'votes' => 0]
];
DB::table('users')->insert($multiple_rows);
$users = DB::table('users')->select('id')->where('id', '>', $latestUser->id)->get();
If you really need all the inserted ID's
$dataArray = [
['name' => 'ABC'],
['name' => 'DEF']
];
$ids = [];
foreach($dataArray as $data)
{
$ids[] = DB::table('posts')->insertGetId($data);
}
To get all id with a massive insertion I think the good way is to first get the last id in the table, make the massive insertion and get the last id. In theory they must follow, unless there has been an insertion from another connection. To avoid that the solution is a transaction.
Update
Also read the documentation

How to get last inserted ids in laravel

I am inserting multiple rows at the same time, say 2 rows
$multiple_rows = [
['email' => 'taylor#example.com', 'votes' => 0],
['email' => 'dayle#example.com', 'votes' => 0]
];
DB::table('users')->insert($multiple_rows);
How can I get those inserted ids.
I am doing it, this way for now.
foreach($multiple_rows as $row){
DB::table('users')->insert($row);
$record_ids[] = DB::getPdo()->lastInsertId();
}
Any other good way to do it, without inserting single row each time.
You could do something like the following:
$latestUser = DB::table('users')->select('id')->orderBy('id', 'DESC')->first();
$multiple_rows = [
['email' => 'taylor#example.com', 'votes' => 0],
['email' => 'dayle#example.com', 'votes' => 0]
];
DB::table('users')->insert($multiple_rows);
$users = DB::table('users')->select('id')->where('id', '>', $latestUser->id)->get();
If you really need all the inserted ID's
$dataArray = [
['name' => 'ABC'],
['name' => 'DEF']
];
$ids = [];
foreach($dataArray as $data)
{
$ids[] = DB::table('posts')->insertGetId($data);
}
To get all id with a massive insertion I think the good way is to first get the last id in the table, make the massive insertion and get the last id. In theory they must follow, unless there has been an insertion from another connection. To avoid that the solution is a transaction.
Update
Also read the documentation

SQL Results as PHP Array

I am trying to solve this. Maybe this is absolutly incorrect, I need some help.
I have a table like this:
INSERT INTO `municipios` (`id`, `provincia`, `municipio`) VALUES (1, 1, 'Alegría-Dulantzi'), (2, 1, 'Amurrio'), (3, 1, 'Añana'), (4, 1, 'Aramaio'), (5, 1, 'Armiñón'),
And this is my handler:
$query = "SELECT * FROM municipios WHERE provincia='1'";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$groups = array(
$row{'id'} => array(
'name' => $row{'municipio'},
'description' => 'Agrupación electoral de ' . $row{'municipio'},
'status' => 'public',
'enable_forum' => 1,
),
);
}
With this I got just the last result. I have tried another options, but doesn´t work.
Something like this should solve your issue:
$groups[] = array(
$row['id'] => array(
'name' => $row['municipio'],
'description' => 'Agrupación electoral de ' . $row['municipio'],
'status' => 'public',
'enable_forum' => 1,
),
);
However, may i suggest your use PDO. There is a pretty good article http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/ that should get you going in the right direction.
Is this an issue with the way you're appending the groups array? I think your overwriting the array every time u set a value. Try using array_push() to append to groups.
Let us know of that helps!
array_push()
http://php.net/manual/en/function.array-push.php

Categories