0

I have SQL string that suppose to be an array. I'm quite new in php and sql and can't figure out what to do next. Sorry for noob question.

I have query from sql, it's fine. Via mysql_fetch_array I've got cell I needed. It looks like:

[{"id":"X","value":"Y"}{Same structure}{Same structure}]

As much as I understand this is short syntax array I can use. So I started from this:

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$extra_fields = $row['extra_fields']; 
}

For my understanding right now I declared array. But in the real world I didn't.

var_dump shows me a string. What should I do to declare proper array in cases like this?

2
  • You should not use mysql extension anymore cause it's deprecated and gets removed with one of the next PHP releases. Use PDO or mysqli instead. Commented Nov 1, 2013 at 7:13
  • try printing the array with print_r($resultvarofquery); and check whether you are getting the result as array. Commented Nov 1, 2013 at 7:14

2 Answers 2

1

No, your data is a string representation - and I assume that's JSON. You'll need to restore structure from JSON string. In PHP, there is json_decode() for that. For example,

//array(1) { [0]=> array(2) { ["id"]=> string(1) "X" ["value"]=> string(1) "Y" } } 
var_dump(json_decode('[{"id":"X","value":"Y"}]', 1));

-so, you should do:

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) 
{
   $extra_fields[] = json_decode($row['extra_fields'], 1); 
}

Hint: don't use mysql functions, they are deprecated. Use mysqli or PDO instead.

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

Comments

0

Try this.

$data = array(); // create a variable to hold the information
while (($row = mysql_fetch_array($result, MYSQL_ASSOC)) !== false){
  $data[] = $row; 
}

print_r($data); // print result

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.