1

i have a mysql table

||==========||==========||==========||
||    id    ||   name   ||   age    ||
||==========||==========||==========||
||    1     ||   joe    ||   10     ||
||    2     ||   harry  ||   20     ||
||    3     ||   jane   ||   45     ||
||    4     ||   john   ||   56     ||
||    5     ||   larry  ||   89     ||
||    6     ||   henry  ||   23     ||
||    7     ||   steve  ||   25     ||
||    8     ||   eric   ||   56     ||
||    9     ||   dave   ||   98     ||
||    10    ||   mat    ||   56     ||
||==========||==========||==========||

i need the sql query that would make an associative array from this table and give me values like this

id=>age
1=>10
4=>56

i also need to make all the id's as a variable where there value would be the age like

$1 = 10
$4 = 56

or if i could add a prefix to the variables

$id_1 = 10
$id_4 = 56

thanks in advance

1
  • i think their is no direct approach to generate the array like this, first fetch the records and store the result to array like you need. Commented Nov 9, 2011 at 5:18

3 Answers 3

2

In PHP, mysql_fetch_assoc() takes the result of a query, and returns one row as an associative array. Call it repeatedly to get all rows.

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

Comments

0

if your using php for fetching your data you may use the function mysql_fetch_array example:

while($row = mysql_fetch_assoc($resource))
{
echo $row['name'].'<br>';
}

you may know more about mysql functions for php on this site: http://www.php.net/manual/en/book.mysql.php

Comments

0
$ids = '1, 4';
$sql = "select age from __TABLE__ where id in ( {$ids} )";

$link = mysql_connect('__SERVER__', '__DBUSER__', '__DB_PWD__') or die('connect error');
$db = mysql_select_db('__DBNAME__', $link) or die('db error');

$rs = mysql_query($sql, $link);

$result = array();
while($row = mysql_fetch_assoc($rs))
{
    $result[] = $row;
}
extract(my_result($result));
var_dump($id_1);
var_dump($id_4);
function my_result($result, $prefix = 'id_')
{
    $data = array();
    foreach($result as $k => $v)
    {
        $data[$prefix . $v['id']] = $v['order_no'];
    }
    return $data;
}

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.