I'm attempting to make a button that, based on the selected form/inputs on the page, will bring you to a page called "typeDefine.php?openness=3?conscientiousness=2?extroversion=1?agreeableness=2?neuroticism=1"(the numbers varying based on the selected inputs). However, $selectedNum- the variable that would ideally be containing the $_POST for each input- is returning an error immediately once the page is loaded, saying:
Undefined index
<?php
$typeWords = array("openness", "conscientiousness", "extroversion", "agreeableness", "neuroticism");
$typeLetters = array("o", "c", "e", "a", "n");
$typePath = "";
$correspondingLetters = array("I", "II", "III");
$isFirst = true;
foreach($typeWords as $typeWord)
{
$selectedNum = $_POST[$typeWord];//error here!!!
if(isset($selectedNum))//if got $typeWord in a form
{
$separationChar;
if($isFirst)
{
$separationChar = "?";
$isFirst = false;
}
else
{
$separationChar = "&";
}
$typePath = $typePath . $separationChar . $typeWord . "=" . $selectedNum;//e.g. $typePath = "?openness=3?conscientiousness=2?extroversion=1?agreeableness=2?neuroticism=1" for $_GET method after arriving on next page
}
}
echo 'search for type
<div>';
foreach($typeWords as $typeWord)
{
$typeLetter = substr($typeWord, 0, 1);
echo '<form method = "post" class = "column">';
for($i = 1; $i <= 3; $i++)
{
echo '<input type = "radio" name = "' . $typeWord . '" id = "' . $typeLetter . $i . '"><label for = "' . $typeLetter . $i . '">' . $correspondingLetters[$i - 1] . '</label>';//sets each input name to $typeWord for $_POST above
}
echo '<li class = "textHighlight">' . $typeWord . '</li>
</form>';
}
echo '</div>';
?>
What can I do to fix this error, in turn filling $typePath and making the script correctly bring you to the desired url upon the button's click?
Thanks in advance!
You should perform the isset() test on the $_POST element, not the variable that you set from it.
foreach ($typeWords as $typeWord)
{
if (isset($_POST[$typeWord])) {
$selectedNum = $_POST[$typeWord];
$typePath = $typePath . "?" . $typeWord . "=" . $selectedNum;
}
}
Note that multiple parameters need to be separated with &, ? should only be used at the beginning. There's a built-in function that will create a query string from an array, you can use that:
$typeArray = [];
foreach ($typeWords as $typeWord)
{
if (isset($_POST[$typeWord])) {
$selectedNum = $_POST[$typeWord];
$typeArray[$typeWord] = $selectedNum;
}
}
$typePath = $typePath . "?" . http_build_query($typeArray);
You can also replace the loop with:
$typeArray = array_intersect_key($_POST, array_flip($typeWords));
You execute your code immidiately without a present $_POST array.
You have to wrap your post related code with an if statement like this:
if ($_POST) {
$selectedNum = $_POST[$typeWord];
}
Related
I am working on a custom Joomla module that returns an LDAP directory with the ability to change sort options on the front end using AJAX.
The getAjax function returns the directory just fine if I call it as a string in the default.php template file (bypassing AJAX):
echo $directoryList;
The problem is when I try to return the variable "$content" through ajax, the directory does not show when changing the selector. However, in the helper.php if I change "return $content" to "return $sortOption", AJAX works and returns the selected option for the sort. So I know AJAX is working. Also note that if I change to "return $content.$sortOption", the select option variable is shown but no directory. I think it has something to do with the LDAP not loading properly through AJAX.
Mod_nu_directory.php
// no direct access
defined('_JEXEC') or die;
// Include the syndicate functions only once
require_once( dirname(__FILE__) . '/helper.php' );
// Instantiate global document object
$doc = JFactory::getDocument();
$js = <<<JS
(function ($) {
$(document).on('change', '#sortDir select', function () {
var value = $('#sortDir option:selected').val(),
request = {
'option' : 'com_ajax',
'module' : 'nu_directory',
'data' : value,
'format' : 'raw'
};
$.ajax({
type : 'POST',
data : request,
success: function (response) {
$('.status').html(response);
}
});
return false;
});
})(jQuery)
JS;
$doc->addScriptDeclaration($js);
$dirDepts = $params->get('dirDepts', 'All');
$dirOptions = $params->get('dirOptions');
$directoryList = modNuDirectoryHelper::getAjax($dirDepts);
require( JModuleHelper::getLayoutPath('mod_nu_directory'));
helper.php
class modNuDirectoryHelper {
public static function getAjax($dirDepts) {
//get the sort variable from the select field using ajax:
$input = JFactory::getApplication()->input;
$sortOption = $input->get('data');
//Set our variables
$baseDN = 'CN=Users,DC=site,DC=local';
$adminDN = "admin";
$adminPswd = "P#55WorD";
$ldap_conn = ldap_connect('ldaps://ad.site.local');
$dirFilter = strtolower('(|(department=*' . implode('*)(department=*', $dirDepts) . '*))');
//if "All" categories are selected, dont add a filter, else add a directory filter
(strpos($dirFilter, 'all directory') !== false) ?
$filter = '(&(objectClass=user)(|(memberof=CN=Faculty,CN=Users,DC=site,DC=local)(memberof=CN=Staff,CN=Users,DC=site,DC=local)))' : $filter = '(&(objectClass=user)(|(memberof=CN=Faculty,CN=Users,DC=site,DC=local)(memberof=CN=Staff,CN=Users,DC=site,DC=local))' . $dirFilter . ')';
ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
$ldap_bind = ldap_bind($ldap_conn, $adminDN, $adminPswd);
if (!$ldap_bind) {
return 'Oh no! Unable to connect to the directory :(';
} else {
$attributes = array('displayname', 'mail', 'telephonenumber', 'title', 'department', 'physicalDelivery', 'OfficeName', 'samaccountname', 'wwwhomepage', 'sn', 'givenname');
$result = ldap_search($ldap_conn, $baseDN, $filter, $attributes);
//sort the entries by last name
ldap_sort($ldap_conn, $result, $sortOption);
$entries = ldap_get_entries($ldap_conn, $result);
// let's loop throught the directory
for ($i = 0; $i < $entries["count"]; $i++) {
// define the variables for each iteration within the loop
$userName = $entries[$i]['displayname'][0];
$userTitle = $entries[$i]['title'][0];
$userDept = $entries[$i]['department'][0];
$userPhone = '888-888-8888, ext. ' . $entries[$i]['telephonenumber'][0];
$userOffice = 'Office: ' . $entries[$i]['physicaldeliveryofficename'][0];
//person must have a name, title, and department
if ((!empty($userName)) || (!empty($userTitle)) || (!empty($userDept))) {
$content .= $userName . '<br />'
. $userTitle . '<br />'
. $userDept . '<br />'
. (!empty($userPhone) ? $userPhone : '') . '<br />'
. (!empty($userOffice) ? $userOffice : '') . '<br />'
. '<br />';
}
}
}
return $content;
}
}
default.php
<?php
// No direct access
defined('_JEXEC') or die;
?>
<p>Displaying the following departments:<br />
<?php
foreach ($dirDepts as $dirDept) {
echo '[' . $dirDept . '] ';
}
?>
</p>
<p class="dirOptions">Displaying the following Options:<br />
<?php
foreach ($dirOptions as $dirOption) {
echo '[' . $dirOption . '] ';
}
?>
</p>
<?php
if (in_array('showSort', $dirOptions)) {
?>
<form method="post" id="sortDir">
<select name="sortDir" >
<option value="displayname" selected="selected">First name</option>
<option value="sn">Last name</option>
<option value="department">Department</option>
</select>
</form>
<?php } ?>
<div class="status"></div>
The problem was the $entries array was not being treated as an actual array. I've tested this by substituting the $entry array with a static array and the AJAX callback behaved properly. I since removed the ajax functionality and just echoed the function and works fine. This is not solve why AJAX can't pull the array though.
I am trying to display the data from the database when a dropdown value is selected by the user. There is dropdown for all the registered members. when a admin user selects a registered member name from the drop down it has to populate all the details for that member.
My selection box code is like this
if ($_SESSION['admin_privs'] == "yes" || $_SESSION['edit_all_listings'] == "yes") {
$display .= '<tr><td align="right"><strong>' . $lang['listing_editor_listing_agent'] . ':</strong></td>';
$display .= '<td align="left" class="row_main">';
$agent_select = array();
// find the name of the agent listed as ID in $edit_or_owner
$sql = "SELECT userdb_user_first_name, userdb_user_last_name FROM " . $config['table_prefix'] . "userdb WHERE (userdb_id = $_SESSION[userID])";
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
$recordSet = $conn->Execute($sql);
if ($recordSet === false) {
$misc->log_error($sql);
}
// strip slashes so input appears correctly
$agent_first_name = $misc->make_db_unsafe($recordSet->fields['userdb_user_first_name']);
$agent_last_name = $misc->make_db_unsafe($recordSet->fields['userdb_user_last_name']);
if ($_SESSION['admin_privs'] != "yes")
{
$agent_select[$_SESSION['userID']] = $agent_last_name.','.$agent_first_name;
}
// fill list with names of all agents
$sql = "SELECT userdb_id, userdb_user_first_name, userdb_user_last_name FROM " . $config['table_prefix'] . "userdb where userdb_is_agent = 'yes' or userdb_is_admin = 'yes' ORDER BY userdb_user_last_name,userdb_user_first_name";
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
$recordSet = $conn->Execute($sql);
if ($recordSet === false) {
$misc->log_error($sql);
}
while (!$recordSet->EOF) {
// strip slashes so input appears correctly
$agent_ID = $recordSet->fields['userdb_id'];
$agent_first_name = $misc->make_db_unsafe($recordSet->fields['userdb_user_first_name']);
$agent_last_name = $misc->make_db_unsafe($recordSet->fields['userdb_user_last_name']);
if ($agent_ID == $_SESSION['userID']) {
$agent_select[$agent_ID] = $agent_last_name.','.$agent_first_name;
$selected = $agent_ID;
}else {
$agent_select[$agent_ID] = $agent_last_name.','.$agent_first_name;
}
$recordSet->MoveNext();
}
$display .= $form->selectBox($agent_select, $selected, 'or_owner');
$display .= "</td>";
$display .= '</tr>';
}
I have different function for forms , like this
function selectBox($array, $selected='', $name='', $size=1, $multiple=false, $additional='') {
$res = '';
static $count = 0;
if (is_array($array)) {
if ($name == '') {
$name = 'selectBox' . ++$count;
}
$res .= "<select name=\"$name\" size=\"$size\"" . ($multiple==false ? '' : " multiple=\"multiple\"") . ($additional ? " $additional" : '') . ">\n";
$i = 0;
foreach($array as $key => $value) {
$res .= "<option value=\"$key\"" . ($key == $selected ? " selected=\"selected\"" : '') . ">$value</option>\n";
}
$res .="</select>\n";
}
return $res;
}
function textField($value, $name='', $hidden=false, $size =-1, $length =-1, $additional='') {
$res = '';
static $count = 0;
if ($name == '') {
$name = 'textField' . ++$count;
}
$res .= "<input name=\"$name\" type=\"" . ($hidden ? 'password' : 'text') . "\" value=\"$value\"";
$res .= ($size != -1 ? " size=\"$size\"" : '');
$res .= ($length != -1 ? " maxlength=\"$length\"" : '');
$res .= ($additional ? " $additional" : '') . ">";
return $res;
}
Now i want to display the details of selected user from database, can somebody tell me how can i achieve this :(
thanks
I am not from php but after looking your code its look like your session cause this problem try to debug from session points..
This can best be achieved using AJAX. There is a tutorial on w3schools.com which explains how ajax works. You will simply have to modify the code they supply.
Fundamentally, what you need is:
<SELECT name='name' id='123' onchange='userhint(this.value)'><OPTION value='usercode'...
As your select. The key is putting the onchange call in the SELECT.
You will also need a form goes here
The JS looks like:
function userhint(str)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("changingdiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","myphpfile.php?q="+str,true);
xmlhttp.send();
}
This will replace the content of 'changingdiv' with whatever myphpfile.php returns in response to a get request of q. You are clearly capable of writing that file yourself.
Depending on how you want to do it, the php can either create the complete HTML of the new div or return a json string which you can then use to populate your original areas. For a beginner, the first option is definitely easiest (and is expected by the very basic js above) but the json method will use a fair bit less bandwidth and makes it easier to re-use the same file to feed multiple pages.
here's a question : After entering some data about students, i need to print them in top side of the page (form one). I've managed to print data for single student, but i can't make it to store data in $studenti array, so that it will print data for all students.
here's code that i used(i forgot to mention, i need to use sessions for this):
<?php
session_start();
$_SESSION['aindex'] = $_POST['index'];
$_SESSION['aime']= $_POST['ime'];
$_SESSION['aprosek'] = $_POST['prosek'];
//if ($index != "" && $ime != "" && $prosek !="")
//{
// = $index;
//= $ime;
//=$prosek;
//}
//print ($_SESSION['aindex']);
function inicijalizacija()
{
$studenti = array ();
$ind = $_SESSION['aindex'];
$im = $_SESSION['aime'];
$pr = $_SESSION['aprosek'];
$studenti[$ind]["ime"] = $im;
$studenti[$ind]["prosek"] = $pr;
return $studenti;
}
function dodaj($studenti)
{
$studenti[$_SESSION['aindex']]["ime"] = $_SESSION['aime'];
$studenti[$_SESSION['aindex']]["prosek"] = $_SESSION['aprosek'];
return $studenti;
}
function prikazi($studenti) //ovde u argumentu treba $studenti
{
print ("<h2> Lista Studenata: </h2>");
foreach ($studenti as $ind => $student)
{
if (empty($ind))
continue;
$n = $student["ime"];
$p = $student["prosek"];
print ("Index: " . $ind . " " . "Ime: " . $n . " " . "Prosek: " . $p );
}
print("<hr size ='1'>");
//Forma dodavanja
print (" <form action = 'index.php' method = 'post' >");
print ( " Indeks:  <input type = 'text' name = 'index' />");
print(" </br>");
print ( " Ime:       <input type = 'text' name = 'ime' >");
print(" </br>");
print ( " Prosek : <input type = 'text' name = 'prosek' />");
print(" </br>");
print (" <input type = 'submit' value = 'Dodaj' name = 'Dodaj' />");
}
$studenti = inicijalizacija();
?>
<html>
<head> <title> pokusaj </title> </head>
<body>
<?php
prikazi($studenti);
dodaj($studenti);
?>
</body>
</html>
It seems you're misunderstanding the way PHP works. For efficiency and security, all variables are destroyed when the script has ran and the variables used for this user aren't visible for the script when called by other users.
$_SESSION is an exception; data in $_SESSION will be preserved until the session expires, but it will still only be visible to one unique user (identified by a cookie).
If you want to save the data of a script for use when it is called again (using another session), you'll have to write data to a file or use a database.
PS, your script looks like it will introduce XSS and CSRF vulnerabilities; make sure you won't make the same mistakes that many people before you made.
I have a loop of data that will only echo the loop inside the while function, but if i call/echo the looped data outside the while function, it only runs the 1st loop.
SAMPLE:
$num = mysql_num_rows($queryFromDB);
$i=0;
while($i < $num)
{
$field1= mysql_result($queryFromDB,$i,"field1");
$field2= mysql_result($queryFromDB,$i,"field2");
$bothFields = $field1 . " " . $field2 "\n";
// This will show 2 rows of data
echo $bothFields;
$i++;
// This will only show 1 row of data. How can I pass the looped data to another variable?
echo $bothFields;
}
The output that I wanted to show is:
TITLE/HEADER GOES HERE in the 1st Line
-1st Row of Data from DB
-2nd Row of Data from DB
Here's the actual code:
$num = mysql_num_rows($qWoundAssessment);
$i=0;
while ($i < $num)
{
$wndType = mysql_result($qWoundAssessment,$i,"wndType");
$wndNum = mysql_result($qWoundAssessment,$i,"wndNum");
$wndLocation = mysql_result($qWoundAssessment,$i,"wndLocation");
$wndStage = mysql_result($qWoundAssessment,$i,"wndStage");
$wndL = mysql_result($qWoundAssessment,$i,"wndL");
$wndD = mysql_result($qWoundAssessment,$i,"wndD");
$wndW = mysql_result($qWoundAssessment,$i,"wndW");
$wndAseptic = mysql_result($qWoundAssessment,$i,"wndAseptic");
$wndIrrigate = mysql_result($qWoundAssessment,$i,"wndIrrigate");
$wndIrrigateBox = mysql_result($qWoundAssessment,$i,"wndIrrigateBox");
$wndPat = mysql_result($qWoundAssessment,$i,"wndPat");
$wndCover = mysql_result($qWoundAssessment,$i,"wndCover");
$wndCoverBox = mysql_result($qWoundAssessment,$i,"wndCoverBox");
$wndSecure = mysql_result($qWoundAssessment,$i,"wndSecure");
$wndSecureBox = mysql_result($qWoundAssessment,$i,"wndSecureBox");
$wndQvisit = mysql_result($qWoundAssessment,$i,"wndQvisit");
$wnd = "-" . $wndType . " " . "#" . $wndNum . ", " . "LOCATION " . $wndLocation . ", " . "STAGE " . $wndStage;
$wndSize = "SIZE " . $wndL . "CM" . " X " . $wndW . "CM" . " X " . $wndD;
if($wndAseptic=="1"){$wndAsepticTech = "USING ASEPTIC TECHNIQUE";}
if($wndIrrigate=="1"){$wndIrrigateWith = "IRRIGATE WITH " . $wndIrrigateBox;}
if($wndPat=="1"){$wndPatDry = "PAT DRY";}
if($wndCover=="1"){$wndCoverWith = "COVER WITH " . $wndCoverBox;}
if($wndSecure=="1"){$wndSecureWith = "COVER WITH " . $wndSecureBox;}
if($wndQvisit=="1"){$wndQv = "Q VISIT";}
if(isset($wnd, $wndSize, $wndAsepticTech, $wndIrrigateWith, $wndPatDry, $wndCoverWith, $wndSecureWith, $wndQv)){
$woundCare = implode(", ",array($wnd, $wndSize, $wndAsepticTech, $wndIrrigateWith, $wndPatDry, $wndCoverWith, $wndSecureWith, $wndQv)) . "\n\n ";}
$wndCare .= $woundCare;
$i++;
}
$snWoundCare = "SN TO PROVIDE SKILLED NURSING VISITS FOR WOUND CARE:" . "\n" . $wndCare;
if I echo $wndCare, it shows the "Undefined variable" error with the actual looped data. But if I pass this variable to PDF, it works.
SN TO PROVIDE SKILLED NURSING VISITS FOR WOUND CARE:
-PRESSURE ULCER #1, LOCATION COCCYX, 3, SIZE 2.0CM X 1.5CM X 0.07, USING ASEPTIC TECHNIQUE, IRRIGATE WITH NORMAL SALINE, PAT DRY, COVER WITH AQUACEL AG, COVER WITH MEPILEX BORDER, Q VISIT
-SURGICAL WOUND #2, LOCATION (R) KNEE, , SIZE 29CM X 0CM X 0, USING ASEPTIC TECHNIQUE, IRRIGATE WITH NORMAL SALINE, PAT DRY, COVER WITH AQUACEL AG, COVER WITH MEPILEX BORDER, Q VISIT
================ CODE NOW WORKS!!! HERE's MY FINAL SOLUTION ======================
$num = mysql_num_rows($qWoundAssessment);
$i=0;
$storeMyData = array();
while($i < $num)
{
$wnd= "-" . mysql_result($qWoundAssessment,$i,"wndType") . " #" . mysql_result($qWoundAssessment,$i,"wndNum"). ", LOCATION " . mysql_result($qWoundAssessment,$i,"wndLocation") . ", STAGE " . mysql_result($qWoundAssessment,$i,"wndStage");
$wndSize = "SIZE " . mysql_result($qWoundAssessment,$i,"wndL") . "CM" . " X " . mysql_result($qWoundAssessment,$i,"wndW") . "CM" . " X " . mysql_result($qWoundAssessment,$i,"wndD") . "CM";
if(isset($rowWoundAssessment['wndAseptic'])){$wndAsepticTech = "USING ASEPTIC TECHNIQUE";}
if(isset($rowWoundAssessment['wndIrrigate'])){$wndIrrigateWith = "IRRIGATE WITH " . mysql_result($qWoundAssessment,$i,"wndIrrigateBox");}
if(isset($rowWoundAssessment['wndPat'])){$wndPatDry = "PAT DRY";}
if(isset($rowWoundAssessment['wndCover'])){$wndCoverWith = "COVER WITH " . mysql_result($qWoundAssessment,$i,"wndCoverBox");}
if(isset($rowWoundAssessment['wndSecure'])){$wndSecureWith = "SECURE WITH " . mysql_result($qWoundAssessment,$i,"wndSecureBox");}
if(isset($rowWoundAssessment['wndQvisit'])){$wndQvisit = "Q VISIT";}
$wndCare = implode (", ", array($wnd, $wndSize, $wndAsepticTech, $wndIrrigateWith, $wndPatDry, $wndCoverWith, $wndSecureWith, $wndQvisit)). "\n\n";
// This will show 2 rows of data
$storeMyData[] = $wndCare ; // store current data in array
$i++;
}
/* this will echo your storedData of loop */
foreach($storeMyData as $prevData)
/* or join the data using string concatenation /
$allFinalData2 = "";
/ this will echo your storedData of loop */
foreach($storeMyData as $prevData)
{
$allFinalData2 = $allFinalData2.$prevData ; // keep on concatenating
}
echo "SN TO PROVIDE SKILLED NURSING VISITS FOR WOUND CARE:" . "\n" . $allFinalData2;
thanks to DhruvPathak and Antonio Laguna! You guys are the best! Just made my day! jumps around the room
This should work:
<?php
$wndCare = '';
while ($row = mysql_fetch_assoc($qWoundAssessment)){
$wnd = '-'.$row['wndType'].' #'..$row['wndNum'].', LOCATION '.$row['wndLocation'].', STAGE '.$row['wndStage'];
$wndSize = 'SIZE '.$row['wndL'].'CM X '.$row['wndW'].'CM X '.$row['wndD'];
$wndAsepticTech = ($row['wndAseptic'] == 1) ? 'USING ASEPTIC TECHNIQUE' : '';
$wndIrrigateWith = ($row['wndIrrigate'] == 1) ? 'IRRIGATE WITH '.$row['wndIrrigateBox'] : '';
$wndPatDry = ($row['wndPat'] == 1) ? 'PAT DRY' : '';
$wndCoverWith = ($row['wndCover'] == 1) ? 'COVER WITH'.$row['wndCoverBox'] : '';
$wndSecureWith = ($row['wndSecure'] == 1) ? 'COVER WITH'.$row['wndSecureBox'] : '';
$wndSecureWith = ($row['wndSecure'] == 1) ? 'COVER WITH'.$row['wndSecureBox'] : '';
$wndQvisit = ($row['wndQvisit'] == 1) ? 'Q VISIT' : '';
$wndCare .= implode (", ", array($wnd, $wndSize, $wndAsepticTech, $wndIrrigateWith, $wndPatDry, $wndCoverWith, $wndSecureWith, $wndQv)). '\n\n';
}
$snWoundCare = "SN TO PROVIDE SKILLED NURSING VISITS FOR WOUND CARE:" . "\n" . $wndCare;
?>
The issue I see is that you were testing if all variables where previously setted and this could make strange things as you were stablishing them sometimes and sometimes don't.
I am not sure what you want to do with your data. It seems you want to store
all the data to use it outside the loop, then this is the way to go :
<?php
$num = mysql_num_rows($queryFromDB);
$i=0;
$storeMyData = array();
while($i < $num)
{
$field1= mysql_result($queryFromDB,$i,"field1");
$field2= mysql_result($queryFromDB,$i,"field2");
$bothFields = $field1 . " " . $field2 "\n";
// This will show 2 rows of data
echo $bothFields;
$storeMyData[] = $bothFields ; // store current data in array
$i++;
}
/* this will echo your storedData of loop */
foreach($storeMyData as $prevData)
{
echo $prevData."\n";
}
?>
$allFinalData = implode("",$prevData); // implode will join all the data as string
echo $allFinalData."\n" ;
/* or join the data using string concatenation */
$allFinalData2 = "";
/* this will echo your storedData of loop */
foreach($storeMyData as $prevData)
{
$allFinalData2 = $allFinalData2.$prevData ; // keep on concatenating
}
echo $allFinalData2,"\n";
?>
I am trying to process a form that is dynamically created and therefore varies in length. The while loop seems to work fine. However, the 'if' statement is not; it should only print the startId$i and corId$i if and only if the form's particular text field was filled in. The code is printing a line for every text field on the form, regardless of if it was left empty or not.
$i = 0;
while(!is_null($_POST["startId$i"])){
if(($_POST["startId$i"]) != ""){
echo "startId: " . $_POST["startId$i"] . " ---<br>";
echo "corId: " . $_POST["corId$i"] . " ---<br>";
}
$i++;
}
$i = 0;
while(isset($_POST["startId$i"])){
if( !empty($_POST["startId$i"]) ){
echo "startId: " . $_POST["startId$i"] . " ---<br>";
echo "corId: " . $_POST["corId$i"] . " ---<br>";
}
$i++;
}
Can you manage with fields names ?
If yes, better way is to name inputs with name="startId[0]" and name="corId[0]" and so on...
Then in PHP you just do:
$startIds = $_POST['startId'];
$corIds = $_POST['corId'];
foreach ( $startIds as $k => $startId ) {
if ( !empty($startId) ) {
$corId = $corIds[$k];
echo "startId: " . $startId . " ---<br>";
echo "corId: " . $corId . " ---<br>";
}
}
You should use empty() in this case:
if(!empty($_POST["startId$i"])) {
...
}
I suggest to check the real content of $_POST. You can do that via var_dump($_POST);
You may find out, for example, that the empty fields contain whitespaces. In that case the trim() function may help.
For example:
while(isset($_POST["startId$i"])){
if(trim($_POST["startId$i"])){
echo "startId: " . $_POST["startId$i"] . " ---<br>";
echo "corId: " . $_POST["corId$i"] . " ---<br>";
}
$i++;
}