How to get name from id in array using query?

1.5k Views Asked by At

I had array values as cause

Ex: $cause = $_REQUEST['cause'];

ie., $cause = 2,3,4

How to get that array value cause name from query

My table name is 'cp_cause'

enter image description here

How to get the 2,3,4 cause name from the above table.

My sample query model in thinkphp is

$cause_name = $GLOBALS['db']->getAll("select category from ".DB_PREFIX."category where id = '".$cause."'");

i want the name of labour, health, women

2

There are 2 best solutions below

1
On BEST ANSWER

If I get it right: you get comma separated Ids and want to query this?

SELECT * FROM cp_cause WHERE id IN (2, 3, 4)

PHP:

$cpCauses = $GLOBALS['db']->getAll("select * from cp_cause where id in('".$cause."')");

The result should be a list, containing the matching rows. But we do not know, what your getAll-Method returns!

Example: if result is an array, you can iterate:

foreach($cpCauses as $cause) {
    echo $cause['cause_name'];
}
0
On

You need to create string like '2','3','4' for checking with MySql in clause.

For e.g.

<?php
    $cause = array();
    $cause[] = '2';
    $cause[] = '3';
    $cause[] = '4';
    $sql_where = array(); 
    foreach($cause as $values){
        $sql_where[] = "'".$values."'";
    }
    $sql_where = implode(",",$sql_where);
    $cause_name = $GLOBALS['db']->getAll("select category from ".DB_PREFIX."category where id in '".$sql_where."'");
?>