RipzCurlz RipzCurlz - 3 months ago 13
MySQL Question

Simple UPDATE MySQl table from php array

I am trying to put together a function that does the following:


  1. retrieve a JSON encoded string from a form

  2. decode the string to a php array

  3. loop through the generated php array to get the values for each part of the array so that I can update a MySql table



Here is my function code so far:

public function saveTestimonials() {


$existing_testimonials_update = $this->post('data');

$update_array = json_decode($existing_testimonials_update);

foreach ($update_array as $key => $testimonials) {
foreach($testimonials as $key => $value) {
//echo "$key = $value\n";

}
}

$db = Loader::db();
$sql = "UPDATE testimonials SET name=var, content=var WHERE id=var";
$db->query($sql);

$this->redirect('/dashboard/testimonials/');

}


Here is the array stored in the $update_array variable:

Array
(
[0] => stdClass Object
(
[id] => 1
[name] => Mr. John Doe, Manager, ABC Ltd
[content] => my content 1.
)

[1] => stdClass Object
(
[id] => 2
[name] => Mr. Joe Smith, Manager, ABC Industries
[content] => my content 2.
)

[2] => stdClass Object
(
[id] => 3
[name] => Mr. Mike Smith, Manager, ABC Industries
[content] => my content 3.
)

[3] => stdClass Object
(
[id] => 4
[name] => Ms. Jane Doe, Manager, ABCD Ltd
[content] => my content 4.
)

)


I have got steps 1 and 2 working fine, however I am stuck on step 3.

I still learning PHP and struggle with syntax at times.
I have tried to work this one out on my own and have spent several hours on it, but just can't seem to figure this one out.

Any assistance is very much appreciated.

Answer
foreach ($update_array as $key => $testimonials) {
    $name = mysql_real_escape_string($testimonials->name);
    $content = mysql_real_escape_string($testimonials->content);
    $id = intval($testimonials->id);

    $sql = "UPDATE testimonials SET name='$name', content='$content' WHERE id=$id";
    $result = mysql_query($sql);
    if ($result === FALSE) {
        die(mysql_error());
    }
}