Hi all,

I'm having trouble getting POST value from dynamically generated txtinput[] and MultiSelect since they form an array. I read so many articles but I get confuse..

a short form of my code is given below..

Pls help me with best way how I can get array values in the form of a string "value1, value2, value3"

Regards... and Thanks.....

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta charset="UTF-8">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>

<script type="text/javascript">
        
$(function(){
       //initially hide the textbox
            $("#other_lang").hide();
            $('#lang').change(function() {
              if($(this).find('option:selected').val() == "Other - specify"){
                $("#other_lang").show();
              }else{
                $("#other_lang").hide();
              }
            });
            $("#other_lang").keyup(function(ev){
                var othersOption = $('#lang').find('option:selected');
                if(othersOption.val() == "Other - specify")
                {
                    ev.preventDefault();
                    //change the selected drop down text
                    $(othersOption).html($("#other_lang").val()); 
                } 
            });
            $('#form_id').submit(function() {
                var othersOption = $('#lang').find('option:selected');
                if(othersOption.val() == "Other - specify")
                {
                    // replace select value with text field value
                    othersOption.val($("#other_lang").val());
                }
            });
        });

	var counter = 1;
	var limit = 3;
	var phonefields = "<input name='phoneno[]' id='phoneno[]' class='phoneno' type='text'/>";
function addInput(divName){
	
	
     if (counter == limit)  {
          alert("Max. " + counter + " Phone numbers only");
     }
     else {
          var newdiv = document.createElement('div');
		  newdiv.innerHTML = phonefields;
          document.getElementById(divName).appendChild(newdiv);
          counter++;
     }
}

</script>

</head>

<body>
<form  class="form" method="post" name="form" action="">
        <label for="langs">Languages:</label><?php dyn_languages() ;?>
        <input id="other_lang" name="other_lang" type="text" placeholder="Other lang" /><br /><br /><br />

        <label for="phoneno[]">Phone No:</label>
        <input id="buttonAsLink" type="button" onClick="addInput('dynamicInput')">         
        <div id="dynamicInput"><input name='phoneno[]' id='phoneno[]' type='text'/></div>
		
        <input name="submit" type="submit" value="Submit" />
</form>

<?php 
//----Dynamic SelectBox for languages
function dyn_languages(){
		$langs = array (1 => 'English', 'French', 'German', 'Russian', 'Spanish', 'Other - specify');
		
		echo "<select size='6' name='lang' id='lang' multiple='multiple'>";
		foreach ($langs as $value) {
			echo (in_array($value,$_POST)) ? '<option value="'.$value.'" selected>'.$value.'</option>\n' : '<option value="'.$value.'">'.$value.'</option>\n';
		} echo '</select>';

}//--END Function* --Dynamic SelectBox for languages

//--- POST Action
if(isset($_POST['submit'])){
		$phoneno = $_POST['phoneno'];
		$langs = $_POST['lang'].",".$_POST['other_lang'];
		
		$sql = "INSERT INTO table(lang, phoneno) VALUES ('$phoneno','$langs')";
		echo "<hr />".$sql; 
}
//--- END POST Action
?>
	
</body>
</html>
Member Avatar for diafol
<label for="phoneno[]">Phone No:</label>
        <input id="buttonAsLink" type="button" onClick="addInput('dynamicInput')">         
        <div id="dynamicInput"><input name='phoneno[]' id='phoneno[]' type='text'/></div>

for attribute relates to an id
ids shouldn't be arrays - name attr OK, but not id

function dyn_languages(){
		$langs = array (1 => 'English', 'French', 'German', 'Russian', 'Spanish', 'Other - specify');
 
		echo "<select size='6' name='lang' id='lang' multiple='multiple'>";
		foreach ($langs as $value) {
			echo (in_array($value,$_POST)) ? '<option value="'.$value.'" selected>'.$value.'</option>\n' : '<option value="'.$value.'">'.$value.'</option>\n';
		} echo '</select>';

Any reason why you base 1ed your array?

in_array($value,$_POST)

This seems a little weak. Any $_POST variable could contain the string - if you entered English into a textbox, for example, it would give a match. Seeing as your select widget is set to multiple, the $_POST array would not 'see' the underlying value in the $_POST array.

$post = (array) $_POST['lang'];
echo (in_array($value,$post)

may be better.

sorry, I'm not much good in PHP yet, so your answer isn't understandbale by me.
if you can rather give me working example code, maybe I'll be able to grasp something

I think what he is saying is you should start off with the basics before going to the advanced. It's obvious your not ready for arrays yet nor are you ready for variable definitions yet. I would strongly suggest following the tizag tutorials and after you have completed them then you will soon realize really quickly what you have done wrong as this is the very basics of PHP.

There is a place between beginner and trained professional, I guess I lie there..

Anyway, I managed to do it with one 2 lines of code...

foreach ($_POST['phoneno'] as $ph) {$phoneno.= $ph.", ";}
foreach ($_POST['lang'] as $lng) {$langs.= $lng.", ";}
Member Avatar for diafol

doesn't that give you a comma at the end of each string?
how about

$ph = implode(", ", $_POST['phoneno']);

etc.

However, you can't trust the post data to be safe, so you should escape all input with a mysql_real_escape_string() or addslashes().
You can do this with array_map() to prevent using a loop.

$ph = implode(", ", array_map('mysql_real_escape_string', $_POST['phoneno));

doesn't that give you a comma at the end of each string?
how about

$ph = implode(", ", $_POST['phoneno']);

etc.

However, you can't trust the post data to be safe, so you should escape all input with a mysql_real_escape_string() or addslashes().
You can do this with array_map() to prevent using a loop.

$ph = implode(", ", array_map('mysql_real_escape_string', $_POST['phoneno));

Also there is a bug in your second code snippet and should be as follows:

$ph = implode(", ", array_map('mysql_real_escape_string', $_POST['phoneno']);

You corrected the missing bracket, but removed one of the ending parentheses.

$ph = implode( ", ", array_map( 'mysql_real_escape_string', $_POST['phoneno'] ) );

You corrected the missing bracket, but removed one of the ending parentheses.

$ph = implode( ", ", array_map( 'mysql_real_escape_string', $_POST['phoneno'] ) );

Well you used double quotes where there should have been single quotes ;)
PHP operates faster with single quotes as it doesn't have to phrase the \n\r and variables inside the quotes.

$ph=implode(', ',array_map('mysql_real_escape_string',$_POST['phoneno']));

Additionally php operates faster if you remove the spacing. Not to be mean or anything just that I don't like to be made a fool of from a mistake. ;)

My intention was not to make a fool of you or to improve the code you corrected. It was simply to correct your flawed correction.

Both your single vs double quotes and the removal of white space arguments are insignificant points. The performance boost gained from using single quotes over double quotes is so trivial any professional developer would focus their time on bottlenecks that actually exist. An approximate ~1% execution difference in a micro benchmark is not enough to base an entire argument on. You'd be better off comparing concatenation methods as these represent a ~30% performance difference, again in a micro benchmark. The real measurable difference between the two quotes is the memory consumption used for parsing variables in double quoted strings vs single quoted strings using concatenation.

There is also no performance benefit to be had by removing whitespace. The only thing you have accomplished is reducing the readability of the code, making every developers job slightly more difficult. PHP does not gain from minifying or packing like javascript does as it does not have to pass it's source files over a network connection. Additionally libraries like APC, IonCube and Zend Encoder strip the whitespace, comments etc. from the cached code anyways.

"Even a fool may be wise after the event." - Homer

However when you add up all of the quotes and spaces that are used within the php code it does make a big difference to the performance because for example, the longer the string php has the process which in the case is the entire file the more memory consumption that will take place. So if for example you have a text file with 2^33 white spaces in it then 32bit php simply couldn't process it because the white spaces would make php crash from a memory overload. The reason being is to strip the white spaces php has to use regex on the file and delete the white spaces however this process does require some doing. If however there are little or no white spaces to be stripped then it will speed up the process. Same applies with the comments that are in the php code. If you remove the comments then php will phrase the code faster too. And believe it or not variable names apply too. If you have shorter variable names then because the text file is shorter there is less memory consumption and in addition when phrasing the variables php only needs to store shorter key's in its indexing system for its variable definitions.

I DO NEED comma, as I'm inputting the whole array as one string, where array fields are concatenated with commas.

And guyz!! don't worry about missing braces etc.. I already said I managed to workout the solution. Ofcourse I have perfectly running code with me..

I just wanted an IDEA, not exact code... so chill!!

Thx anyways for the excellent ideas..

Member Avatar for diafol

Christ guys, get a room why don't you. It was my original mistake, direct it at me. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.