Sickaaron
Sickaaron

Reputation: 448

array explode and save

I am saving data to a mysql database and these are going to be different options, rather then having them in their own column i am trying to to keep them in the same.

So like surface in mysql would look like : grass,pavement,tarmac - i can get the data to show, but i cannot for some reason get it to save, after either adding a new option or deleting an option.

EDIT - This is now working, i reposted it on here incase others needs help! Thanks

Add:

    $surface = mysql_real_escape_string($_POST['surface']);
    $array = explode(',',$setQuery['Surface']);
    $new_array = implode(',',$array).','.$surface;
    $saveSettings = mysql_query("UPDATE `settings` SET Surface = '$new_array' WHERE id = '1'");

Delete:

    $surface = mysql_real_escape_string($_GET['s']);
    $array = explode(',',$setQuery['Surface']);
    unset($array[$surface]);
    $new_array = implode(',',$array);
    $saveSettings = mysql_query("UPDATE `settings` SET Surface = '$new_array' WHERE id = '1'");

Thanks for any help regards

Upvotes: 0

Views: 1058

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270609

Having used a for loop to build your array into a comma-separated string sent you down the wrong path.

The correct course of action here is to use the PHP built-in implode() to construct the string from your array:

$new_array = implode(",", $array);

I notice also that your add method reads input from $_POST['s'] while the delete method reads from $_GET['s']. Check the consistency between these, if it is an issue.

In either case, however, you must call mysql_real_escape_string() to properly escape it against SQL injection. That is best done just before inserting it into the SQL string, after you have added or deleted from the array and called implode().

// All changes add/del made to array already...
$new_array = implode(",", $array);
$new_array = mysql_real_escape_string($new_array);

$saveSettings = mysql_query("UPDATE `settings` SET Surface = '$new_array' WHERE id = '1'");
// Use error handling methods:
if (!$saveSettings) {
  // Something went wrong
  echo mysql_error();
}

Upvotes: 1

Related Questions