0

Hy I have some problems with php and mysql -> I can't find a good solution for it.

This is my DB:

user_id | meta_key | meta_value
1       | name     | Freddy
1       | phone    | 123
1       | adress   | Elm Street 1428
1       | city     | Springwood

I'm getting datas this way:

$userdata = array (userdata);
$get_user_data = mysql_query("SELECT `meta_value` FROM `table` WHERE `user_id` = $user_id", $link);

while($row=mysql_fetch_array($get_user_data)){
array_push($userdata, $row["meta_value"]);}

What i don't like is: I can only get data this way -> $userdata[1];

How can i get my data that there is a connection between the two rows?

$userdata['name']; (Freddy)

2
  • 1
    Note: The mysql_* functions are deprecated, they will be removed from PHP in future versions and your code will stop working then. You should not write new code using them, use mysqli_* or PDO instead. Commented Jan 9, 2015 at 8:30
  • how would this code look like if i use mysqli? Can i just use mysqli_query and mysqli_fetch_array insted of? Commented Jan 9, 2015 at 11:54

3 Answers 3

1

If you want the meta_key as index in your array, just add the data like this:

// add meta_key to the query
$get_user_data = mysql_query("SELECT `meta_value`,`meta_key` FROM `table` WHERE `user_id` = $user_id", $link);

// use _assoc instead of _array, we don't need the numerical indexes.
while($row=mysql_fetch_assoc($get_user_data)){
  $userdata[$row['meta_key']] = $row['meta_value'];
}

This will result in:

Array(
  'name' => 'Freddy',
  // ...
)
Sign up to request clarification or add additional context in comments.

Comments

0

Use:

while ($row=mysql_fetch_array($get_user_data, MYSQL_ASSOC)) {
    ....
}

or:

while ($row=mysql_fetch_assoc($get_user_data)) {
    ...
}

2 Comments

this is unnessecary, mysql_fetch_array() returns by default an array with numerical and associative indexes.
@GeraldSchneider Indeed, but by using an associative array the numeric values are left out.
0
mysql_fetch_array($get_user_data, MYSQL_ASSOC)

1 Comment

this is unnessecary, mysql_fetch_array() returns by default an array with numerical and associative indexes.

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.