1

hello i would like to shorten my code and would like to combine two functions that exactly do the same.

so i got this:

function a($a){
    global $db;
    $query = $db->query("SELECT col_a FROM table WHERE Field= '$a' ");
    $check = $query->fetch_assoc();
    $return_a = $check['col_a'];
    return ($return_a);
}
function b($a){
    global $db;
    $query = $db->query("SELECT col_b FROM table WHERE Field= '$a' ");
    $check = $query->fetch_assoc();
    $return_b = $check['col_b'];
    return ($return_b);
}

so i thought i could combine both into one:

function ab($a){
global $db;
$query = $db->query("SELECT col_a, col_b FROM table WHERE Field= '$a' ");
$check = $query->fetch_assoc();
$return_array = array( $check['col_a'], $check['col_b'] );
return ($return_array);
}

this does not seems to work. i tried reading out the array by using:

$db_data = ab($a);

echo $db_data['col_a'];
echo $db_data['col_b'];

so if there is someone who could tell what am i doing wrong i really would appreciate.

thanks alot.

0

4 Answers 4

1

if you do this (same as your code) you can access it like

function ab($a){
    global $db;
    $query = $db->query("SELECT col_a, col_b FROM table WHERE Field= '$a' ");
    $check = $query->fetch_assoc();
    $return_array = array( $check['col_a'], $check['col_b'] );
    return ($return_array);
}



$db_data = ab($a);

echo $db_data[0]; // will return 'col_a';
echo $db_data[1]; // will return 'col_b';

you should do this

function ab($a){
    global $db;
    $query = $db->query("SELECT col_a, col_b FROM table WHERE Field= '$a' ");
    $check = $query->fetch_assoc();
    //$return_array = array( $check['col_a'], $check['col_b'] );
    return ($check);
}

and when you need to fetch

$db_data = ab($a);

echo $db_data['col_1'];
echo $db_data['col_1'];
Sign up to request clarification or add additional context in comments.

Comments

1

Try this :

$db_data = ab($a);

echo $db_data[0];
echo $db_data[1];

Comments

1

You're not creating a named array, so your result is indexed with $db_data[0] and $db_data[1]

Replace: $return_array = array( $check['col_a'], $check['col_b'] );

With: $return_array = array( 'col_a' => $check['col_a'], 'col_b' => $check['col_b'] );

Or even more simpler just return $check;

Comments

0
list($col_a, $col_b) = ab($a);
echo $col_a;
echo $col_b;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.