Forum Moderators: coopster

Message Too Old, No Replies

Multiple Selections, Arrays, and MySQL

Storring and retrieving arrays from a drop menu with multiple selecion.

         

avatar_bc

7:59 pm on Apr 13, 2007 (gmt 0)

10+ Year Member



OK this place has been great with explaining things that are way over my head, now I could use a boost to get my brain working again. I have a form with a drop down menu with multiple selections. When the form is submitted it shows up in the DB field as "array", as well as the page where I how the form's info. I think I have to set up an array, and loop(?) it, or do I need to implode the array? And how and where would I put these commands on this incredible messy form page. Would someone mind helping me get started?

Here's the form: (please don't make fun of me, I used to a Dreamweaver extension to create the form using PHP, before I decided to try and write this stuff myself. I am re-doing the form but this actually works for now, so I am using it. Also not sure how much of this mess to post so if it's too much, please forgive me.)

if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
$theValue = get_magic_quotes_gpc()? stripslashes($theValue) : $theValue;

$theValue = function_exists("mysql_real_escape_string")? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

switch ($theType) {
case "text":
$theValue = ($theValue!= "")? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue!= "")? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue!= "")? "'" . doubleval($theValue) . "'" : "NULL";
break;
case "date":
$theValue = ($theValue!= "")? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue!= "")? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
$insertSQL = sprintf("INSERT INTO characters (user_id, charactername, image, secretid, `level`, archetype, origin, `primary`, secondary, pool, epic, sg, background, main) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
GetSQLValueString($_POST['user_id'], "int"),
GetSQLValueString($_POST['charactername'], "text"),
GetSQLValueString($_POST['image'], "text"),
GetSQLValueString($_POST['secretid'], "text"),
GetSQLValueString($_POST['level'], "int"),
GetSQLValueString($_POST['archetype'], "text"),
GetSQLValueString($_POST['origin'], "text"),
GetSQLValueString($_POST['primary'], "text"),
GetSQLValueString($_POST['secondary'], "text"),
GetSQLValueString($_POST['pool'], "text"),
GetSQLValueString($_POST['epic'], "text"),
GetSQLValueString($_POST['sg'], "text"),
GetSQLValueString($_POST['background'], "text"),
GetSQLValueString($_POST['main'], "text"));

mysql_select_db($database_Minutemen, $Minutemen);
$Result1 = mysql_query($insertSQL, $Minutemen) or die(mysql_error());

$insertGoTo = "index.php";
if (isset($_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo, '?'))? "&" : "?";
$insertGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $insertGoTo));
}

mysql_select_db($database_Minutemen, $Minutemen);
$query_characters = "SELECT * FROM characters";
$characters = mysql_query($query_characters, $Minutemen) or die(mysql_error());
$row_characters = mysql_fetch_assoc($characters);
$totalRows_characters = mysql_num_rows($characters);
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>

<body>
<form action="<?php echo $editFormAction;?>" method="POST" enctype="multipart/form-data" name="form1">

<tr valign="baseline">
<td align="left" valign="top" nowrap><p>Power Pools </p>
<p>(hold CTRL+LClick to select more than one):</p></td>
<td><select name="pool[]" size="10" multiple="multiple">
<option value="" >n/a</option>
<option value="Concealment" <?php if (!(strcmp("Concealment", ""))) {echo "SELECTED";}?>>Concealment</option>
<option value="Fighting" <?php if (!(strcmp("Fighting", ""))) {echo "SELECTED";}?>>Fighting</option>
<option value="Fitness" <?php if (!(strcmp("Fitness", ""))) {echo "SELECTED";}?>>Fitness</option>
<option value="Flight" <?php if (!(strcmp("Flight", ""))) {echo "SELECTED";}?>>Flight</option>
<option value="Leadership" <?php if (!(strcmp("Leadership", ""))) {echo "SELECTED";}?>>Leadership</option>
<option value="Leaping" <?php if (!(strcmp("Leaping", ""))) {echo "SELECTED";}?>>Leaping</option>
<option value="Medicine" <?php if (!(strcmp("Medicine", ""))) {echo "SELECTED";}?>>Medicine</option>
<option value="Presence" <?php if (!(strcmp("Presence", ""))) {echo "SELECTED";}?>>Presence</option>
<option value="Speed" <?php if (!(strcmp("Speed", ""))) {echo "SELECTED";}?>>Speed</option>
<option value="Teleportation" <?php if (!(strcmp("Teleportation", ""))) {echo "SELECTED";}?>>Teleportation</option>
</select> </td>
</tr>

Here is the display form (I actually did this one myself yayyy me!):
{
$select = $_GET['select'];
}
{

$charquery = "SELECT * FROM characters WHERE charactername='$select'";
$charresult = mysql_query($charquery, $con) or die("query [$charquery] failed: ".mysql_error());
echo '<table cellspacing="5" cellpadding="5" border="0"><tr>';
echo '<td><u>Character Name</u></td>
<td><u> Security Level</u></td>
<td><u>Archetype</u></td>
<td><u>Origin</u></td>
<td><u>Main/Alt</u></td>';
'</tr>';
}
while ($row = mysql_fetch_assoc($charresult))
{
echo '<tr>';
echo '<td>' .$row['charactername'].'</td>';
echo '<td>' .$row['level'].'</td>';
echo '<td>' .$row['archetype'].'</td>';
echo '<td>' .$row['origin'].'</td>';
echo '<td>' .$row['main'].'</td>';
echo '</tr>';

echo '<tr>';
echo '<td><u>Primary Power Set</u></td>
<td><u>Secondary Power Set</u></td>
<td><u>Power Pool Sets</u></td>
<td><u>Epic Power Pool Set</u></td>
<td><td>';
echo '</tr>';

echo '<tr>';
echo '<td>' .$row['primary'].'</td>';
echo '<td>' .$row ['secondary'].'</td>';
echo '<td>' .$row['pool'].'</td>';
echo '<td>' .$row['epic'].'</td>';
echo '</tr>';
echo '<tr>';
echo '<td><u>Background:</u></td>';
echo '</tr>';
echo '<tr>';
echo '<td colspan="4">' .$row['background'].'</td>';
echo '</tr>';
echo '<tr>';
echo '<td colspan="4"> <img src=" '.$row[image].' "/> </td>';
echo '</tr>';
echo '</table>';

}
?>

I'm not real sure where the array would go, or how to set it up. And even worse how to retrieve and display the data. SO far most of the stuff I've read in the manuals about setting up arrays has confused me when it comes to applying it to this particular form.
Thanks so much for any suggestions in advance, this forum has been really great.

eelixduppy

4:31 am on Apr 16, 2007 (gmt 0)



How exactly are you searching items based on the selections in the list? First, however, you should check to even see if it is an array. This is because they may select one object only:

if([url=http://www.php.net/is-array]is_array[/url]($_POST['drop_down_list'])) {
#loop through array and construct your query appropriately
} else {
#construct array as if $_POST['drop_down_list'] is just a string
}
#print results

Hope this points you in the correct direction. Also, for further reference, please only post code related to the problem. Large code dumps are messy and hard to read when only dealing with a specific problem. Thank you :)

avatar_bc

5:13 am on Apr 16, 2007 (gmt 0)

10+ Year Member



Yeah I apologized for posting so much crap in the original post. I had a feeling it was too much, but I wasn't sure what was going to be relevant and what wasn't. So again, my apologies.

So if I'm understanding right, if they only select one item, it would not go in the DB as an array?

eelixduppy

12:29 pm on Apr 16, 2007 (gmt 0)



Yes, that is what my above code is doing. It is checking to see if it is an array so that it can handle it properly, but, if is_array() is false (meaning that it is not an array), then it will be handled as a string(only one was selected).

Depending on how you want the information inserted into the table, the solution will be a little different, however, you could just explode the data and insert it if you want. Something like this:


$insert_data = ([url=http://www.php.net/is-array]is_array[/url]($_POST['pool']))? [url=http://www.php.net/implode]implode[/url](',',$_POST['pool']):$_POST['pool'];

The above uses the Ternary Operator [us.php.net] to basically accomplish the same thing as my last post. Once you have $insert_data set like this, it is a string and can be inserted into the database normally.

And no worries about posting too much code. We've had much, much longer posts before. It more to help you get a better response (for the most part ;))

Good luck!

avatar_bc

7:20 am on Apr 19, 2007 (gmt 0)

10+ Year Member



Sweet, the script worked! And I think I understand arrays a lot better. Here's what I did:

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
$insertSQL = sprintf("INSERT INTO characters (user_id, charactername, image, secretid, `level`, archetype, origin, `primary`, secondary, pool, epic, sg, background, main) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
GetSQLValueString($_POST['user_id'], "int"),
GetSQLValueString($_POST['charactername'], "text"),
GetSQLValueString($_POST['image'], "text"),
GetSQLValueString($_POST['secretid'], "text"),
GetSQLValueString($_POST['level'], "int"),
GetSQLValueString($_POST['archetype'], "text"),
GetSQLValueString($_POST['origin'], "text"),
GetSQLValueString($_POST['primary'], "text"),
GetSQLValueString($_POST['secondary'], "text"),
GetSQLValueString((is_array($_POST['pool']))? implode(',',$_POST['pool']):$_POST['pool'], "text"),
GetSQLValueString($_POST['epic'], "text"),
GetSQLValueString($_POST['sg'], "text"),
GetSQLValueString($_POST['background'], "text"),
GetSQLValueString($_POST['main'], "text"));

It shows up in the DB as comma seperated data (which I'm pretty sure is how I wanted it). Thanks you so much for the help. The cool thing is I can actually understand which command in the line does what now, most of the time.

eelixduppy

10:52 am on Apr 19, 2007 (gmt 0)



I'm glad everything worked out :) Remember, to get back to the original data you have to explode() the string in the database.