How to limit foreach for multiple table as a one - php

I have the issue with LIMIT with foreach using PHP.
Basics: I have 50 different tables and in every table I have 2 rows.
When I try to add LIMIT 1 to $$modules_for_all, then I see 50 rows, but I want to see only 1. If I add LIMIT 2, then I see 100 rows.
How I can connect all these tables as a one LIMIT 1 to get 1 row in foreach?
<?php
for ($i = 1; $i <= 50; $i++) {
// $array_table_name contains names with tables
$table_names = $array_table_name[$i];
$modules_for_all = 'g_module_for_all_'.$i;
$$modules_for_all = $db->QueryFetchArrayAll("SELECT * FROM $table_names WHERE user='1' LIMIT 1");
}
for ($i = 1; $i <= 50; $i++) {
$modules_for_from = ${"g_module_for_all_$i"};
foreach ($modules_for_from as $m_foreach_as) {
echo $m_foreach_as['id'];
}
}
Example tables:
table_1
id date_added
1 2018-12-01 00:00:00
2 2018-12-02 00:00:00
table_2
id date_added
1 2018-12-03 00:00:00
2 2018-12-04 00:00:00
table_3
id date_added
1 2018-12-05 00:00:00
2 2018-12-06 00:00:00
Example foreach:
<?php
$array_table_name_1 = 'table_1';
$array_table_name_2 = 'table_2';
$array_table_name_3 = 'table_3';
$for_table_1 = $db->QueryFetchArrayAll("SELECT * FROM $array_table_name_1 WHERE id='1' LIMIT 1 ORDER BY date_added");
$for_table_2 = $db->QueryFetchArrayAll("SELECT * FROM $array_table_name_2 WHERE id='1' LIMIT 1 ORDER BY date_added");
$for_table_3 = $db->QueryFetchArrayAll("SELECT * FROM $array_table_name_3 WHERE id='1' LIMIT 1 ORDER BY date_added");
foreach ($for_table_1 as $m_foreach_as) {
echo $m_foreach_as['id'];
}
foreach ($for_table_2 as $m_foreach_as) {
echo $m_foreach_as['id'];
}
foreach ($for_table_3 as $m_foreach_as) {
echo $m_foreach_as['id'];
}
// Now result is '111' but I want only '1' (realted to make LIMIT 1 to all foreach)

The only way to connect the tables is by using a UNION. So you will need to build one large UNION query and then perform the select after the loop:
$tables = array();
for ($i = 1; $i <= 50; $i++) {
// $array_table_name contains names with tables
$table_names = $array_table_name[$i];
$tables[] = "(SELECT * FROM $table_names WHERE user='1')";
}
$query = implode(" UNION ", $tables) . " ORDER BY date_added LIMIT 1";
$result = $db->QueryFetchArrayAll($query);
foreach ($result as $row) {
echo $row;
}

You are gonna have to use UNION ALL for summing this rows together before ordering and limiting the results.
But keep in mind that a query like this will only work if all the tables in your array have the same structure. If they do not, then you will have to be specific in the query to make them have the same fields.
$array_table_name = [
'table_1',
'table_2',
'table_3',
];
$search_id = 1;
$selectsArray = [];
foreach ($array_table_name as $table_name) {
$selectsArray[] = "SELECT * FROM $table_name WHERE id='$search_id'\n";
}
As you see, I am using foreach() and not for() so you won't update the for by decreasing/increasing the number of tables in the array. So to finally have:
$selectsUnion = implode("UNION ALL\n", $selectsArray) . "ORDER BY date_added \nLIMIT 1";
You can see the code tested and query mounted here: https://3v4l.org/HXH2K

I solved my problem using this: foreach ($modules_for_from as $m_foreach_as) if ($tmp++ < 1) {

Related

Show only the last result from mysql row

I have a table
id | field1 | field2 | ... | field[x-1] | field[x]
1 | val1 | val2 | ... | val[x-1] | val[x]
And I'm doing this search
for($i = 1; $i <= $x; $i++){
$getvalue = mysql_query("SELECT * FROM table WHERE id='1' AND field".$i." LIKE 'some_value%'")or die(mysql_error());
while($row = mysql_fetch_array($getvalue)){
$j=$i+1;
$val = $row['field'.$j.''];
}
}
Some values in the table (val[1-x]) will be the same but I need to get only the LAST value. Limit 1 doesn't seem to work.
Update.
Unfortunately as David suggested, I can't change the database. It has to be as it is. I have a text file (a settings dump from a sensor) that I insert it line by line into the db and do a check to see if there are any errors. Most check run ok but I have a few lines in that I need to choose only the last one to do the check.
I have about 10 lines like this
D?
String
R?
String
...
D?
String
R?
String
I'm interested in the last string after R?. I use explode () and each value checked that they are with in limits.
Using ORDER BY id DESC LIMIT 1:
To get last row (with highest=last=newest id), you should use this:
SELECT * FROM table ORDER BY id DESC LIMIT 1;
Your updated code (with mysqli_ extension) to get last row:
$query= mysqli_query("SELECT * FROM table ORDER BY id DESC LIMIT 1") or die (mysqli_error());
}
$lastRow = mysqli_fetch_row($query);
echo $lastRow['id']; //get the last id
Using MAX():
You also can do it using SQL MAX() function:
SELECT * FROM table WHERE id=(SELECT MAX(id) FROM table)
Managed to get it working as I need it by doing this:
for($i = 1; $i <= 250; $i++){
$getvalue = mysql_query("SELECT * FROM full_dump WHERE file_name='".$_FILES['datafile']['name']."' AND field_".$i." LIKE ' 100,%'")or die(mysql_error());
while($row = mysql_fetch_array($getvalue)){
$i_temp = $i;
}
}
if($i_temp != NULL){
$getvalue = mysql_query("SELECT * FROM full_dump WHERE file_name='".$_FILES['datafile']['name']."' AND field_".$i_temp." LIKE ' 100,%'")or die(mysql_error());
while($row = mysql_fetch_array($getvalue)){
$r = $row['field_'.$i_temp.''];
}
}

how to explode mysql table data in php

In mysql table table data, one column has multiple value like this,
code name
1,2,3 a
4 b
My desired output will be
code name
1 a
2 a
3 a
4 b
Here is my code:
$sql="SELECT * FROM hsc_sub group by sub_name order by sub_code";
$res = app_db_query($app,$sql);
while($row = mysqli_fetch_assoc($res)){
//enter code here
$subj[] = $row;
$subj[] = explode(",",$row['sub_code']);
}
Within the ForEach Loop, we can achieve your requirement.
$subCode[];
$name[];
echo("Code");
echo("\t");
echo("Name");
echo("\n");
$sql="SELECT * FROM hsc_sub group by sub_name order by sub_code";
$res = app_db_query($app,$sql);
while($row = mysqli_fetch_assoc($res)){
$nm = $row['sub_name']
$sub[] = explode(",",$row['sub_code']);
foreach($sub as $item)
{
$name.push($nm);
$subCode.push($item);
echo($item);
echo("\t");
echo($nm);
echo("\n");
}
}

Fetching data from relational database in codeigniter

I have got 2 tables; table1 and table2. Both of them are related to eachother with a common groupid I am able to query the second table successfully using the following code:
$query = $this->db->query("SELECT * FROM `table2` WHERE `memberid`='$id'");
$data['relation'] = $query->result_array();
Now using groupid result I want to query the first table i.e. table1
I have tried the following methods, without any success:
for($ii = 0 ; $ii < count($data['relation']) ; $ii++){
$id = $data['relation'][$ii]['groupid'];
$query1 = $this->db->query("SELECT * FROM `group` WHERE `id`='$id'");
}
$data1['group'] = $query1->result_array();
$fine = array_merge($data, $data1);
print_r(count($fine)); // the count result is 1 ideally should be 2
The above code only returns the last row of the table1 however I am looking for all the results.
When I run the above code inside the "for" loop, it shows me a count of 33:
for($ii = 0 ; $ii < count($data['relation']) ; $ii++){
$id = $data['relation'][$ii]['groupid'];
$query1 = $this->db->query("SELECT * FROM `group` WHERE `id`='$id'");
$data1['group'] = $query1->result_array();
$fine = array_merge($data, $data1);
print_r(count($fine)); // the count result is 33 ideally should be 2
}
I know how to achieve this in core php however not too sure how to do it in CI. I am new to CI, any help will be greatly appreciated.
Thanks,
Utpal
$ok = array();
for($ii = 0 ; $ii < count($data['relation']) ; $ii++){
$id = $data['relation'][$ii]['groupid'];
print_r ($id);
echo "<br>";
$query1 = $this->db->query("SELECT * FROM `group` WHERE `id`='$id'");
$data1['group'][$ii]= $query1->result_array();
}
//print_r($data1['group']);
$fine = array_merge($data, $data1);
print_r($fine);
You need to create a array ($data1) outside this for loop and define $query->result_array(); inside forloop as shown above

Mysql search with semi colon delimited string

I have 2 tables that look like this
table A table B
id | data id | features
--------- --------------
1 | blue 1A | 1;2
2 | red 2B | 1;2;3
3 | yellow 3B | 3;1
...... ......
What i plan to do is something like this, where i query one table. loop thru the array of results and explode the data with the semicolon delimiter. then loop thru that new array and query it to get the data (note code below not tested)
$sql = "SELECT * FROM `tableB` WHERE `id`= '2B' LIMIT 1";
$query = $db->query($sql);
while ($row = mysql_fetch_array($query)) {
$arr = explode(';', $row['features']);
for ($i = 0; $i < sizeof($arr); $i++)
{
$sql2 = "SELECT * FROM `tableA` WHERE `id`="'.$arr[$i].'"";
$query2 = $db->query($sql2);
while ($row2 = mysql_fetch_array($query2)) {
$r[] = $row2['data'];
}
}
}
print_r($r);
is there a way i can achieve this just in mysql, where i match the column in tableB with the ID's in tableA? or maybe by not using a nested loop? performance is key. coz both tables have more than 25k rows of data.
thanks in advance
Check out this code. Reduced few loops.
$sql = "SELECT * FROM `tableB` WHERE `id`= '2B' LIMIT 1";
$query = $db->query($sql);
$arr = explode(';', $row['features']);
$str = implode(",", $arr);
$sql2 = "SELECT * FROM `tableA WHERE id IN ({$str});";
$query2 = $db->query($sql2);
while ($row2 = mysql_fetch_array($query2)) {
$r[] = $row2['data'];
}
What you are looking for is the IN function
This will take an array of id's and give you every result in a single query.
So your code should look like this after you apply it
while ($row = mysql_fetch_array($query)) {
$new_query = str_replace(";", ",", $row['features']);
$sql2 = "SELECT * FROM `tableA` WHERE `id` IN ($new_query)";
$query2 = $db->query($sql2);
while ($row2 = mysql_fetch_array($query2)) {
$r[] = $row2['data'];
}
}

select with limit and update table. Limit not working fine. sql

I am trying to update thable with select using limit
It's update table fine when we enter "limit" only with one parameter in select query like (limit 50)
But when select with "limit" like (limit $sqlFrom, $sqlTo) it updates the table but skip 2nd (51 to 100) records and again start updating from 101.
It skip every 2nd 50 records
Where is the problem???
Here is the code
$sqlFrom = 0;
$sqlTo = 50;
for($try = 0; $try < 6; $try++)
{
$res = mysql_query("select * from table_name where underprocess = 0 limit " . $sqlFrom . "," . $sqlTo);
while($row = mysql_fetch_array($res))
{
$id = $row['id'];
mysql_query("update table_name set underprocess = 1 where id = " . $id) or die('error');
echo $id;
}
print '<hr/>';
if($sqlFrom != 0)
{
$sqlFrom += $sqlTo;
}
else
{
$sqlFrom = $sqlTo;
}
}//for
This is as expected
When you update rows 1-50 based on your first iteration, you set underprocess = 1. These are ignored in the 2nd call because ask for rows underprocess = 0.
So rows 51-100 in the 1st query are now rows 1-50 for your 2nd query if you like.
You don't need to change your LIMIT range because you always want the "first" 50.
NOTE
Your LIMIT isn't guaranteed anyway because you have no ORDER BY.

Categories