1

i am running a mysql query to return all rows from a temp database, i then need to ammend some of the attributes in those rows so i am trying to return each row to an array so i can then reference the array and amend specific attributes of each row

im just stuck on how to get each row into its own array, im guessing i will need to use a 2d array for this however cannot figure out how to populate it from the mysql query into the 2d array. Im guessing it is something like i have tried below?

    $result_array = array();
while ($row = mysql_fetch_assoc($res2)) {
 $result_array[] = $var;
foreach($row as $key => $var) {
// Insert into array
echo $var;
}

however when trying this i am getting a notice saying:

Notice: Array to string conversion

any help pointing me in the right direction for this would be great

1
  • $result_array[] = $var doesn't make much sense, because $var isn't defined until you've run that inner foreach() loop. Commented Oct 15, 2013 at 17:03

1 Answer 1

2

If I understand what you're asking for, you literally want each row from the SQL query to be a single index in the $result_array array?

If that's the case, you're already getting it with $row - you can add that directly to the array:

$result_array = array();
while ($row = mysql_fetch_assoc($res2)) {
    $result_array[] = $row;
}

You can modify the values inside the array either when you're adding them to the global array, or after:

foreach ($result_array as $index => $row) {
    $result_array[$index]['some_key'] = $row['some_key'] . ' [modified]';
}


Side-note (not answer specific)
I would recommend against using the old, deprecated mysql_ functions and instead favor MySQLi or PDO. Both of these are easy to use, more secure than the older methods and offer a large range of features such as prepared statements.

The above can be written with mysqli like:

if ($result = mysqli_query($connection, $query)) {
    $results = array();
    while ($row = mysqli_fetch_assoc($result)) {
        $results = $row;
    }
    mysqli_free_result($result);
}
Sign up to request clarification or add additional context in comments.

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.