Select value from foreach result - php

Hi is there a way to get the value from each foreach result.
For Example I have a table named tblsamp.
id | data |
1 | d1 |
2 | d2 |
3 | d3 |
then put some query:
$query = $this->db->query("SELECT * FROM tblsamp");
foreach ($query->result() as $row){
echo $row->data .'<br>';
}
Result is:
d1
d2
d3
Now what I want is I want to get the value of the first result and compare the value from another table, and so on...
For Example:
if('d1' == '(value from another table)'{
\\do something here
} else if ('d2' == '(value from another table)'{
\\and so on.....
}
how can I do this guys? TIA!.

It looks like you are using codeigniter based off the $this->db->query syntax. With codeigniter you can change a table into an array using $query->result_array().
If you are sure both tables have the same amount of rows, you can use something like the following.
$query = $this->db->query("SELECT * FROM tbl1");
$table1 = $query->result_array();
$query = $this->db->query("SELECT * FROM tbl2");
$table2 = $query->result_array();
for ($x = 0; $x <= count($table1); $x++) {
if ($table1[$x] === $table2[$x]) {
//DO SOMETHING HERE
}
}
If $table1 might have more rows than table2, I would change it to
$query = $this->db->query("SELECT * FROM tbl1");
$table1 = $query->result_array();
$query = $this->db->query("SELECT * FROM tbl2");
$table2 = $query->result_array();
for ($x = 0; $x <= count($table1); $x++) {
if (isset($table1[$x]) && isset($table2[$x])) {
if ($table1[$x] === $table2[$x]) {
//DO SOMETHING HERE
}
} else {
break;
}
}

You can find you have matches in 2 tables however you may want to do more research about How SQL query can return data from multiple tables
How can an SQL query return data from multiple tables
This may work for your basic example
$query = $this->db->query("SELECT * FROM tblsamp,tblother");
$rst = mysql_query($query);
if(mysql_affected_rows() > 0) {
while($row = mysql_fetch_array($rst)) :
if($row['data'] == '$row['otherdata']') {
echo 'you got a match' . $row['data'] . ' In table sample to ' . $row['otherdata'] . ' In other table<br>';
}
else {
echo ' no match found in results;
}
}
endwhile;

You could add a query within your query, but this is not recommended -- things can get REALLY slow. It might be something like this:
// your original query
$query = $this->db->query("SELECT * FROM tblsamp");
foreach ($query->result() as $row){
// for each record in your original query, we run a new query derived from the result
// OBVIOUSLY you need to change this line of code to be specific to
// your database table's structure because some_col is probably not
// the name of a column in your database
$subquery = $this->db->query("SELECT * FROM other_table WHERE foo=" . $row->some_col);
$subrows = $subquery->result();
// output $subrows here?
// note that $subrows might be an array with any number any number of records
}
the exact code will depend on the db classes you are using. It's codeigniter, if I'm not mistaken? EDIT: it is codeigniter.
The correct solution here is going to depend on your database table definitions. I would strongly suggest creating a JOIN using CodeIgniter, but can't offer much more advice without some idea of what your db structures are going to look like and how many records in the second table exist for each record in the first table.

Related

Best practice for writing code in php for foreach->foreach->if(1st loop id == 2nd loop id)->result

First loop table
user_id | fname | lname
1 | first | emp
2 | second| emp
3 | third | emp
Second loop table
shift_id | employee_id
1 | 1
2 | 2
3 | 2
if($employees)
{
foreach ($employees as $employee)
{
if($employee['user_id'] == $shift['employee_id'])
{
echo ucwords($employee['fname']. ' ' .$employee['lname']);
}
}
}
I am getting the right result but I think there is some better way of writing this.
You can use joins in table. Left join means that the user line has to exists (because: LEFT) and the shifts enty is optional.
SELECT user.user_id, user.fname, user.lname, shifts.shift_id
FROM yourUserTable AS user
LEFT JOIN yourShiftsTable AS shifts ON(user.user_id = shifts.employee_id)
Now you get it in your initial array, as if you'd select it as one row from a table and no longer need to do tricks in PHP to combine information. If you can, always try to get the database to manage data, it does that way faster than PHP can.
Please note, the query could be a little off, I just wrote this out of the top of my head.
Just some test code I whipped up to test this from the information provided for this "Demonstration Code".
Note: I have used the mysqli class for the database (instantiating $db ) and have excluded the SQL Table setup.
What you would have had is something along the lines of this...
Case 1 - The original
$db = new mysqli('localhost', 'root', 'test', 'phptutorials_st26');
echo '<h2>Create $employees </h2>';
$query = "SELECT * FROM users";
$result = $db->query($query);
$employees = $result->fetch_all(MYSQL_ASSOC);
var_dump($employees);
echo '<h2>Create $shifts </h2>';
$query = "SELECT * FROM shifts";
$result = $db->query($query);
$shifts = $result->fetch_all(MYSQL_ASSOC);
var_dump($shifts);
echo '<h2>Using foreach on $employees and $shifts</h2>';
if ($employees) {
foreach ($employees as $employee) {
foreach ($shifts as $shift) {
if ($employee['user_id'] == $shift['employee_id']) {
echo ucwords($employee['fname'] . ' ' . $employee['lname']);
echo '<br>';
}
}
}
}
The Result from the above is
First Emp
Second Emp
Second Emp
Case 2 - Using a Join
Well using a join, as everyone has already stated, is the way to go...
$sql = "SELECT u.user_id, u.fname, u.lname, s.shift_id
FROM users AS u
JOIN shifts AS s ON(u.user_id = s.employee_id)
";
$result = $db->query($sql);
$employees = $result->fetch_all(MYSQL_ASSOC);
// To see what comes out because we always check things.
var_dump($joined_result);
(Don't ask me why I love using very abbreviated aliases for the table names! It's just "a thing".)
Then your "loop" simply becomes...
echo '<h2>Using foreach on join</h2>';
foreach ($employees as $employee) {
echo ucwords($employee['fname'] . ' ' . $employee['lname']);
echo '<br>';
}
And the result is...
First Emp
Second Emp
Second Emp
Case 2 - has reduced the code and only requires 1 Trip to the Database.
Does that help you any?
You could do it this way also. Its a little shorter.
SELECT TABLE1.FNAME, TABLE1.LNAME, TABLE2.EMPLOYEE_ID
FROM TABLE1, TABLE2
WHERE TABLE1.USER_ID = TABLE2.EMPLOYEE_ID;

PHP/SQL: Faster Way to Combine Query Results

I'm joining data from two SQL queries and I'm wondering if there is a faster way to do this as a single SQL query because there is a lot of looping involved. I've got two queries that look for different string values in the "option_name" field:
$sql01= "SELECT user_id, option_value FROM wp_wlm_user_options WHERE option_name = 'wpm_login_date' ORDER BY user_id";
$sql02 = "SELECT user_id, option_value FROM wp_wlm_user_options WHERE option_name ='stripe_cust_id' ORDER BY user_id ";
Then I create two arrays:
//Process the 1st SQL query data into an Array
$result_array01 = array();
$j = 0;
while($r = mysql_fetch_assoc($result01)) {
if(!empty($r['option_value'])){
//User Id and Last Login
$result_array01[$j]['user_id'] = $r['user_id'];
$result_array01[$j]['last_login'] = $r['option_value'];
$j++;
}
}
//Process the 2nd SQL query data into an Array
$result_array02 = array();
$k = 0;
while($s = mysql_fetch_assoc($result02)) {
if(!empty($s['option_value'])){
//User Id and Stripe Customer Id
$result_array02[$k]['user_id'] = $s['user_id'];
$result_array02[$k]['cust_id'] = $s['option_value'];
$k++;
}
}
And finally, I combine the arrays:
//Combine the SQL query data in single Array
$combined_array = array();
$l = 0;
foreach($result_array01 as $arr01){
// Check type
if (is_array($arr01)) {
//mgc_account_print("hello: " . $arr01['user_id'] . "\r\n");
foreach($result_array02 as $arr02){
// Check type
if (is_array($arr02)) {
//Check if User Id matches
if($arr01['user_id'] == $arr02['user_id']){
//Create Array with User Id, Cust Id and Last Login
$combined_array[$l]['user_id'] = $arr01['user_id'];
$combined_array[$l]['last_login'] = $arr01['last_login'];
$combined_array[$l]['cust_id'] = $arr02['cust_id'];
$l++;
}
}
}
}
}
Why you doing in two different queries?
Use mysql IN('val', 'val2');
$sql01= "SELECT tbl1.user_id, tbl1.option_value FROM wp_wlm_user_options as tbl1 WHERE tbl1.option_name = 'wpm_login_date'
union all
SELECT tbl2.user_id, tbl2.option_value FROM wp_wlm_user_options as tbl2. WHERE tbl2.option_name ='stripe_cust_id' ";
But using OR/AND will your help you in your case , I didnt see at first that you want combined same table. I didnt delete my answer to help you for another solution
Also you should use DISTINCT to avoid multiple records.
SELECT DISTINCT USER_ID, OPTION VALUE FROM TABLE

Make hierarchy from table with PHP

I have a table in database and in this table i have added 3 columns that is i, name,parent_id.please see below.
ID | name | parent_id
1 name1 0
2 name2 1
3 name3 1
Now i want to fetch this id from database. I have created a method in PHP and fetch data one by one from database. Please see below
function getData($id)
{
$array = array();
$db = JFactory::getDBO();
$sql = "SELECT * from table_name when id = ".$id;
$db>setQuery($sql);
$fetchAllDatas = $db->getObjectList();
foreach ($fetchAllDatas as $fetchAllData)
{
if($fetchAllData->parent_id > 0)
{
$array[$fetchAllData->parent_id] = $fetchAllData->name;
$this->getData($fetchAllData->parent_id);
}
else
{
$array[$fetchAllData->parent_id] = $fetchAllData->name;
}
}
return $array;
}
Now if i call this method with id 3 like
$this->getData(3); // has a parent
It will return like that
Array(
[0]=>name1
)
But i want like below
Array(
[1]=>name3,
[0]=>name1
)
I know i have redefine array if we have parent but how i manage it.
i have used array_push php function but its not work with my condition.
foreach ($fetchAllDatas as $fetchAllData)
{
$array[$fetchAllData->parent_id] = $fetchAllData->name;
if($fetchAllData->parent_id > 0)
array_push($array,$this->getData($fetchAllData->parent_id));
}
return $array;
1)Because you do $array[$fetchAllData->parent_id] = $fetchAllData->name; in the if and in the else, you do this in both cases so put out of if..else.
2) Try to push the result of your second call in the original array to get what you want.
you have unique ID in your table, so if you call your query it will always return only one result. Maybe you wanted to write query this way:
$sql = "SELECT * from table_name when parent_id = ".$id;
if you want to get the result with given ID and his parent, you should add this after calling $this->fetchSharedFolder(...);
$array = array_merge($array, $this->getData($fetchAllData->parent_id));

When i use if else condition in query based on condition, how can i get that value on view in PHP CODEIGNITER

I am confuse with this problem in mysql, I have two table, "A" and "B"
TableA:
S.No contact1 contact2 status
1 Blbh eeee 1
TAbleB:
S.No Phone1 phone2
1 ddd ssss
From this table i am going to get value, from TableA ia m going to check
if (status == 1)
{
run tableA;
}
else
{
run table b;
}
I am gone a return result of this query. In view, how to get value with respected column name. I have no idea of this, help me to get value in view.
public function contDetails($id){
$check = $this->db->query("SELECT contact_status FROM account WHERE id = '$id' ");
$str = $check->row();
$chk = $str->contact_status;
if($chk == 1){
$query = $this->db->query("SELECT * FROM account WHERE id = '$id'");
}else{
$query = $this->db->query("SELECT * FROM contact_details WHERE user_id = '$id'");
}
$run = $query->num_rows();
print_r($run);
}
You can use in your model
$query = $this->db->get(); //--- run the query ---//
return $query->result() //--- to get result in array of object ---//
and then in your view use foreach loop
foreach($results as $result){
echo $result->columnName;
}
have you already written the query in mysql? If yes and if you are concerned about whether the column name to use exist or not you can use isset...
in your view you can use like the following:
<?php
foreach($results as $result)
{
echo (isset($result['col1']))?$result['col1']:$result['col1_2'];
}
?>
And don't forget to use result_array() instsead of result in the controller

Queries with conditional queries

Let's say i have a query with quite a number of joins and subqueries in one php file that handles queries.
Nb: i put an example of what $query looks like at the bottom
$query = query here;
if ($query) {
return $query->result();
} else {
return false;
}
}
Then in my php file that handles the html, i have the usual foreach loop with some conditions that require making other queries e.g;
Note: result houses object $query->result().
foreach ($results as $item) {
$some_array = array();
$some_id = $item->id;
if ($some_id != 0) {
//id_return_other_id is a function that querys a db table and returns the specified column in the same table, it returns just one field
$other_id = id_return_other_id($some_id);
$some_query = another query that requires some joins and a subquery;
$some_array = the values that are returned from some_query in an array
//here i'm converting obj post into an array so i can merge the data in $some_array to item(Which was converted into an array) then convert all of it back into an object
$item = (object)array_merge($some_array, (array)$item);
}
//do the usual dynamic html stuff here.
}
This works perfectly but as i don't like the way i'm doing lot's of queries in a loop, is there a way to add the if $some_id != 0 in the file that handles queries?
I've tried
$query = query here;
//declaring some array as empty when some_id is 0
$some_array = array();
if ($query) {
if ($some_id != 0) {
//same as i said before
$other_id = $this->id_return_other_id($some_id);
$some_query = some query;
$some_array = array values gotten from some query;
}
$qresult = (object)array_merge($some_array, (array)$query->result);
return $qresult;
} else {
return false;
}
}
This doesn't work for obvious reasons, does any one have any ideas?
Also if there's a way to make these conditions and queries in the $query itself i'd love you forever.
Ps: A demo query would be something like
$sql = "SELECT p.*,up.*,upi.someField,etc..
FROM (
SELECT (another subquery)
FROM table1
WHERE table1_id = 3
UNION ALL
SELECT $user_id
) uf
JOIN table2 p
ON p.id = uf.user_id
LEFT JOIN table3 up
ON .....
LEFT JOIN table4
ON ....
LEFT JOIN table5
ON ....
And so on..etc..
ORDER BY p.date DESC";
$query = mysql_query..
It seems like you just need to run two queries in your query file. The first query would get a broad set of what you’re looking for. The second query would query an id that’s in the result and perform a new query to get any details about that particular id. I use something similar to this in the customer search page for my application.
$output = array();
$query1 = $this->db->query("SELECT * FROM...WHERE id = ...");
foreach ($query->result_array() as $row1)
{
$output[$row1['some_id']] = $row1;
$query2 = $this->db->query("SELECT * FROM table WHERE id = {$row1['some_id']}");
foreach ($query2->result_array() as $row2)
{
$output[$row1['some_id']]['data_details'][$row2['id']] = $row2;
}
}
Then in your page that displays html, you’ll just need two foreaches:
foreach($queryresult as $key=> $field)
{
echo $field['some_field'];
foreach($child['data_details'] as $subkey => $subfield)
{
echo $subfield['some_subfield'];
}
}
I know you’re using objects, but you could probably convert this to use that format. I hope this makes sense/helps.
use this
if ($some_id !== 0) {
instead of
if ($some_id != 0) {

Categories