peipei
peipei

Reputation: 1497

Can I put an array inside a Mysql query?

I have an array :

$arrayA = array(1, 2, 3, 4, 5);

Can I put an array like putting a constant number inside a query? like this:

SELECT id as 'ID',
       name as 'NAME',
       '1234' as 'Number'
FROM student 

This above query will generate this:

ID    NAME    Number
1     Lily    1234
2     Sherry  1234
3     Bob     1234
4     Tom     1234
5     Lucy    1234

I want to do something like this:

SELECT id as 'ID',
       name as 'NAME',
       $arrayA as 'Number'
FROM student 

So if i have 5 students, when I do mysql_fetch_array it will automatically generate 1,2,3,4,5 under the Number column.

ID    NAME    Number
1     Lily    1
2     Sherry  2
3     Bob     3
4     Tom     4
5     Lucy    5

Upvotes: 0

Views: 259

Answers (2)

ajreal
ajreal

Reputation: 47321

you can use php to achieve this, such as

$students = array();
$arr = range(1,5);
$idx = 0;
while ( $row = $mysql_result->fetch_assoc())
{
  // return array(1,2,3,4,5)
  // $row['Number'] = $arr;

  // return matched
  // $row['Number'] = $arr[$idx];

  // this is what you can try
  $row['Number'] = ++$idx;
  $students[] = $row; 
}

NOTE: if you intend to use oi, and li tag for displaying,
you can opt this out

Upvotes: 1

Polynomial
Polynomial

Reputation: 28316

No, you can't. Furthermore, you should not do this. It's violating first normal form. Each value should have its own column if there are a fixed number of values. If there are not a fixed number, you should have an intermediate table to handle the many-to-many relationship.

The whole idea behind relational databases is that each column stores one item of data per row. If you need to store more than one item of data, it should be in multiple columns or multiple rows.

See my answer to this question: storing multiple data in one mysql column and retrieval of data individually

Upvotes: 0

Related Questions