How to iterate through a table from last row to first? - php

My table:
-----------------------
| id: | data: |
|---------------------|
| 1 | a |
| 20 | b |
| 546 | c |
-----------------------
I want to store the data in an array from last inserted row (id is auto incremented) to first.
$sth = $dbh->query('SELECT * FROM mytable');
$data = array();
while ($row = $sth->fetch(PDO::FETCH_ASSOC))
{
array_push($data, $row);
}
return $data;
What can I add to the query in order to loop through the table from bottom to top?
I tried variations of ORDER BY but they didn't work, I'm missing something.

Change MySQL statement to be
SELECT * FROM 'mytable' ORDER BY 'id' DESC
or reverse the array using PHPs reverse array function
return array_reverse($data);

Get records by descending order
use following query
SELECT * FROM mytable order by id desc
where id is the auto increment id of your table

Related

How to do a multiple select from same column as one query

I have a Mysql database table named as_items as below:
-----------------------------------------------------------------------
| itemid | item_type | item_number | item_title | item_content |
-----------------------------------------------------------------------
| 1 | 1 | 2 | First Item | The first item |
| 2 | 2 | 3 | Second Item | The second item |
| 3 | 3 | 5 | Third Item | The third item |
| 4 | 3 | 1 | Forth Item | The forth item |
| 5 | 2 | 4 | Fifth Item | The fifth item |
-----------------------------------------------------------------------
I would like to get multiple queries from the same column which in this case is "item_type" using my php script. In my php script the reference value could one or multiple based on the existence of the character "," in it which my code check for.
if (strpos($itemtypes, ',') !== false) {
$items = explode(',',$itemtypes);
$query = "SELECT ";
foreach ($items as $item){
$query .= "(SELECT * FROM as_items WHERE item_type=$item ORDER BY item_number ASC) AS j$item, ";
}
$result = mysql_query($query) or die(mysql_error());
} else {
$songbook = $songbookids;
$result = mysql_query("SELECT * FROM as_items WHERE item_type= $itemtypes ORDER BY item_number ASC") or die(mysql_error());
}
Take into account the query is based on the php final output. When i use the multiple query I get an error from the server as "Operand should contain 1 column(s) "
NOTE:
Please note the reference item is from my other code where when 2 or 3 item types are selected its output is like "itemtype,itemtype,itemtype" but when only one is selected it is just plain as "itemtype".
Instead of doing the query(s) like that, try this:
$query = "SELECT * FROM as_items WHERE item_type IN ('".str_replace(',', '\',\'', $itemtypes)."') ORDER BY item_number ASC";
$result = mysql_query($query);
This should replace your whole thing, no need to check if , is in the string.

MySQL PHP nested results

I have 3 tables:
profile
id | fname | policy
users
id | fullname | claimnum
and returnprod
claim_id | prodname | description
My SQL is this:
("SELECT *
,CONCAT(fname, ' ' ,lname) AS fullName
,CONCAT(firstname, ' ' ,lastname) AS InsName
,a.address AS ADDRESS
,a.city AS CITY
,a.state AS STATE
,a.zip AS ZIP
,a.phone AS PHONE
,a.fax AS FAX
,a.email AS EMAIL
FROM profile a
INNER JOIN returnprod b ON a.policy = b.claim_id
INNER JOIN users c ON a.adjuster_id = c.id
WHERE date >= '$Start' AND date <= '$End'
Jump ahead a little bit to the loop
`$products[]= $row;`
`foreach ($products as $product)
{
if ($row['policy'] === $product['claim_id']) {
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowcount,$product['product']);
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowcount, $product['comment']);
$objPHPExcel->getActiveSheet()->SetCellValue('D'.$rowcount, $product['anotes']);
$objPHPExcel->getActiveSheet()->SetCellValue('E'.$rowcount, $product['price']);
}`
This is working fine if there is only one product. The result will look something like this...
row 1: claim_id | firstname | adjuster name
row 2: productname | description | etc
If I have more than one product this happens...
row 1: claim_id | firstname | adjuster name
row 2: productname | description | etc
row 3: claim_id | firstname | adjuster name
row 4: productname | description | etc
row 5: productname | description | etc
Instead of grouping all the products together and displaying all of them below the profile information it is giving me the first result under the profile then giving me the profile information again with the first product and then the second product.
How do I go about grouping all products underneath the profile the first time?
Example:
row 1: claim_id | firstname | adjuster name
row 2: productname | description | etc
row 3: productname | description | etc
Thank you for taking the time to read through this.
$products[] = $row seems to indicate that this is not the only loop; more context might help. At the least, you will want to sort your DB results by whatever you intend to group by (ORDER BY a.id, a.policy). Then you could keep a reference to the last-seen policy and skip the header if it matches.
$last_id = '';
foreach ($rows as $row) {
if (! $row['policy'] === $last_id ) {
// Write claim_id | firstname | adjuster name
}
// Write productname | description | etc
$last_id = $row['policy'];
}
Assuming that is what you are after...
I went about this a different way.
instead of using FOREACH I ended up using WHILE.
while($row = mysql_fetch_array($result)){
// CODE TO QUERY PROFILE INFORMATION
$productquery=("SELECT * FROM returnprod WHERE claim_id = '$POLICY'");
while($product = mysql_fetch_array($prods)){
//CODE TO QUERY THE PRODUCTS ASSOCIATED WITH THE PROFILE
}
}
Then I added GROUP BY a.policy in the $result

Creat treeview array or sub array

These are the data as they are in mysql table
Table A (Tasks)
task_id | name | description
-----------------------------
1 | soccer| fora
-----------------------------
2 | sussam| forb
-----------------------------
3 | sosssi| forc
-----------------------------
4 | sillly| ford
Tabble B Milestones
mile_id | name | task_id
------------------
1 | task1mi | 1
------------------
2 | task2mi | 1
-------------------
3 | task3mi | 3
I am looking to making a treeview array, something like for each task as a parent milestone as a child array of task id.
What the print_r() function should return (desired output with php after mysql query)
array(
name=>'soccer',
description =>'fora'
task_id=>array(
mile_id=>'1',
name=>'task1mi'
)
)
Any Suggestions
You can do it following way but it is not good for performance. I don`t know exact requirement and fretwork are you using. So i am giving basic idea.
$sqlparent = "select * from tasks";// get your task details from database.
$parentData = $sqlparent;// result from sql function.
foreach($parentData as $key=>$value)
{
$sql = "select * from Milestones where task_id='".$value['task_id']."'";// find the Milestones of the task
$milestonesResult = mysql_featch_array($sql); // run sql and get data from database it is giving you single record you need to create loop here. as i don`t know what are you using for PHP.
$value['milestoneslist'] = $milestonesResult; //task_id=>array( here you can not use task_id => array as it is already there. if you do it it will over-right the task_id
}
I hope you will get idea from this.
You can use below code for your solution as i thought
$sql = "select table_b.*,table_a.name as aname, table_a.description as description as aname from table_b left join table_a on table_b.task_id=table_a.task_id"
$result = mysql_query($sql);
//based on above query result you will get array on mysql_fatch_assoc
$result_array = array();
while($result = mysql_fatch_assoc($result)){
$tmp_arr = array();
$tmp_arr['mile_id'] = $result['mile_id'];
$tmp_arr['name'] = $result['name'];
$result_array[$result['task_id']]['name'] = $result['aname'];
$result_array[$result['task_id']]['description'] = $result['description'];
$result_array[$result['task_id']]['task_id'][] = $tmp_arr;
}
$result_array = array_values($result_array);
print_r($result_array);

Php , Mysql Select from table where row = ? it is possible?

Hello I want to get select query with send row record number
$row = 3;
SELECT FROM clients WHERE ROW()=$row ORDER BY ID DESC
it is possible ? How can i do that ?
If you want the third row, use offset/limit:
select *
from clients
order by id
offset 2
limit 1;
Note that that offset 0 gets the first record, so offset 2 would be the third record.
You need to use LIMIT instead of WHERE
If you want get a row with N position, you can try this:
SELECT * FROM clients LIMIT N-1,1
So if you want get third row you need to use something like this:
SELECT * FROM clients LIMIT 2,1
This is what i would do.. entry_id is unique and 1 = first row, 2 = second row, etc..
entry_id is set as primary index and auto increase..
entry_id | what | ever | records
1 | a | b | c
2 | a | b | c
3 | b | c | a
4 | a | b | c
5 | a | b | c
$row = 3;
Select * From clients Where entry_id = $row
returns third row, 3, b, c, a

Doctrine: Multiple orWhere with LIKE condition

Use table with structure:
id | count
/string/id1 | 3
/string/id1/r1 | 2
/string/id1/r2 | 1
/string/id2/r1 | 2
/string/id2 | 3
/string/id2/r1 | 2
/string/id3/r1 | 5
and I want to select all rows which have needed substring in id.
i.e.
I need all rows which have substring in id: /string/id1 and /string/id2
The query should be easy - plain sql:
select * from table_name where id LIKE '/string/id1%' OR id LIKE '/string/id2%';
Result should be:
id | count
/string/id1 | 3
/string/id1/r1 | 2
/string/id1/r2 | 1
/string/id2/r1 | 2
/string/id2 | 3
/string/id2/r1 | 2
Unfortunately, if you try to use the same query in symfony and doctrine2:
$ids = array('/string/id1', '/string/id2');
$query = $this->createQueryBuilder('r')
->select('r');
foreach ($ids as $id) {
$query->orWhere("r.linkedId LIKE :id ")
->setParameter('id', $id."%");
}
$plainQuery = $query->getQuery()->getSQL();
$results = $query->getQuery()->getResult();
Plain query looks the same like select * from table_name where id LIKE '/string/id1%' OR id LIKE '/string/id2%';, but results are not.
results contains only rows of last item in ids - /string/id2
id | count
/string/id2/r1 | 2
/string/id2 | 3
/string/id2/r1 | 2
How to solve it? Where is my mistake? Do you have any suggestion?
I cannot be sure but this seems to me like a conflict with parameter identifiers.
This is what you're trying to do:
Construct the basic SELECT * FROM table_name statement
Append WHERE r.linkedId LIKE :id
set the value of id parameter to /string/id1%
Append OR r.linkedId LIKE :id
set the value of id parameter to /string/id2% (override the previous value) <-- AN ERROR
Basically, you are telling Doctrine to override previously defined value of id parameter with new one.
You could easily overcome this issue. Just add $i to parameter name
foreach ($ids as $i => $id) {
// $i here has the value of 0,1,2, etc...
$query->orWhere("r.linkedId LIKE :id$i" ) // append $i
->setParameter("id$i", $id."%"); // but also append it here
}
Be sure to use double quotes, or concatenate ("id" . $i) instead ;)

Categories