1

in this case, for example,
i have string from array of person_code => 1,2,3
then i want change that string to another string from array of person_nama => name1, name2, name3
i have try with my code :

public function Person_name($person_code)
    {
        $code= explode(',', $person_code);
        $name=array();
        for($i=0; $i<count($code); $i++){
            $sql= Yii::app()->db->createCommand('select nm_person from tbl_person where kd_person="'.$code[$i].'";');
            $name=$sql->queryRow();
        }
        $namearray= implode(',',$name);
        return $namaarray;
    }


but that result is only return the last person name in array,
anyone can help me?? thank you

1
  • 1
    you're overwriting it, $name[] =, push continually, and why not just use a WHERE IN clause, i'm sure Yii already has that somewhere, use the API, that accepts a WHERE IN clause method and also that accepts an array of integers Commented Sep 21, 2016 at 2:22

1 Answer 1

1

I'd just answer this by just using a band-aid solution with just normally pushing the results into the array. Your current code is just overwriting $name.

$name[] = $sql->queryRow();

But.

Don't directly interpolate variables into the query string. Just stop that, you're already using a good framework with useful query builder.

Instead of executing each query for each id, why not use a WHERE IN clause flavor along with the builder.

Much better untested basic idea:

public function Person_name($person_code)
{
    $persons = array();
    $person_code = explode(',', $person_code);

    if(!empty($person_code)) {
        $result = Yii::app()->db->createCommand()
        ->setFetchMode(PDO::FETCH_COLUMN, 0)
        ->select('nm_person')
        ->from('tbl_person')
        ->where(array('IN', 'kd_person', $person_code)
        ->queryAll();

        $persons = implode(', ', $result);
    }

    return $persons;
}

Based on reading the manual

Sign up to request clarification or add additional context in comments.

3 Comments

thank you for response, that is good idea, i have try your code, but any error in Array Helper.php, i think that is because i use Yii 1.xx
@YanuarIhsan oh okay thats why, i've changed it into that version you're using, i'v eedited it
@YanuarIhsan sure glad this helped

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.