Query with multiple WHERE and CASE PHP(CodeIgniter) MySQL - php

I'd like to select all period of current term (as now FY80) + 3 period only of last term (FY79) from m_period table
Here's the table m_period looks :
+----+------+-------------+--------+
| id | term | period | status |
+----+------+-------------+--------+
| 1 | FY79 | 79::2020/01 | close |
| 2 | FY79 | 79::2020/02 | close |
| 3 | FY79 | 79::2020/03 | close |
| 4 | FY79 | 79::2020/04 | close |
| 5 | FY79 | 79::2020/05 | close |
| 6 | FY79 | 79::2020/06 | close |
| 7 | FY80 | 80::2020/07 | open |
| 8 | FY80 | 80::2020/08 | open |
| 9 | FY80 | 80::2020/09 | open |
| 10 | FY80 | 80::2020/10 | open |
| 11 | FY80 | 80::2020/11 | open |
| 12 | FY80 | 80::2020/12 | open |
| 13 | FY80 | 80::2021/01 | open |
| 14 | FY80 | 80::2021/02 | open |
| 15 | FY80 | 80::2021/03 | open |
| 16 | FY80 | 80::2021/04 | open |
| 17 | FY80 | 80::2021/05 | open |
| 18 | FY80 | 80::2021/06 | open |
+----+------+-------------+--------+
my php script stuck from here :
<?php
function getPeriod()
{
$prev_term = (int)substr($this->session->userdata('term'),2,2) - 1;
$this->db->select('period');
$this->db->where('term', $this->session->userdata('term'));
$this->db->where('term', $prev_term);
$this->db->order_by('period', 'ASC');
return $this->db->get('m_period')->result_array();
}
I've read CI documentation and couldn't find how to use CASE in codeigniter, or there is another way instead of using CASE ?
can someone help me , how to do this ?
Note : I store current term on session

You can use limit() method.
Then, You have to have two separate functions.
function getPrevPeriod()
{
$prev_term = (int)substr($this->session->userdata('term'),2,2) - 1;
$this->db->select('period');
$this->db->where('term', $prev_term);
$this->db->order_by('period', 'ASC');
$this->db->limit(3);
return $this->db->get('m_period')->result_array();
}
function getCurrentPeriod()
{
$this->db->select('period');
$this->db->where('term', $this->session->userdata('term'));
$this->db->order_by('period', 'ASC');
return $this->db->get('m_period')->result_array();
}
Then you can use array_merge() to combine arrays.
$periods = array_merge($prev, $current);
Edit: With one query
function getPeriod()
{
$prev_term = (int)substr($this->session->userdata('term'),2,2) - 1;
$this->db->select('term','period');
$this->db->or_where_in('term',[$this->session->userdata('term'),$prev_term])
$this->db->order_by('period', 'ASC');
$result = $this->db->get('m_period')->result_array();
$output = [];
$n = 0;
foreach($result as $row){
if($row["term"] == $prev_term){
if($n <= 3){
$output[] = $row;
$n++;
}
}else{
$output[] = $row;
}
}
return $output;
}

Related

create a sequence for rows with similar ids using php

i have a datastructure similar to this
+---------+---------+
| id | value |
+---------+---------+
| 1 | value |
1 | value |
| 1 | value |
| 1 | value |
| 1 | value |
| 2 | value |
| 2 | value |
| 2 | value |
| 3 | value |
| 3 | value |
| 3 | value |
| | |
+---------+---------+
I am trying to update this table to look something like this
+---------+---------+
| id | value |
+---------+---------+
| 1 | value 0 |
1 | value 1 |
| 1 | value 2 |
| 1 | value 3 |
| 1 | value 4 |
| 2 | value 0 |
| 2 | value 1 |
| 2 | value 2 |
| 3 | value 0 |
| 3 | value 1 |
| 3 | value 2 |
| | |
+---------+---------+
To achieve this, i have written php script that looks like this
$query = "select count(*) as count,id, value from foo group by id";
$sql=$con->prepare($query);
$sql->execute();
$sql->setFetchMode(PDO::FETCH_ASSOC);
while($row=$sql->fetch()){
$id[] = $row['id'];
$count[] = $row['count'];
$value[] = $row['value'];
echo "<pre>";
}
$c=array_combine($id, $count);
foreach ($c as $key=>$value){
for($i=0;$i<=$value;$i++){
$postid = $key;
if($i==0){
$multiple = "multiple";
$newvalue= $value;
}
else{
$x=$i-1;
$multiple = "multiple_".$x;
echo $multiple . "<br>";
$query2 = "update foo set value = :multiple";
$sql2=$con->prepare($query2);
$sql2->bindValue(':multiple', $multiple);
$sql2->execute();
}
}
}
The problem is that the code returns the following results
+---------+---------+
| id | value |
+---------+---------+
| 1 | value_1 |
1 | value_1 |
| 1 | value_1 |
| 1 | value_1 |
| 1 | value_1 |
| 2 | value_1 |
| 2 | value_1 |
| 2 | value_1 |
| 3 | value_1 |
| 3 | value_1 |
| 3 | value_1 |
| | |
+---------+---------+
What can i be possibly be doing wrong?
Thanks #Shadow
Your query runs fine but returns the following results
+------+-----------------------------------------------+
| id | value |
+------+-----------------------------------------------+
| 1 | multiple_1_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0 |
| 1 | multiple_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1 |
| 1 | multiple_1_2_2_2_2_2_2_2_2_2_2_2_2_2_2_2_2 |
| 1 | multiple_1_3_3_3_3_3_3_3_3_3_3_3_3_3_3_3_3 |
| 2 | multiple_1_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0 |
| 2 | multiple_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1 |
| 2 | multiple_1_2_2_2_2_2_2_2_2_2_2_2_2_2_2_2_2 |
| 2 | multiple_1_3_3_3_3_3_3_3_3_3_3_3_3_3_3_3_3 |
| 3 | multiple_1_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0 |
| 3 | multiple_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1 |
| 3 | multiple_1_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0 |
+------+-----------------------------------------------+
You can do the update iterating and creating data in such a way:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $pdo->prepare("SELECT * FROM foo");
$sth->execute();
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
$response = array();
foreach ($data as $dataIndex => $dataValue) {
if (!isset($response[$dataValue["id"]]["count"])) {
$response[$dataValue["id"]]["count"] = 0;
} else {
$response[$dataValue["id"]]["count"] ++;
}
$response[$dataValue["id"]]["values"][$dataValue["pid"]] = "value_" . $response[$dataValue["id"]]["count"];
$sth = $pdo->prepare("UPDATE foo SET value = '{$response[$dataValue["id"]]["values"][$dataValue["pid"]]}' WHERE pid = {$dataValue["pid"]}");
$sth->execute();
}
?>
But try to do an update using the least iteration not to create as many database queries , example:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $pdo->prepare("SELECT * FROM foo");
$sth->execute();
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
$response = array();
$update = array();
foreach ($data as $dataIndex => $dataValue) {
$response[$dataValue["id"]]["id"] = $dataValue["id"];
if (!isset($response[$dataValue["id"]]["count"])) {
$response[$dataValue["id"]]["count"] = 0;
} else {
$response[$dataValue["id"]]["count"] ++;
}
$response[$dataValue["id"]]["values"][$dataValue["pid"]] = "value_" . $response[$dataValue["id"]]["count"];
$update[] = "UPDATE foo SET value = '{$response[$dataValue["id"]]["values"][$dataValue["pid"]]}' WHERE pid = {$dataValue["pid"]};";
}
$update = implode("",$update);
$sth = $pdo->prepare($update);
$sth->execute();
?>
Your update query
$query2 = "update foo set value = :multiple";
does not contain any where criteria, each time you call this query it updates the value field's value in all records.
Honestly, I would not really involve php in this update, would do it purely in sql using user defined variables and multi-table join syntax in the update:
update foo inner join (select #i:=0, #previd:=-1) as a
set foo.value=concat(foo.value,'_',#i:=if(id=#previd,#i+1,0),if(#previd:=id,'',''))
The subquery in the inner join initialises #i and #previd user defined variables. The 3rd parameter of the concat function determines the value #i to be concatenated to the value field. The 4th parameter of concat sets the #previd variable and returns an empty string not to affect the overall concatenation. Unfortunately, I do not have access to MySQL to test the query, but it should be a good starting point anyway.
UPDATE
The OP claims in the updated question that the query I provided creates the below resultset:
+------+-----------------------------------------------+
| id | value |
+------+-----------------------------------------------+
| 1 | multiple_1_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0 |
| 1 | multiple_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1 |
| 1 | multiple_1_2_2_2_2_2_2_2_2_2_2_2_2_2_2_2_2 |
| 1 | multiple_1_3_3_3_3_3_3_3_3_3_3_3_3_3_3_3_3 |
| 2 | multiple_1_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0 |
| 2 | multiple_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1 |
| 2 | multiple_1_2_2_2_2_2_2_2_2_2_2_2_2_2_2_2_2 |
| 2 | multiple_1_3_3_3_3_3_3_3_3_3_3_3_3_3_3_3_3 |
| 3 | multiple_1_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0 |
| 3 | multiple_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1 |
| 3 | multiple_1_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0 |
+------+-----------------------------------------------+
Tested my solution in sqlfiddle. I had to remove the order by clause, otherwise the query produced the results in line with the requirements stated in the question. See sqlfiddle for details.
The results in the updated question are likely the result of running the query in a loop multiple times. In simple words: you just copy pasted the query into your code and did not remove the loop, even when I pointed out, that this may be the reason of the results you received.

Number auto increase with other while function (PHP)

I want the queqe id auto increase start from 1
I have an mysql table call t1
mysql table t1 Data as below:
+----------+------------------+-------------+
| ID | Name | Status |
+----------+------------------+-------------+
| 1 | ABBCCC | 1 |
| 2 | BASDASD | 1 |
| 3 | ABBCCC | 1 |
| 4 | ABBCCC | 2 |
+-------------------------------------------+
I loop data in php like this:
$quserCA = DB::query("SELECT * FROM ".DB::table('jnbook_book')." WHERE Name = 'ABBCCC' ORDER BY id DESC LIMIT 20");
$nqCA = mysql_num_rows($quserCA);
while($ruserCA = DB::fetch($quserCA)){
$CAlist[] = $ruserCA;
}
$x = 1;
while($x <= $nqCA) {
//echo "The number is: $x <br>";
$x++;
}
I loop this in my htm like this:
<table>
<tr>
<td>Queqe ID</td><td>ID</td><td>Status</td>
</tr>
<!--{loop $CAlist $value}-->
<tr>
<td>{$x}</td><td>{$value[id]}</td><td>{$value[status]}</td>
</tr>
<!--{/loop}-->
</table>
But after that my table output as below show
+---------------+-------------------+----------------+
| Queqe ID | ID | Status |
+---------------+-------------------+----------------+
| 1 | 1 | 1 |
| 1 | 3 | 1 |
| 1 | 4 | 2 |
+----------------------------------------------------+
Actually what I want the table output as below
(I want the queqe id auto increase start from 1):
+----------+-----------------+-----------------+
| Queqe ID | ID | Status |
+----------+-----------------+-----------------+
| 1 | 1 | 1 |
| 2 | 3 | 1 |
| 3 | 4 | 2 |
+----------------------------------------------+
Thank you.
This should be done something like:
$x = 1;
while($ruserCA = DB::fetch($quserCA)){
// add a field, say `x` with number of a record:
$ruserCA['x'] = $x++;
$CAlist[] = $ruserCA;
}
In a template:
<td>{$value[x]}</td><td>{$value[id]}</td><td>{$value[status]}</td>

Codeigniter join multiple tables with where clauses

I have four tables that I need to join together, with one of those tables having two different records I need to grab. The guild and party tables I'm getting the name of those so that I can display the name instead of ID to the user, and the charlog table has the char_id's creation date and last login date that I want to show as well. Here are the tables:
char table:
----------------------------------------------------
| char_id | name | guild_id | party_id |
|---------------------------------------------------
| 150000 | char1 | 3 | 3 |
| 150001 | char2 | 2 | (NULL) |
| 150002 | char3 | (NULL) | 1 |
| 150003 | char4 | 1 | 2 |
----------------------------------------------------
guild table:
-------------------------
| guild_id | name |
-------------------------
| 1 | guild_1 |
| 2 | guild_2 |
| 3 | guild_3 |
-------------------------
party table:
-------------------------
| party_id | name |
-------------------------
| 1 | party_1 |
| 2 | party_2 |
| 3 | party_3 |
-------------------------
charlog table:
----------------------------------------------------
| time | char_id | char_msg |
----------------------------------------------------
| 2015-02-14 06:45:32 | 150000 | make new char |
| 2015-02-14 06:45:58 | 150000 | char select |
| 2015-02-15 12:32:19 | 150001 | make new char |
| 2015-02-15 16:54:01 | 150000 | char select |
| 2015-02-15 19:23:54 | 150001 | char select |
| 2015-02-16 01:32:13 | 150002 | make new char |
| 2015-02-16 01:33:01 | 150003 | make new char |
| 2015-02-16 04:45:43 | 150000 | char select |
| 2015-02-16 07:43:22 | 150003 | char select |
----------------------------------------------------
As mentioned, I need to get the make new char entry from the charlog table to display when the character was created and as well the LAST (by date) char select entry to display when the character was played, all of this with one single char_id.
All in all, I'd be looking for a table that looks like this:
---------------------------------------------------------------------------------------------------------------------
| char_id | name | guild_id | guild_name | party_id | party_name | create_time | lastlogin_time |
---------------------------------------------------------------------------------------------------------------------
| 150000 | char1 | 3 | guild_3 | 3 | party_3 | 2015-02-14 06:45:32 | 2015-02-16 04:45:43 |
I'm using the following active record lines in Codeigniter to attempt to get the data I need. It returns the create_date correctly but the lastlogin_time is not returned (it's blank):
function get_char_info($cid) {
$this->db->select('char.*,guild.guild_id,guild.name AS guild_name,party.party_id,party.name AS party_name,charlog1.time AS create_time,charlog2.time AS lastlogin_time');
$this->db->from('char');
$this->db->where('char.char_id', $cid);
$this->db->join('guild', 'char.guild_id = guild.guild_id', 'left');
$this->db->join('party', 'char.party_id = party.party_id', 'left');
$this->db->join('charlog AS charlog1', 'char.char_id = charlog1.char_id AND charlog1.char_msg = "make new char"', 'left');
$this->db->join('charlog AS charlog2', 'char.char_id = charlog2.char_id AND charlog2.char_msg = (SELECT max(charlog.time) FROM charlog WHERE char_msg = "char select")', 'left');
$query = $this->db->get();
return $query->row();
}
As mentioned, the guild_name, party_name and create_time come through correctly, but the lastlogin_time is blank, no error.
I've tried jumbling some things around in the active record clauses but can't get the lastlogin_time to show. Any help would be appreciated.
The join on your subquery is not correct :
It should be charlog2.time = (SELECT....) not charlog2.char_msg = (SELECT....)

Get all dbpprops from a certain box in wikipedia

Let me use these 2 links as my examples:
http://en.wikipedia.org/wiki/Maarten_Stekelenburg
http://dbpedia.org/page/Maarten_Stekelenburg
What I want to do is get all the dbpprops which are in the top right infobox (the one with the picture).
Here I encounter 2 problems:
How do I get all the properties without knowing them (We are putting together a football player database, and the prop names are all different for every player)
How do I make sure those are the properties that are inside the box, because there are many other dbpprops on that page and it doesn't look like dbpedia differentiates between those.
After that I want to add all those properties to an array(if that is possible).
If it's possible, I would like it to look something like this:
PREFIX dbp: <http://dbpedia.org/resource/>
PREFIX dbp2: <http://dbpedia.org/ontology/>
PREFIX dbp3: <http://dbpedia.org/property/>
SELECT *
WHERE {
dbp:".$term." dbp2:abstract ?abstract .
dbp:".$term." dbp2:thumbnail ?img .
dbp:".$term." dbp3:* ?properties . //This would then be replaced by the necessary line
FILTER langMatches(lang(?abstract), 'en')
}
EDIT: I am working with PHP
I can't guarantee that the set of properties from the infobox will be exactly the properties that are dbpprop properties (as opposed to dbpedia-owl properties), but it looks like there's a fairly good correspondence. In this case, you could use a query like the following which asks for properties and values of the person you mentioned, but only thoe properties that are in the dbpprop namespace.
prefix dbpedia: <http://dbpedia.org/resource/>
prefix dbpprop: <http://dbpedia.org/property/>
select ?property ?value where {
dbpedia:Maarten_Stekelenburg ?property ?value
filter( strstarts(str(?property),str(dbpprop:)) )
}
SPARQL results
----------------------------------------------------------------------------------------------------------------------
| property | value |
======================================================================================================================
| dbpprop:bg | "gold"#en |
| dbpprop:bg | "#F1771D"#en |
| dbpprop:birthDate | "1982-09-21+02:00"^^<http://www.w3.org/2001/XMLSchema#date> |
| dbpprop:birthPlace | "Haarlem, Netherlands"#en |
| dbpprop:caps | 44 |
| dbpprop:caps | 191 |
| dbpprop:clubnumber | 24 |
| dbpprop:clubs | dbpedia:A.S._Roma |
| dbpprop:clubs | dbpedia:AFC_Ajax |
| dbpprop:currentclub | dbpedia:A.S._Roma |
| dbpprop:dateOfBirth | 22 |
| dbpprop:fg | "navy"#en |
| dbpprop:fg | "white"#en |
| dbpprop:fullname | "Maarten Stekelenburg"#en |
| dbpprop:goals | 0 |
| dbpprop:name | "Maarten Stekelenburg"#en |
| dbpprop:name | "Stekelenburg, Maarten"#en |
| dbpprop:nationalcaps | 4 |
| dbpprop:nationalcaps | 54 |
| dbpprop:nationalgoals | 0 |
| dbpprop:nationalteam | dbpedia:Netherlands_national_football_team |
| dbpprop:nationalteam | dbpedia:Netherlands_national_under-21_football_team |
| dbpprop:nationalyears | 2002 |
| dbpprop:nationalyears | 2004 |
| dbpprop:ntupdate | 18 |
| dbpprop:pcupdate | 21 |
| dbpprop:placeOfBirth | "Haarlem, Netherlands"#en |
| dbpprop:position | <http://dbpedia.org/resource/Goalkeeper_(association_football)> |
| dbpprop:shortDescription | "Dutch footballer"#en |
| dbpprop:title | "Awards"#en |
| dbpprop:title | "Netherlands squads"#en |
| dbpprop:years | 2002 |
| dbpprop:years | 2011 |
| dbpprop:youthclubs | dbpedia:AFC_Ajax |
| dbpprop:youthclubs | "Schoten"#en |
| dbpprop:youthclubs | "Zandvoort '75"#en |
| dbpprop:youthyears | 1997 |
| dbpprop:wordnet_type | <http://www.w3.org/2006/03/wn/wn20/instances/synset-soccer_player-noun-1> |
| dbpprop:hasPhotoCollection | <http://wifo5-03.informatik.uni-mannheim.de/flickrwrappr/photos/Maarten_Stekelenburg> |
----------------------------------------------------------------------------------------------------------------------
You mentioned storing results in an array, but I don't really understand the example that you've provided. It looks more like a query than code to put something into an array. Additionally, you haven't specified what programming language you're working with, so we can't really respond with array manipulation code.

pulling from a specific data from a row and column in a database

My data base looks like this.
its ordered ascending by NO#
And col2 is the start of the database NO# is basically invisible and only used as a reference as to row number
so lets say I wanted to display on a web page the text in col8, row 5. What would the php code be?
PS. the connect code is seperate and not an issue hence i did not include itI
-|NO#|col2|col3|col4|col5|col6|col7|col8|col9|col10
---------------------------------------------------
|1 | | | | | | | | | |
---------------------------------------------------
|2 | | | | | | | | | |
---------------------------------------------------
|3 | | | | | | | | | |
---------------------------------------------------
|4 | | | | | | | | | |
---------------------------------------------------
|5 | | | | | | |2012| | |
---------------------------------------------------
|6 | | | | | | | | | |
---------------------------------------------------
|7 | | | | | | | | | |
---------------------------------------------------
|8 | | | | | | | | | |
---------------------------------------------------
|9 | | | | | | | | | |
---------------------------------------------------
|10 | | | | | | | | | |
---------------------------------------------------
Here is my code but it whites out the page when I try to load it.
<?php
//selects row
$query = "SELECT * FROM `Inventory` WHERE NO# = '5'";
//select column
$col8 = $row['col8'];
// fetch the results
WHILE($row = mysql_fetch_array($query):
$row = mysql_fetch_array($result);
// display the results
<div id="year">echo "$col8";</div>
?>
I would probably do something like what's below. I have not tested this code, though.
<?php
$result = mysql_query( "SELECT `col8` FROM `Inventory` WHERE `NO#` = '5' LIMIT 1" );
$row = mysql_fetch_assoc( $result );
?>
<div id="year"><?php echo $row['col8']; ?></div>
Hopefully that'll help you out a bit.

Categories