Solved

Complicated Record Add to DB using PHP

Posted on 2006-06-27
42
251 Views
Last Modified: 2008-02-01
Hi all,
So.. I have a field on a page that through a javascript function now has a list of town_id's in it. Each town id is separated by a comma so a sample would look like (17,25,36). I also have a user_id passed to this page through a POST array (e.g. user id = 15). I want to add records to a table with the above information like this: For the above example, I want to create the following records in the group_table of the database:
User id:         Town id:
15                   17
15                   25
15                   36  

How would I go about creating 3 diferent records like this? I know that some type of loop will be required but have very little idea how to achieve it? Can anyone help?
Cheers,
D
0
Comment
Question by:dereksheahan
  • 21
  • 21
42 Comments
 
LVL 40

Expert Comment

by:RQuadling
ID: 16992361
I assume that town_ids is coming in the $_POST as a string also? If not how is the data getting from the client to PHP?

<?php
if
      (
      isset($_POST['user_id') &&
      (intval($_POST['user_id') > 0) &&
      isset($_POST['town_ids'])
      )
      {
      $i_user_id = intval($_POST['user_id']);
      $a_town_ids = explode(',', $_POST['town_ids']);
      $s_SQL = '';
      foreach($a_town_ids as $i_key => $m_town_id)
            {
            if (intval($m_town_id) > 0)
                  {
                  $i_town_id = intval($m_town_id);
                  $s_SQL .= "INSERT INTO group_table(User_ID, Town_ID) VALUES({$i_user_id}, {$i_town_id});"
                  }
            }
      // Connect to your DB.
      mysql_pconnect($server, $username, $password) or die('Cannot connect : ' . mysql_errno() . ':' . mysql_error());
      $r_results = mysql_query($s_SQL) or die('Cannot execute : ' . mysql_errno() . ':' . mysql_error());
      if (mysql_affected_rows($r_results) !== count($a_town_ids))
            {
            // Something didn't go quite to plan.
            }
      else
            {
            // All is well.
            }
      }
?>
0
 

Author Comment

by:dereksheahan
ID: 16992604
Hi RQuadling,
Thanks for your swift response. No the town_id's I gettting from the page in question through a javascript function. Only the user id is being passed through the $_POST to the page. How will I alter your above code to cater for this?  Through the javascript function the result is stored in the town id's are put "activityId" textbox.
Cheers,
D
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 16992750
In my code, where you see $_POST['town_ids'] replace this with $_POST['activityID']

That should do the same.

If you want to test this first, comment out the mysql_xxx calls and add ...

echo $s_SQL just above the // Connect comment, but beneath the closing } ...

e.g.

<?php
      if
            (
            isset($_POST['user_id') &&
            (intval($_POST['user_id') > 0) &&
            isset($_POST['activityID'])
            )
            {
            $i_user_id = intval($_POST['user_id']);
            $a_town_ids = explode(',', $_POST['activityID']);
            $s_SQL = '';
            foreach($a_town_ids as $i_key => $m_town_id)
                  {
                  if (intval($m_town_id) > 0)
                        {
                        $i_town_id = intval($m_town_id);
                        $s_SQL .= "INSERT INTO group_table(User_ID, Town_ID) VALUES({$i_user_id}, {$i_town_id});\n"
                        }
                  }

            echo nl2br($s_SQL);
            // Connect to your DB.
            /*
            $r_conn = mysql_pconnect($server, $username, $password) or die('Cannot connect : ' . mysql_errno() . ':' . mysql_error());
            $r_results = mysql_query($s_SQL) or die('Cannot execute : ' . mysql_errno() . ':' . mysql_error());
            if (mysql_affected_rows($r_results) !== count($a_town_ids))
                  {
                  // Something didn't go quite to plan.
                  }
            else
                  {
                  // All is well.
                  }*/
            }
?>

And a small fix on the mysql_pconnect(). Forgot to assign the connection resource.
0
 

Author Comment

by:dereksheahan
ID: 16999352
Hi RQuadling,
Thanks, I've been playing around with that for a few hours but can't get it working yet. I've changed a few of the names of the variables and I think corrected an error in the INSERT INTO statement (changed from i_town_id to m_town_id??) I've tested the posted variable "user_id" and it posts to the page correctly alright. When I leave out this looping part of the script the page works fine but now it just returns blank. Any suggestions as to where I might be going wrong with it? I'll post the complete page just in case its got anything to do with that. Also, do I need to include the line in your code "$r_conn = ... " as I already have a connection for the DB defined.
Thanks so much,
D

<?php require_once('../Connections/Database_test.php'); ?>
<?php echo $_POST['user_id'] ?>
<?php


     if
          (
          isset($_POST['user_id') &&
          (intval($_POST['user_id') > 0) &&
          isset($_POST['activityId'])
          )
          {
          $i_user_id = intval($_POST['user_id']);
          $a_town_ids = explode(',', $_POST['activityId']);
          $s_SQL = '';
          foreach($a_town_ids as $i_key => $m_town_id)
               {
               if (intval($m_town_id) > 0)
                    {
                    $i_town_id = intval($m_town_id);
                    $s_SQL .= "INSERT INTO group_per_table(group_mem_record_id, group_mem_town_id) VALUES({$i_user_id}, {$m_town_id});\n"
                    }
               }

          echo nl2br($s_SQL);
         
              // Connect to your DB.
          /*
          $r_conn = mysql_pconnect($server, $username, $password) or die('Cannot connect : ' . mysql_errno() . ':' . mysql_error());
          $r_results = mysql_query($s_SQL) or die('Cannot execute : ' . mysql_errno() . ':' . mysql_error());
          if (mysql_affected_rows($r_results) !== count($a_town_ids))
               {
               // Something didn't go quite to plan.
               }
          else
               {
               // All is well.
               }*/
          }
?>
<?php
mysql_select_db($database_Database_test, $Database_test);
$query_rscotown = "SELECT county_table.c_county_id, county_table.c_county_name, town_table.t_town_id, town_table.t_town_name, town_table.t_county_id FROM county_table, town_table WHERE town_table.t_county_id = county_table.c_county_id";
$rscotown = mysql_query($query_rscotown, $Database_test) or die(mysql_error());
$row_rscotown = mysql_fetch_assoc($rscotown);
$totalRows_rscotown = mysql_num_rows($rscotown);
?><!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>
<style type="text/css">
<!--
#Chosen {
      position:absolute;
      left:382px;
      top:18px;
      width:181px;
      height:88px;
      z-index:1;
}
-->
</style>
<script language="javascript" type="text/javascript">
var activities = new Array() //Make sure this is outside of any functions!!
function addActivity(select){
var div;
var addIt = true;
if(select!=undefined){
value = select.value.split(':');

for(var x in activities){
     if(activities[x][0]==value[0]){
          addIt = false;
          }
     }
if(addIt==true){
     activities.splice(activities.length,0,new Array());
     activities[activities.length - 1][0] = value[0];
     activities[activities.length - 1][1] = value[1];
     }
}
document.form1.activityId.value = ''
document.getElementById('Chosen').innerHTML = ''

for(var x in activities){
div = '<div id="' + activities[x][0] + '" ondblclick="removeActivity(this.id)">' + activities[x][1] + '</div>';
   if(x>0){
      document.form1.activityId.value = document.form1.activityId.value + ',' + activities[x][0];
      document.getElementById('Chosen').innerHTML = document.getElementById('Chosen').innerHTML + div;
      }
   else{
      document.form1.activityId.value = activities[x][0];
      document.getElementById('Chosen').innerHTML = div;
      }
   }

}
function removeActivity(id){
for(var x in activities){
    if(activities[x][0]==id){
       activities.splice(x,1);
       }
    }
addActivity();
}
function clearAll(){
activities.splice(0,activities.length);
document.getElementById('Chosen').innerHTML = '';
document.form1.activityId.value = '';
}

</script>
</head>

<body>
<div id="Chosen"></div>
<form id="form1" name="form1" method="post" action="">
  <p>
    <select name="County" id="County" onchange="TCN_reload(this)">
      <option selected="selected">County</option>
    </select>
 </p>
  <p>  
    <select name="Town" size="3" id="Town" onchange="TCN_reload(this)" ondblclick="addActivity(this)">
      <option selected="selected">Town</option>
    </select>
    <script language="JavaScript" type="text/javascript">
TCN_contents=new Array();
TCN_tempArray=new Array();
TCN_counter=0;
function TCN_addContent(str){
      TCN_contents[TCN_counter]=str;
      TCN_counter++;
}
function TCN_split(){
      TCN_arrayValues = new Array();
      for(i=0;i<TCN_contents.length;i++){
            TCN_arrayValues[i]=TCN_contents[i].split(separator);
            TCN_tempArray[0]=TCN_arrayValues;
      }
}
function TCN_makeSelValueGroup(){
      TCN_selValueGroup=new Array();
      var args=TCN_makeSelValueGroup.arguments;
      for(i=0;i<args.length;i++){
            TCN_selValueGroup[i]=args[i];
            TCN_tempArray[i]=new Array();
      }
}
function TCN_makeComboGroup(){
      TCN_comboGroup=new Array();
      var args=TCN_makeComboGroup.arguments;
      for(i=0;i<args.length;i++) TCN_comboGroup[i]=findObj(args[i]);
}
function TCN_setDefault(){
      for (i=TCN_selValueGroup.length-1;i>=0;i--){
            if(TCN_selValueGroup[i]!=""){
                  for(j=0;j<TCN_contents.length;j++){
                        if(TCN_arrayValues[j][(i*2)+1]==TCN_selValueGroup[i]){
                              for(k=i;k>=0;k--){
                                    if(TCN_selValueGroup[k]=="") TCN_selValueGroup[k]=TCN_arrayValues[j][(k*2)+1];
                              }
                        }
                  }
            }
      }
}
function TCN_loadMenu(daIndex){
      var selectionMade=false;
      daArray=TCN_tempArray[daIndex];
      TCN_comboGroup[daIndex].options.length=0;
      for(i=0;i<daArray.length;i++){
            existe=false;
            for(j=0;j<TCN_comboGroup[daIndex].options.length;j++){
                  if(daArray[i][(daIndex*2)+1]==TCN_comboGroup[daIndex].options[j].value) existe=true;
            }
            if(existe==false){
                  lastValue=TCN_comboGroup[daIndex].options.length;
                  TCN_comboGroup[daIndex].options[TCN_comboGroup[daIndex].options.length]=new Option(daArray[i][daIndex*2],daArray[i][(daIndex*2)+1]);
                  if(TCN_selValueGroup[daIndex]==TCN_comboGroup[daIndex].options[lastValue].value){
                        TCN_comboGroup[daIndex].options[lastValue].selected=true;
                        selectionMade=true;
                  }
            }
      }
      if(selectionMade==false) TCN_comboGroup[daIndex].options[0].selected=true;
}      
function TCN_reload(from){
      if(!from){
            TCN_split();
            TCN_setDefault();
            TCN_loadMenu(0);
            TCN_reload(TCN_comboGroup[0]);
      }else{
            for(j=0; j<TCN_comboGroup.length; j++){
                  if(TCN_comboGroup[j]==from) index=j+1;
            }
            if(index<TCN_comboGroup.length){
                  TCN_tempArray[index].length=0;
                  for(i=0;i<TCN_comboGroup[index-1].options.length;i++){
                        if(TCN_comboGroup[index-1].options[i].selected==true){
                              for(j=0;j<TCN_tempArray[index-1].length;j++){
                                    if(TCN_comboGroup[index-1].options[i].value==TCN_tempArray[index-1][j][(index*2)-1]) TCN_tempArray[index][TCN_tempArray[index].length]=TCN_tempArray[index-1][j];
                              }
                        }
                  }
            TCN_loadMenu(index);
            TCN_reload(TCN_comboGroup[index]);
            }
      }
}
function findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
TCN_makeSelValueGroup("","");
TCN_makeComboGroup("County","Town");
 var separator="+#+";
<?php do{?>
TCN_addContent("<?php echo $row_rscotown['c_county_name']; ?>+#+<?php echo $row_rscotown['c_county_id']; ?>+#+<?php echo $row_rscotown['t_town_name']; ?>+#+<?php echo $row_rscotown['t_town_id'].":"; ?><?php echo $row_rscotown['t_town_name']; ?>");
<?php } while ($row_rscotown = mysql_fetch_assoc($rscotown)); ?>
TCN_reload();

    </script>
    </p>
      <input name="button" type="button" onclick="clearAll()" value="Clear All!" />
      <input type="button" id="removeButton" style="display: none" value="Remove!" onclick="removeActivity()"/>
  </p>
    <p>
      <input type="text" name="activityId"  id="activityId" value=""/>
    </p>
    <p>
      <label for="Submit">Proceed</label>
      <input type="submit" name="Submit" value="Submit" id="Submit" />
    </p>
    <p>&nbsp;</p>
      <?php echo $user_id ?>
</form>
</body>
</html>
<?php
mysql_free_result($rscotown);
?>
0
 

Author Comment

by:dereksheahan
ID: 16999357
Don't worry about all that javascript in the middle of the script, its for a dynamic drop-down and works fine :)
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 16999388
Don't use m_town_id.

This contains potentially unknown and damaging data.

That is why I first convert it to an int and make sure it is NOT zero.

if (intval($m_town_id) > 0) // Is the supplied data an integer greater than 0.
                    {
                    $i_town_id = intval($m_town_id); // Get the ID.
                    $s_SQL .= "INSERT INTO group_per_table(group_mem_record_id, group_mem_town_id) VALUES({$i_user_id}, {$i_town_id});\n"
                    }

If $m_town_id =

1);DELETE * FROM group_per_table;--

You'd be screwed.

ALWAYS use sanatized data.

Intval returns the integer value. It does not ALTER the value for later use!!!!!!! VERY IMPORTANT.

0
 
LVL 40

Expert Comment

by:RQuadling
ID: 16999395
Use ...

<?php
echo '<pre>' . var_export($_POST, True) . '</pre>';
?>

As the script.

What output? This will tell you what you have to use.
0
 

Author Comment

by:dereksheahan
ID: 16999441
Hi,
if I use the above instead of the script it prints the array that is send to the page:
array (
  'user_id' => '3',
  'Submit' => 'Submit',
)

I'm not the best at php but are we allowed to use the POST method for data that hasn't been sent to the page but instead has been created on that page using Javascript. I've encountered this problem before using Paypal and first had to re-send the form to itself in order to use the $_POST['activityId'] in this situation?
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 16999978
As you can see, the script did NOT receive anything to do with the towns.

Why are you using a JS function to populate the field? Surely the user has to select them?
0
 

Author Comment

by:dereksheahan
ID: 17000489
Hi,
I tried to explain that in my original post but I should have been clearer. The page is set up in such a way that a list box contains all of the towns in it. When the user double clicks on a town, the id is passed into another box ("activityId") and the name of the town is passed to the div tag "Chosen". So once the user has finished selecting their towns the box activityId will look something like (21,15,23). I needed to use JS so that the user could add and remove towns as they please. Is there an easy way of using your code by setting the form action to PHP_SELF and then get the activtiyId from the POST array?
Thanks,
D
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 17000578
Your code is not sending activityID to PHP, so PHP can't get it!

Have you got a URL?


For each town add a hidden input field and set the value to the id when they click the town.

<input type="hidden" id="hidden_xxx" name="activityID[]" value="">

xxx is the ID of the town.

When the town is clicked, you will need to know what the ID is (you already do that).

Then

eval("document.getElementById('hidden_' + town_id).value = town_id;");

If the town is unselected ...

eval("document.getElementById('hidden_' + town_id).value = '';");

Watch out for " and ' in that. Cut and Paste rather than retype.

Once you've done that, use the

<?php
echo '<pre>' . var_export($_POST, True) . '</pre>';
?>

code to see that is sent to you.
0
 

Author Comment

by:dereksheahan
ID: 17000695
Hi,
I already have this textbox where the id's are sent:
<input type="text" name="activityId"  id="activityId" value=""/>
Will I alter this one or create a new one like you suggest above?
D
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 17000714
Nope. That should be OK. As long as it exists between the <form>...</form> tags it should be sent.
<input type="text" name="activityId"  id="activityId" value="" />

You need to put the space before /
0
 

Author Comment

by:dereksheahan
ID: 17000762
>>>For each town add a hidden input field and set the value to the id when they click the town.

<input type="hidden" id="hidden_xxx" name="activityID[]" value="">

I'm not sure I understand fully. How do I get the town_id in there to PHP? As I said after selection this text-box is in the form "23,45,48". How would I create one hidden box for each id or is it necessary?
D
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 17000824
ARGH!!!!

You have forms. You have an action. If the action is a PHP script, then the PHP script will get whatever data the form has in it, either in $_GET if the method was GET or in $_POST if the method was POST.

That's it.

By using a PHP script of ...

<?php
echo '<pre>' . var_export($_POST, True) . '</pre>';
?>

You can see what the HTML form is generating BEFORE you have to write any PHP code to deal with the data.

NO MATTER WHAT YOU WANT TO DO IN PHP, THE DATA HAS TO COME FROM THE FORM!!!!!!

PHP ONLY exists on the server. It hasn't a clue what the user is doing in their browser, nor does it care. Not its job.

So, for the time being, forget PHP and use the little script I've shown above.

Until that has the correct data in it, PHP can do nothing.

Get your form and JS right.



The input name of something[] will create an array in the $_POST array in PHP.

So, by having lots of hidden inputs all with the same name but ending in [], you end up with an array in PHP.



You already have javascript to populate one field. But that field NEVER arrives at PHP's end. You are doing something wrong!!!

Have you got a URL I can look at.
0
 

Author Comment

by:dereksheahan
ID: 17000843
Okay I understand whast you're saying. I have it on the local server but I'll put a version on the web server now. Give me 5 mins... :)
0
 

Author Comment

by:dereksheahan
ID: 17000915
Okay, have a look at this so and I think you'll have a better idea what I'm up to: http://www.reachateacher.ie/Registration/reg6backuplive.php
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 17000968
Personally, I would use a multiple select.

Anyway, can you add the action so I can see what is being sent to PHP.

0
 

Author Comment

by:dereksheahan
ID: 17001043
Hi,
So here's what I've done:
I've added the hidden field like so to the end of the form: <input type="hidden" id="hidden_" name="activityId[]" value="">

To the remove function I've changed to:
function removeActivity(id){
eval("document.getElementById('hidden_' + town_id).value = '';");
for(var x in activities){
    if(activities[x][0]==id){
       activities.splice(x,1);
       }
    }

And similarly to the add function in the JS. The page still returns blank though. Am I on the right track or gone completely off??
Thanks,
D
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 17001117
You are driving me nuts!!!!

What I don't understand is you've managed to create so much JS and all I want is to see what that form generates so I can supply PHP code to work with the data!!!!

Whatever you are doing in JS is NOT working as there is NO list of town ids in the data being sent to PHP.

So, you've ___GOT___ to get that working first.

BEFORE EVERYTHING ELSE!!!

No data in = no data out.

0
 

Author Comment

by:dereksheahan
ID: 17001130
Sorry RQuadling,
I still had your full looping php part in there and it was causing the page to come up blank. Without it and just the <?php
echo '<pre>' . var_export($_POST, True) . '</pre>';
?>

it gives the following error when I try to add a town:

error "town_id" is undefined.
The only place I'm getting the town_id from is from the recordset :  $row_rscotown['t_town_id']
How do I integrate this into the JS line: eval("document.getElementById('hidden_' + town_id).value = '';");

Thanks so much,
D
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 40

Expert Comment

by:RQuadling
ID: 17001178
"Thanks for your swift response. No the town_id's I gettting from the page in question through a javascript function. Only the user id is being passed through the $_POST to the page. How will I alter your above code to cater for this?  Through the javascript function the result is stored in the town id's are put "activityId" textbox."

The textbox activityId is NOT getting populated correctly.

0
 
LVL 40

Expert Comment

by:RQuadling
ID: 17001190
ARGH!

From this, would I be right in thinking you didn't write the JS code either?
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 17001203
Whatever.

The form has no action.

Pressing submit will do fuck all.
0
 

Author Comment

by:dereksheahan
ID: 17001207
Okay,
have you any idea what might be going wrong with it? When I try to POST the result and recieve it on another page it works fine.
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 17001230
What page?

<form action='' ...>

no action. Pressing submit goes nowhere.

WHERE DO YOU WANT IT TO GO TO!!!!!

THIS IS HTML FORMS 101!

0
 

Author Comment

by:dereksheahan
ID: 17001263
Sorry,
I've adapted this script from a page written previously for a very similar page on the site we're working on. Yes, you are correct I didn't write the script and I'm sorry you've been driven around the bend with my lack of knowledge on the subject. I am aware that the form has no action as of yet, but in a test for this page I did enter an action and posted the information from this text-box and it did print on the other page.
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 17001332
Right.

I just took your source.

Added an action to point to itself and add the following PHP code ...

<?php
$s_vars = '<pre>Get = ' . var_export($_GET, True) . "<br />Post = " . var_export($_POST, True) . '</pre>';

echo <<< END_HTML
Here is all your source....nearly...
    <label for="Submit">Proceed</label>
      <input type="submit" name="Submit" value="Submit" id="Submit" />
    </p>
    <p>&nbsp;</p>
      </form>
$s_vars;
</body>
</html>
END_HTML;
?>

and saved that as Q_21900546.php

WHen I run it I get this at the bottom ...

Get = array (
)
Post = array (
)


I fill in some data and I get ...

Get = array (
)
Post = array (
  'County' => '4',
  'Town' => '7:Waterford City',
  'activityId' => '3,7',
  'Submit' => 'Submit',
)

So, the activityId is being sent.

But there is no user id.

Where is this in the form?
0
 

Author Comment

by:dereksheahan
ID: 17001438
Sorry, I had it running on the local server but not on the web server .Try it from this link and all of this works fine.
http://www.reachateacher.ie/Registration/regpost.php
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 17001513
Right. So now we have user_id and activityId.

Back to my FIRST POST!!!!!

<?php
if
     (
     isset($_POST['user_id') &&
     (intval($_POST['user_id') > 0) &&
     isset($_POST['activityId'])
     )
     {
     $i_user_id = intval($_POST['user_id']);
     $a_activity_ids = explode(',', $_POST['activityId']);
     $s_SQL = '';
     foreach($a_activity_ids as $i_key => $m_activity_id)
          {
          if (intval($m_activity_id) > 0)
               {
               $i_activity_id = intval($m_activity_id);
               $s_SQL .= "INSERT INTO group_table(User_ID, Town_ID) VALUES({$i_user_id}, {$i_activity_id});"
               }
          }
     // Connect to your DB.
     mysql_pconnect($server, $username, $password) or die('Cannot connect : ' . mysql_errno() . ':' . mysql_error());
     $r_results = mysql_query($s_SQL) or die('Cannot execute : ' . mysql_errno() . ':' . mysql_error());
     if (mysql_affected_rows($r_results) !== count($a_town_ids))
          {
          // Something didn't go quite to plan.
          }
     else
          {
          // All is well.
          }
     echo 'Executed:<br />' . str_replace(';', ';<br />', $s_SQL);
     }
?>
0
 

Author Comment

by:dereksheahan
ID: 17001622
Hi,
So.. I've re-entered your above statement and made the required changes for the database name etc. I have the require_once statement for the database at the top of the page so how much of your connection data should I leave out (just the first line?)

 mysql_pconnect($server, $username, $password) or die('Cannot connect : ' . mysql_errno() . ':' . mysql_error());
     $r_results = mysql_query($s_SQL) or die('Cannot execute : ' . mysql_errno() . ':' . mysql_error());
     if (mysql_affected_rows($r_results) !== count($a_town_ids))
          {
          // Something didn't go quite to plan.
          }
     else
          {
          // All is well.
          }
     echo 'Executed:<br />' . str_replace(';', ';<br />', $s_SQL);
     }

When I load the page it comes up blank. Here is the full code I'm now using for the page to make sure we're looking at the same thing.

Thanks for your patience,
D

<?php require_once('../Connections/Database_test.php'); ?>

<?php
echo '<pre>' . var_export($_POST, True) . '</pre>';
?>
<?php
if
     (
     isset($_POST['user_id') &&
     (intval($_POST['user_id') > 0) &&
     isset($_POST['activityId'])
     )
     {
     $i_user_id = intval($_POST['user_id']);
     $a_activity_ids = explode(',', $_POST['activityId']);
     $s_SQL = '';
     foreach($a_activity_ids as $i_key => $m_activity_id)
          {
          if (intval($m_activity_id) > 0)
               {
               $i_activity_id = intval($m_activity_id);
               $s_SQL .= "INSERT INTO group_per_table(group_mem_record, group_mem_town_id) VALUES({$i_user_id}, {$i_activity_id});"
               }
          }
     // Connect to your DB.
     mysql_pconnect($server, $username, $password) or die('Cannot connect : ' . mysql_errno() . ':' . mysql_error());
     $r_results = mysql_query($s_SQL) or die('Cannot execute : ' . mysql_errno() . ':' . mysql_error());
     if (mysql_affected_rows($r_results) !== count($a_town_ids))
          {
          // Something didn't go quite to plan.
          }
     else
          {
          // All is well.
          }
     echo 'Executed:<br />' . str_replace(';', ';<br />', $s_SQL);
     }
?>
<?php
mysql_select_db($database_Database_test, $Database_test);
$query_rscotown = "SELECT county_table.c_county_id, county_table.c_county_name, town_table.t_town_id, town_table.t_town_name, town_table.t_county_id FROM county_table, town_table WHERE town_table.t_county_id = county_table.c_county_id";
$rscotown = mysql_query($query_rscotown, $Database_test) or die(mysql_error());
$row_rscotown = mysql_fetch_assoc($rscotown);
$totalRows_rscotown = mysql_num_rows($rscotown);
?><!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>
<style type="text/css">
<!--
#Chosen {
      position:absolute;
      left:382px;
      top:18px;
      width:181px;
      height:88px;
      z-index:1;
}
-->
</style>
<script language="javascript" type="text/javascript">
var activities = new Array() //Make sure this is outside of any functions!!
function addActivity(select){
var div;
var addIt = true;
if(select!=undefined){
value = select.value.split(':');

for(var x in activities){
     if(activities[x][0]==value[0]){
          addIt = false;
          }
     }
if(addIt==true){
     activities.splice(activities.length,0,new Array());
     activities[activities.length - 1][0] = value[0];
     activities[activities.length - 1][1] = value[1];
     }
}
document.form1.activityId.value = ''
document.getElementById('Chosen').innerHTML = ''

for(var x in activities){
div = '<div id="' + activities[x][0] + '" ondblclick="removeActivity(this.id)">' + activities[x][1] + '</div>';
   if(x>0){
      document.form1.activityId.value = document.form1.activityId.value + ',' + activities[x][0];
      document.getElementById('Chosen').innerHTML = document.getElementById('Chosen').innerHTML + div;
      }
   else{
      document.form1.activityId.value = activities[x][0];
      document.getElementById('Chosen').innerHTML = div;
      }
   }

}
function removeActivity(id){
for(var x in activities){
    if(activities[x][0]==id){
       activities.splice(x,1);
       }
    }
addActivity();
}
function clearAll(){
activities.splice(0,activities.length);
document.getElementById('Chosen').innerHTML = '';
document.form1.activityId.value = '';
}

</script>
</head>

<body>
<div id="Chosen"></div>
<form id="form1" name="form1" method="post" action="<?php echo $PHP_SELF;?>">
  <p>
    <select name="County" id="County" onchange="TCN_reload(this)">
      <option selected="selected">County</option>
    </select>
 </p>
  <p>  
    <select name="Town" size="3" id="Town" onchange="TCN_reload(this)" ondblclick="addActivity(this)">
      <option selected="selected">Town</option>
    </select>
    <script language="JavaScript" type="text/javascript">
TCN_contents=new Array();
TCN_tempArray=new Array();
TCN_counter=0;
function TCN_addContent(str){
      TCN_contents[TCN_counter]=str;
      TCN_counter++;
}
function TCN_split(){
      TCN_arrayValues = new Array();
      for(i=0;i<TCN_contents.length;i++){
            TCN_arrayValues[i]=TCN_contents[i].split(separator);
            TCN_tempArray[0]=TCN_arrayValues;
      }
}
function TCN_makeSelValueGroup(){
      TCN_selValueGroup=new Array();
      var args=TCN_makeSelValueGroup.arguments;
      for(i=0;i<args.length;i++){
            TCN_selValueGroup[i]=args[i];
            TCN_tempArray[i]=new Array();
      }
}
function TCN_makeComboGroup(){
      TCN_comboGroup=new Array();
      var args=TCN_makeComboGroup.arguments;
      for(i=0;i<args.length;i++) TCN_comboGroup[i]=findObj(args[i]);
}
function TCN_setDefault(){
      for (i=TCN_selValueGroup.length-1;i>=0;i--){
            if(TCN_selValueGroup[i]!=""){
                  for(j=0;j<TCN_contents.length;j++){
                        if(TCN_arrayValues[j][(i*2)+1]==TCN_selValueGroup[i]){
                              for(k=i;k>=0;k--){
                                    if(TCN_selValueGroup[k]=="") TCN_selValueGroup[k]=TCN_arrayValues[j][(k*2)+1];
                              }
                        }
                  }
            }
      }
}
function TCN_loadMenu(daIndex){
      var selectionMade=false;
      daArray=TCN_tempArray[daIndex];
      TCN_comboGroup[daIndex].options.length=0;
      for(i=0;i<daArray.length;i++){
            existe=false;
            for(j=0;j<TCN_comboGroup[daIndex].options.length;j++){
                  if(daArray[i][(daIndex*2)+1]==TCN_comboGroup[daIndex].options[j].value) existe=true;
            }
            if(existe==false){
                  lastValue=TCN_comboGroup[daIndex].options.length;
                  TCN_comboGroup[daIndex].options[TCN_comboGroup[daIndex].options.length]=new Option(daArray[i][daIndex*2],daArray[i][(daIndex*2)+1]);
                  if(TCN_selValueGroup[daIndex]==TCN_comboGroup[daIndex].options[lastValue].value){
                        TCN_comboGroup[daIndex].options[lastValue].selected=true;
                        selectionMade=true;
                  }
            }
      }
      if(selectionMade==false) TCN_comboGroup[daIndex].options[0].selected=true;
}      
function TCN_reload(from){
      if(!from){
            TCN_split();
            TCN_setDefault();
            TCN_loadMenu(0);
            TCN_reload(TCN_comboGroup[0]);
      }else{
            for(j=0; j<TCN_comboGroup.length; j++){
                  if(TCN_comboGroup[j]==from) index=j+1;
            }
            if(index<TCN_comboGroup.length){
                  TCN_tempArray[index].length=0;
                  for(i=0;i<TCN_comboGroup[index-1].options.length;i++){
                        if(TCN_comboGroup[index-1].options[i].selected==true){
                              for(j=0;j<TCN_tempArray[index-1].length;j++){
                                    if(TCN_comboGroup[index-1].options[i].value==TCN_tempArray[index-1][j][(index*2)-1]) TCN_tempArray[index][TCN_tempArray[index].length]=TCN_tempArray[index-1][j];
                              }
                        }
                  }
            TCN_loadMenu(index);
            TCN_reload(TCN_comboGroup[index]);
            }
      }
}
function findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
TCN_makeSelValueGroup("","");
TCN_makeComboGroup("County","Town");
 var separator="+#+";
<?php do{?>
TCN_addContent("<?php echo $row_rscotown['c_county_name']; ?>+#+<?php echo $row_rscotown['c_county_id']; ?>+#+<?php echo $row_rscotown['t_town_name']; ?>+#+<?php echo $row_rscotown['t_town_id'].":"; ?><?php echo $row_rscotown['t_town_name']; ?>");
<?php } while ($row_rscotown = mysql_fetch_assoc($rscotown)); ?>
TCN_reload();

    </script>
    </p>
      <input name="button" type="button" onclick="clearAll()" value="Clear All!" />
      <input type="button" id="removeButton" style="display: none" value="Remove!" onclick="removeActivity()"/>
  </p>
    <p>
      <input type="text" name="activityId"  id="activityId" value="" />
    </p>
    <p>
      <label for="Submit">Proceed</label>
      <input type="submit" name="Submit" value="Submit" id="Submit" />
        <input type="hidden" name="user_id" value="<?php echo $_POST['user_id'] ?>" />
    </p>
    <p>&nbsp;</p>
      
</form>
</body>
</html>
<?php
mysql_free_result($rscotown);
?>
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 17001736
Blank means no action!!!!!

CHeck the httml in the browser.

$PHP_SELF is not a valid PHP variable.

$_SERVER['PHP_SELF'] is what you want.
0
 

Author Comment

by:dereksheahan
ID: 17001772
Hi,
I've changed it to action="<?php echo $_SERVER['PHP_SELF'];?>">
but the page still comes up blank in the browser. Any other suggestions?

D
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 17007502
That means use the current program to also handle the uploaded data.
0
 

Author Comment

by:dereksheahan
ID: 17008010
Hi RQuadling,
Not sure I understand what it is you want me to change. How can I use the current program to handle the uploaded data?
Thanks,
D
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 17008037
Ok.

In the HTML of the form, what is the URL that is being used.

Ignore the code you've written, examine what the browser receives.
0
 

Author Comment

by:dereksheahan
ID: 17008064
Hi RQuadling,
I have to leave the office until later this evening, I'll let you know as soon as I can.
Thanks,
D
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 17008086
I don't know where you are in the world. I'm in the UK and here 8AM to 4PM Mon-Fri. Maybe I can help you outside of EE? ICQ#1711757
0
 

Author Comment

by:dereksheahan
ID: 17014408
Hi RQuadling,
I'm here in Ireland (your little brother!) so in theory I should be working roughly the same hours as you. I work a few days a week teaching music and play gigs almost all nights of the weekend. I'm new at programming ( a couple of months practice) and find it hard to find the time for it. Anyways, thanks  yeah I have an ICQ account and should be here again early in the morning if you have a few mins.
In response to above:
>>>Ignore the code you've written, examine what the browser receives.

As the variable  coming from the previous page is in the POST array, it is not passed in the URL, so the url for this page just looks like:
http://localhost/....../reg6.php (I have one one the web-server too and it looks the same)
The page opens blank in the browser so I don't get a chance to see what the $_SERVER['PHP_SELF'] action will do to the page. With the php loop part of the code the page works alright as we have established.
I think you are asking me this question because of my poor choice of words in a previous post. I said the page retuns blank when I should have said the page opens blank. Sorry!!! That was probably misleading alright.
My ICQ number is 196779069 and I should be in after 9.30 if you have the time.
Thanks,
D
0
 
LVL 40

Accepted Solution

by:
RQuadling earned 450 total points
ID: 17016725
Load the page and do a view-source to see what the form's action is BEFORE you submit the form.
0
 

Author Comment

by:dereksheahan
ID: 17016739
Source:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=Content-Type content="text/html; charset=windows-1252"></HEAD>
<BODY></BODY></HTML>
0
 

Author Comment

by:dereksheahan
ID: 17017105
The working code for the page:


<?php require_once('../Connections/full.php'); ?>
<?php echo $_POST['user_id'] ?>
<?php
$s_vars = '<pre>Get = ' . var_export($_GET, True) . "<br />Post = " . var_export($_POST, True) . '</pre>';

echo <<< END_HTML
Here is all your source....nearly...
 
    </p>
    <p>&nbsp;</p>
     </form>
$s_vars;
</body>
</html>
END_HTML;
?>
<?php
echo '<pre>' . var_export($_POST, True) . '</pre>';
?>
<?php
if


     (
     isset($_POST['user_id']) &&
     (intval($_POST['user_id']) > 0) &&
     isset($_POST['activityId'])
     )
     {
     $i_user_id = intval($_POST['user_id']);
     $a_activity_ids = explode(',', $_POST['activityId']);
     $s_SQL = '';
    foreach($a_activity_ids as $i_key => $m_activity_id)
          {
          if (intval($m_activity_id) > 0)
               {
               $i_activity_id = intval($m_activity_id);
               $s_SQL = "INSERT INTO group_per_table(group_mem_record_id, group_mem_town_id) VALUES({$i_user_id}, {$i_activity_id});" ;
               $r_results = mysql_query($s_SQL) or die('Cannot execute : ' . mysql_errno() . ':' . mysql_error());
               }
          }


     // Connect to your DB.
     
     
   
     }
?>
<?php
mysql_select_db($database_Database_test, $dbh);
$query_rscotown = "SELECT county_table.c_county_id, county_table.c_county_name, town_table.t_town_id, town_table.t_town_name, town_table.t_county_id FROM county_table, town_table WHERE town_table.t_county_id = county_table.c_county_id";
$rscotown = mysql_query($query_rscotown, $dbh) or die(mysql_error());
$row_rscotown = mysql_fetch_assoc($rscotown);
$totalRows_rscotown = mysql_num_rows($rscotown);
?><!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>
<style type="text/css">
<!--
#Chosen {
      position:absolute;
      left:382px;
      top:18px;
      width:181px;
      height:88px;
      z-index:1;
}
-->
</style>
<script language="javascript" type="text/javascript">
var activities = new Array() //Make sure this is outside of any functions!!
function addActivity(select){
var div;
var addIt = true;
if(select!=undefined){
value = select.value.split(':');

for(var x in activities){
     if(activities[x][0]==value[0]){
          addIt = false;
          }
     }
if(addIt==true){
     activities.splice(activities.length,0,new Array());
     activities[activities.length - 1][0] = value[0];
     activities[activities.length - 1][1] = value[1];
     }
}
document.form1.activityId.value = ''
document.getElementById('Chosen').innerHTML = ''

for(var x in activities){
div = '<div id="' + activities[x][0] + '" ondblclick="removeActivity(this.id)">' + activities[x][1] + '</div>';
   if(x>0){
      document.form1.activityId.value = document.form1.activityId.value + ',' + activities[x][0];
      document.getElementById('Chosen').innerHTML = document.getElementById('Chosen').innerHTML + div;
      }
   else{
      document.form1.activityId.value = activities[x][0];
      document.getElementById('Chosen').innerHTML = div;
      }
   }

}
function removeActivity(id){
for(var x in activities){
    if(activities[x][0]==id){
       activities.splice(x,1);
       }
    }
addActivity();
}
function clearAll(){
activities.splice(0,activities.length);
document.getElementById('Chosen').innerHTML = '';
document.form1.activityId.value = '';
}

</script>
</head>

<body>
<div id="Chosen"></div>
<form id="form1" name="form1" method="post" action="<?php echo $PHP_SELF;?>">
  <p>
    <select name="County" id="County" onchange="TCN_reload(this)">
      <option selected="selected">County</option>
    </select>
 </p>
  <p>  
    <select name="Town" size="3" id="Town" onchange="TCN_reload(this)" ondblclick="addActivity(this)">
      <option selected="selected">Town</option>
    </select>
    <script language="JavaScript" type="text/javascript">
TCN_contents=new Array();
TCN_tempArray=new Array();
TCN_counter=0;
function TCN_addContent(str){
      TCN_contents[TCN_counter]=str;
      TCN_counter++;
}
function TCN_split(){
      TCN_arrayValues = new Array();
      for(i=0;i<TCN_contents.length;i++){
            TCN_arrayValues[i]=TCN_contents[i].split(separator);
            TCN_tempArray[0]=TCN_arrayValues;
      }
}
function TCN_makeSelValueGroup(){
      TCN_selValueGroup=new Array();
      var args=TCN_makeSelValueGroup.arguments;
      for(i=0;i<args.length;i++){
            TCN_selValueGroup[i]=args[i];
            TCN_tempArray[i]=new Array();
      }
}
function TCN_makeComboGroup(){
      TCN_comboGroup=new Array();
      var args=TCN_makeComboGroup.arguments;
      for(i=0;i<args.length;i++) TCN_comboGroup[i]=findObj(args[i]);
}
function TCN_setDefault(){
      for (i=TCN_selValueGroup.length-1;i>=0;i--){
            if(TCN_selValueGroup[i]!=""){
                  for(j=0;j<TCN_contents.length;j++){
                        if(TCN_arrayValues[j][(i*2)+1]==TCN_selValueGroup[i]){
                              for(k=i;k>=0;k--){
                                    if(TCN_selValueGroup[k]=="") TCN_selValueGroup[k]=TCN_arrayValues[j][(k*2)+1];
                              }
                        }
                  }
            }
      }
}
function TCN_loadMenu(daIndex){
      var selectionMade=false;
      daArray=TCN_tempArray[daIndex];
      TCN_comboGroup[daIndex].options.length=0;
      for(i=0;i<daArray.length;i++){
            existe=false;
            for(j=0;j<TCN_comboGroup[daIndex].options.length;j++){
                  if(daArray[i][(daIndex*2)+1]==TCN_comboGroup[daIndex].options[j].value) existe=true;
            }
            if(existe==false){
                  lastValue=TCN_comboGroup[daIndex].options.length;
                  TCN_comboGroup[daIndex].options[TCN_comboGroup[daIndex].options.length]=new Option(daArray[i][daIndex*2],daArray[i][(daIndex*2)+1]);
                  if(TCN_selValueGroup[daIndex]==TCN_comboGroup[daIndex].options[lastValue].value){
                        TCN_comboGroup[daIndex].options[lastValue].selected=true;
                        selectionMade=true;
                  }
            }
      }
      if(selectionMade==false) TCN_comboGroup[daIndex].options[0].selected=true;
}      
function TCN_reload(from){
      if(!from){
            TCN_split();
            TCN_setDefault();
            TCN_loadMenu(0);
            TCN_reload(TCN_comboGroup[0]);
      }else{
            for(j=0; j<TCN_comboGroup.length; j++){
                  if(TCN_comboGroup[j]==from) index=j+1;
            }
            if(index<TCN_comboGroup.length){
                  TCN_tempArray[index].length=0;
                  for(i=0;i<TCN_comboGroup[index-1].options.length;i++){
                        if(TCN_comboGroup[index-1].options[i].selected==true){
                              for(j=0;j<TCN_tempArray[index-1].length;j++){
                                    if(TCN_comboGroup[index-1].options[i].value==TCN_tempArray[index-1][j][(index*2)-1]) TCN_tempArray[index][TCN_tempArray[index].length]=TCN_tempArray[index-1][j];
                              }
                        }
                  }
            TCN_loadMenu(index);
            TCN_reload(TCN_comboGroup[index]);
            }
      }
}
function findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
TCN_makeSelValueGroup("","");
TCN_makeComboGroup("County","Town");
 var separator="+#+";
<?php do{?>
TCN_addContent("<?php echo $row_rscotown['c_county_name']; ?>+#+<?php echo $row_rscotown['c_county_id']; ?>+#+<?php echo $row_rscotown['t_town_name']; ?>+#+<?php echo $row_rscotown['t_town_id'].":"; ?><?php echo $row_rscotown['t_town_name']; ?>");
<?php } while ($row_rscotown = mysql_fetch_assoc($rscotown)); ?>
TCN_reload();

    </script>
    </p>
      <input name="button" type="button" onclick="clearAll()" value="Clear All!" />
      <input type="button" id="removeButton" style="display: none" value="Remove!" onclick="removeActivity()"/>
  </p>
    <p>
      <input type="text" name="activityId"  id="activityId" value=""/>
    </p>
    <p>
      <label for="Submit">Proceed</label>
      <input type="submit" name="Submit" value="Submit" id="Submit" />
        <input type="hidden" name="user_id" value="<?php echo $_POST['user_id'] ?>" />
    </p>
    <p>&nbsp;</p>
      <?php echo $user_id ?>
</form>
</body>
</html>
<?php
mysql_free_result($rscotown);
?>
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article discusses four methods for overlaying images in a container on a web page
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now