Forum Moderators: coopster

Message Too Old, No Replies

Entering multiple keywords into a database

HTML, PHP and MySQL

         

Maynard

3:19 pm on Feb 12, 2004 (gmt 0)

10+ Year Member



Hello,

I want users to select multiple keywords from a dropdown menu and have these keywords entered in to a MySQL database.

eg:
<p>Keyword:</p>
<select name="keyword" multiple>
<option value="agriculture">Agriculture
<option value="aid">Aid
<option value="animals">Animals
</select>

My Keywords field in my MySQL database is TEXT.

The line that processes the Keywords in PHP is:
$keyword = trim(addslashes($keyword));

But only the first selected keyword is being entered and not the others a user may also select.

What am I doing wrong?

Newbie to PHP,
Maynard.

scumm_bar2

3:30 pm on Feb 12, 2004 (gmt 0)

10+ Year Member



A select multiple input is sent to the script as an array. Use foreach() like this:

if ($keyword) {
foreach($keyword as $key) {
// Remove spaces and add slashes
$key = trim(addslashes($key));

// Add to our keyword list, followed by a comma
$key_list .= $key.',';
}
// Strip off the last comma, since we've finished the loop
if ($key_list) {
$key_list = substr($key_list, 0, -1);
}
}

Now insert '$key_list' into the database.

andrewB

3:47 pm on Feb 12, 2004 (gmt 0)

10+ Year Member



It's only entering the first one because you have set the select name as an array like so
<select name="keyword[]" multiple>

then after posting your form the selected words will be in the array $_POST['keyword']
so then you loop over it like so
for ($i=0; $i < count($_POST['keyword']); $i++)
echo $_POST['keyword'][$i];

Maynard

5:02 pm on Feb 12, 2004 (gmt 0)

10+ Year Member



Thanks so much, guys, that was very quick. I will try it out and let you know!

Maynard.

Maynard

5:20 pm on Feb 12, 2004 (gmt 0)

10+ Year Member



It worked! Here's what I used for other peoples' reference:

HTML page:
<p>Keyword:</p>
<select name="keyword[]" size="10" multiple>
<option value="agriculture">Agriculture
<option value="aid">Aid
<option value="animals">Animals
</select>

PHP page:
if ($keyword)
{
foreach($keyword as $key)
{
$key = trim(addslashes($key));
// Add to keyword list and follow by comma
$keywordList .= $key.',';
}

// Strip off the last comma
if ($keywordList)
{
$keywordList = substr($keywordList, 0, -1);
}
}

// Now insert $keywordList into database

Fantastic, thanks again guys!

Maynard.