select rows with the same value using Codeingiter - php

How to select all with the same value using codeigniter.
+-------+-------------+------------+
| id | coupon_code | Barcode |
+-------+-------------+------------+
| 1 | COUPON02 | 12542 |
| 2 | COUPON02 | 11229 |
| 3 | COUPON03 | 11823 |
| 4 | COUPON03 | 47875 |
+-------+-----------+--------------+
public function fetch_available_coupon(){
$coupon_code = $this->uri->segment(3);
$this->db->select('*');
$this->db->from('barcode');
$this->db->where('coupon_code', $coupon_code);
$query = $this->db->get();
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}else{
return false;
}
}
in my result it only show 1 row not the not all the same Coupon_Code
Im using codeigniter as my active record. Please Help thank you

use where condition instead of group by
$this->db->where('coupon_code', $coupon_code);
You can use GROUP BY to group values from a column, and, if you wish, perform calculations on that column. You can use COUNT, SUM, AVG, etc., functions on the grouped column.

Related

Join tables horizontally and dynamically

I need some help from joining tables horizontally my tables are
+---------+---------+
| Candidates Table |
+---------+---------+
| can_id | Name |
+---------+---------+
| 1 | Liza |
| 2 | Sarah |
| 3 | Jane |
| | |
+---------+---------+
+---------+---------+
| Judges Table |
+---------+---------+
| id | Name |
+---------+---------+
| 1 | judge1 |
| 2 | judge2 |
| 3 | judge3 |
+-------------------+
+---------+---------------+--------+-------+
| Score Table |
+---------+-------+------------------------|
| sco_id | can_id| jud_id |crit_id |score|
+---------+--------+-----------------------+
| 1 | 1 | 2 | 1 | 87 |
| 2 | 1 | 3 | 1 | 89 |
| 3 | 1 | 1 | 1 | 80 |
+------------------------------------------+
I need an output of something like this one..
+---------+---------------+-------------+
| Score board |
+---------+---------+-------------------|
| Name | judge1 | judge2 | judge3 |
+---------+---------+-------------------|
| Liza | 80 | 87 | 89 |
|some data|some data|some data|some data|
|some data|some data|some data|some data|
+---------------------------------------+
notes: crit_id is criteria id from criteria table.
Normally I would use some joins and subqueries but my problems is I need the output dynamically where in if I add a new judges it will automatically generate a new column. I need at least 1 candidate data with all of the judges scores then just loop it with parameters on php to get the other candidates data something like
php loop start
<td>name</td>
<td>judge1 score</td>
<td>judge2 score</td>
php end loop
or if i could get the whole candidates table with judges score much better for me not to loop them per candidate
I've tried to research similar questions like
Concatenate more than two tables horizontally in SQL Server
I've tried to code myself but I got stuck with joining the judges..
SELECT s.sco_id,c.Name,c.Municipalities
FROM `tbl_scoring` s
LEFT JOIN tbl_candidates c ON c.`can_id` = s.`can_id`
WHERE s.can_id = 11
AND crit_id = 1
ORDER BY s.jud_id asc
I need a query that would generate dynamically depending on the number of judges either get candidate data with scores of judge then loop it on php or much way better if i get all the data without looping
Initialize the following arrays:
$judges = [];
$scores = [];
$candidates = [];
Then execute your query, and loop the results. Set those values for each iteration:
$judges[$row['jud_id']] = 1;
$candidates[$row['can_id']] = $row['Name'];
$scores[$row['can_id']][$row['jud_id']] = $row['score'];
Now you want to get the participant judges names, so let's run a SQL query:
$sql = 'SELECT Name FROM judges WHERE id IN (' . implode(',', array_keys($judges)) . ')';
And on every iteration set the judge's name in the $judges array:
$judges[$row['id']] = $row['Name'];
Then for the output:
echo '<tr>';
echo '<td>Name</td>';
ksort($judges);
foreach ($judges as $name) {
echo '<td>Judge: ' . $name . '</td>';
}
echo '</tr>';
foreach ($scores as $candidateId => $data) {
echo '<tr>';
echo "<td>$candidates[$candidateId]</td>";
ksort($data);
foreach ($data as $score) {
echo "<td>$score</td>";
}
echo '</tr>';
}
I used ksort on $judges and $data so the score will fit each judge.
first, we retrieve the judges' ids and name that exist on the score table.
$judges = [];
$query = "SELECT id, name FROM Judges WHERE id IN ( SELECT DISTINCT jud_id FROM Score )";
// execute the query and store the results in the $judges array.
we retrieve the candidates' ids and name that exist on the score table.
$candidates = [];
$query = "SELECT id FROM Candidate WHERE id IN ( SELECT DISTINCT can_id FROM Score )";
// execute the query and store the results in the $candidates array.
then, we join the candidate and score table.
$candidate_score = [];
$query = "SELECT Candidate.name, Candidate.id as candidate_id , Score.jud_id, Score.score FROM Candidate JOIN Score ON Score.can_id = Candidate.id";
// execute the query and store it in the $candidate_score array.
now, for each candidate, we fill its score on the $score_board array.
$score_board = [];
foreach ( $candidates as $candidat )
{
$score_board[$candidat] = [];
foreach ( $judges as $judge )
{
$judge_name = $judge['name'];
$judge_id = $judge['id'];
$score_board[$candidat][$judge_name] = get_judge_score($candidate_score,$candidat,$judge_id);
}
}
this is how the get_judge_score will work:
function get_judge_score ( $scores , $candidate , $judge )
{
$score_filtred = array_filter($scores, function ($score) use ($candidate,$judge) {
return $score['jud_id'] == $judge && $score['candidate_id'] = $candidate;
});
return count($score_filtred) > 0 ? $score_filtred[0]['score'] : 0;
}

Fetching data from a table and storing in variables

I have website settings stored in a table like this:
+---------+-------------+
| id | value |
+---------+-------------+
| 1 | title |
| 2 | description |
| 3 | email |
| 4 | keywords |
+---------+-------------+
How can I select them and assign them to variables ($title, $desc, $email, $key)
// Get Website Infos
$result=$db->query("SELECT `value` FROM `settings`");
if($result->num_rows >= 1){
$row=$result->fetch_assoc();
$otitle=$row['value'];
$odescription=$row['value'];
$oemail=$row['value'];
$okeywords=$row['value'];
}
but it only get the first row 'title',any idea how to do it or better way to save settings.
UPDATE:
If you are reading this question now, don't use this structure to store your settings, use the one suggested by Yellow Bird in the answers.
You have to loop with your fetch_assoc() method :
$result = $db->query("SELECT `value` FROM `settings`");
if ($result->num_rows >= 1){
$data = array();
while ($row = $result->fetch_assoc()) {
$data[] = $row['value'];
}
}
var_dump($data);
As DanFromGermany noticed in comments, your db structure is probably not done the right way. You should have a design like this :
+---------+-------------+--------------+
| id | key | value |
+---------+-------------+--------------+
| 1 | title | title value |
| 2 | description | desc value |
| 3 | email | email value |
| 4 | keywords | keyw value |
+---------+-------------+--------------|
And then, your code would look like this :
$result = $db->query("SELECT key, value FROM `settings`");
if ($result->num_rows >= 1) {
$data = array();
while ($row = $result->fetch_assoc()) {
$data[$row['key']] = $row['value'];
}
}

Count same values in different column mysql

I need to count how many times in ripeted the same values in different columns for the same id..
I'll try to clarify with an example:
TABLE:
+-----+-----+-----+-----+-----+
| id | d01 | d02 | d03 | d04 |
+=====+=====+=====+=====+=====+
| 1 | A | A | B | B |
+-----+-----+-----+-----+-----+
| 2 | A | A | A | A |
+-----+-----+-----+-----+-----+
| 3 | B | B | A | A |
+-----+-----+-----+-----+-----+
| 4 | A | A | A | A |
+-----+-----+-----+-----+-----+
| 5 | A | A | A | A |
+-----+-----+-----+-----+-----+
| 6 | B | A | A | A |
+-----+-----+-----+-----+-----+
I need to know how many times the value "B" is repeating for any person (ID)..
Is that possible to do that? RESULTS
+-----+-----+-----+
| id | count B |
+=====+=====+=====+
| 1 | 2 |
+-----+-----+-----+
| 2 | 0 |
+-----+-----+-----+
| 3 | 2 |
+-----+-----+-----+
I was thinking to use the function "SUM" but I have no idea how to display just the single ID.
Thanks in advance, hope the question is clear enough!
If there are only four columns:
SELECT id, (d01 = 'B') + (d02 = 'B') + (d03 = 'B') + (d04 = 'B')
FROM tablename
No there are 31 columns
That's a problem which you can solve in two ways:
Repeat the condition for the other 27 columns :)
Normalize your structure so that each value is dependent on both the id and a numeric value that represents a calendar.
The PHP way
You can also fetch all columns and let PHP solve this for you:
$res = $db->query('SELECT * FROM tablename');
foreach ($res->fetchAll(PDO::FETCH_ASSOC) as $row) {
$id = $row['id'];
unset($row['id']); // don't count the id column
$count = count(array_keys($row, 'B', true));
printf("ID %d: %d\n", $id, $count);
}
Since you seem to be using mysql_*:
// SHOW COLUMNS returns all the columns and constrains of the defined table
// We only need the column names so we will be later calling it by 'Field'
$sql = mysql_query("SHOW COLUMNS FROM table"); //your table name here
$val_to_count = 'B'; //value to count here
$id = 1; //id to search for
$new_sql = 'SELECT id, ';
// In this loop we will construct our SELECT query using the columns returned
// from the above query
while($row=mysql_fetch_array($sql)){
if($row['Field']!='id'){
$new_sql .= ' ('.$row['Field'].' = "'.$val_to_count.'") + ';
}
}
//Removing the last "+ " produced in the select query
$new_sql = rtrim($new_sql,"+ ");
$new_sql .= ' as count FROM table WHERE id = '.$id; //table name here again
// so $new_sql now has an output like:
// SELECT ID, (d01 = 'B') + (d02 = 'B') ... WHERE id = 1
$sql2 = mysql_query($new_sql);
//executing the constructed query with the output below
while($row2=mysql_fetch_array($sql2)){
echo 'ID - '.$row2['id']."<br>";
echo 'Count - '.$row2['count']."<br>";
}
Note:
mysql_* is deprecated, please consider to migrate to mysqli_*

How to get in array data from table?

I have a tags_ids array 1,3,2 and
data in my table:
+---------+----------+
| user_id | tag_id |
+---------+----------+
| 1 | 1 |
| 1 | 2 |
| 2 | 1 |
| 2 | 2 |
+---------+----------+
I want to get the users ids into array, but not working:
foreach ($tags_ids as $i)
{
if ($result = $mysqli->prepare("SELECT `user_id` FROM `mytable` WHERE `tag_id`=?"))
{
$result->bind_param("i",$i);
$result->execute();
$result->bind_result($d);
$result->fetch();
$result->close();
}
if (!in_array($d,$users_ids)) $users_ids[] = $d;
}
My result is always 1. Whats I'm doing wrong, and can I do it in a more simple way?
you need a while loop, you can find it here for full assist:http://www.youtube.com/watch?v=hO0YOOeJrOE
be sure to watch the other video's too, very helpfull.
goodluck,
PHPNoob

codeigniter , mysql

I'm new to CI and I'm having a problem with MySQL
Table1
id | house_id |
1 | 1 |
2 | 4 |
3 | 3 |
Table2
house_id | image_name |
4 | a.jpg |
4 | b.jpg |
3 | c.jpg |
How I can select (distinctively) image_name for each house_id by using CodeIgniter Active Record class?
http://codeigniter.com/user_guide/database/active_record.html
this is the API you are looking for $this->db->distinct();
Just use a simple method group_by in codeigniter model
function get_house_image(){
$items = $this->db->select('house_id', 'image_name')
->from("table1")
->join("table2", "table1.house_id = table2.house_id")
->group_by("table1.house_id")
->get();
return $items->result_array();
}
In your Model
function get_house_image($id){
$this->db->where('house_id',$id);
$query = $this->db->get('table2');
return $query->result();
}
In your cotroller
function house($id){
$data['house'] = $this->your_model->get_house_image($id);
$this->load->view('your_view',$data);
In your view foreach the result and use it. This gets the house's picture which id you pass in url.
You can use left join of tables to get records as follow:
$this->read->select('t1.house_id,t2.image_name');
$this->read->join('table2 as t2','t1.house_id = t2.house_id','left');
$result = $this->read->get('table1 as t1');
if($result){
$data = $result->result_array();
print_r($data);
}

Categories