Muhammad Ahsan Ayaz Khan Muhammad Ahsan Ayaz Khan - 9 months ago 28
MySQL Question

how to combine 2 sql queries to get 1 result

SELECT users.name, users.registrationdate, users.city, users.status
FROM users, referrals
WHERE users.username= referrals.referrals AND referrals.username='user_name'

SELECT adearning, reffearning
FROM earnings WHERE usersname='user_name33'


How can I combine these two queries as if first query condition doesn't match and doesn't run.. then the second query should run and return some value if condition match

Answer Source

Try this

$query1 = $this->db->query("SELECT users.name, users.registrationdate, users.city, users.status 
                            FROM users, referrals 
                            WHERE users.username = referrals.referrals AND referrals.username='user_name'")
$result1 = $query1->result_array();


$query2 = $this->db->query("SELECT adearning, reffearning FROM earnings WHERE usersname='user_name33' ")
$result2 = $query2->result_array();


$dataArray = array_merge($result1, $result2);

if want to check the result, end of the line add this

print_r($dataArray);die;

On this it will print all of them in one array


Example

$result1 = array(
    '0' => 'sjhccsd', 
    '1' => 'ddd', 
    '2' => 'df', 
    '3' => 'dfd', 
    );

$result2 = array(
    '0' => 'sjhccsd', 
    '1' => 'ddd', 
    '2' => 'df', 
    '3' => 'dfd', 
    );


$dataArray = array_merge($result1, $result2);

print_r($dataArray);

Output : Array ( [0] => sjhccsd [1] => ddd [2] => df [3] => dfd [4] => sjhccsd [5] => ddd [6] => df [7] => dfd )