Save textfield input as comma separated list in php

1k Views Asked by At

I would like to take a textfield input (job) and store it in my database with a comma separated list. This is what I've tried:

public function __saveNewJob($newJob,$jobscopeChosen) {
    $jobId = $this->__getScopeId($jobscopeChosen);
    $jobList = $this->__getJoblist($jobId);

    $jobList_comma = explode(",",array_filter($joblist));
    $jobList_array = array_push($jobList_comma,$newJob);
    $jobList_save = implode(",",$jobList_array);

    $query = "UPDATE xxxx SET jobs='".$jobList_save."' WHERE id='$jobId'";
    $result = mysql_query($query) OR die(mysql_error());

$newJob is the string from my textfield which I'd like to save. $jobscopeChosen is a value from a select box.

The table in the database, named jobs, should be like Designer, Producer, Administration etc.

My idea was to get the comma separated list, explode it to an array, push the new value and implode it again to a string.

My database says Array in my table. I'm desperate. What am I doing wrong? Any ideas?

1

There are 1 best solutions below

0
On

I personally don't like using array_push when PHP has perfectly acceptable language structures built in like [].

You need to implode the correct array, so try this:

$jobList_comma = explode(",", array_filter($joblist));
$jobList_comma[] = $newJob;
$jobList_save = implode(",", $jobList_comma);

If this doesn't work for you, $joblist must be an array (required by explode) rather than a string, you should do a var_dump on it to check its type and contents, then you can work out what is wrong with it and how to fix it. If getJobList() returns an array from a database for example, you dont need to explode it, but you will need to filter out only the data you need and implode that for save.