PHP: $_POST["startId$i"]) != "" - php

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++;
}

Related

Undefined variable When values are empty

I have 2 blocks of code....
// 1st block
<div id="a1">
<?php
if (is_array($new_array) || is_object($new_array))
{
foreach ($new_array as $name => $val)
{
echo $name . " : " . $val[0] . " , " . $val[1]. " , " . $val[2];
}
}
unset($new_array);
?>
</div>
2nd block
<div id="a2">
<?php
if (is_array($new_array) || is_object($new_array))
{
foreach ($new_array as $name => $val)
{
echo $name . " : " . $val[0] . " , " . $val[1]. " , " . $val[2];
}
}
unset($new_array);
?>
</div>
Either 1st or 2nd Block will give empty results in a day. Means if Today , 1st block will give empty result & tomorrow 2nd Block will give empty result.... Alternatively....
Issue :
Today, Value is empty for 2nd block , it gave Notice: Undefined variable: new_array error , so I initialized this before 2nd block of code :
$new_array='';
it worked fine.... but tomorrow 2nd block code will give this result :
Warning: Illegal string offset ,
Fatal error: Uncaught Error: Cannot use string offset as an array
So i need to remove this code : $new_array=''; before 2nd block & i need to place before 1st block.....
What about to use if (isset($new_array)) {...} or to initialize it like array, $new_array = [];
You can add isset to other checks, like this:
if (isset($new_array) && (is_array($new_array) || is_object($new_array))) { .... }
More info about isset()
You can use isset() function to check if $new_array is set or not. Edit your code as below
// 1st Block
<div id="a1">
<?php
if(isset($new_array)){
if (is_array($new_array) || is_object($new_array))
{
foreach ($new_array as $name => $val)
{
echo $name . " : " . $val[0] . " , " . $val[1]. " , " . $val[2];
}
}
}
unset($new_array);
?>
</div>
// 2nd Block
<div id="a2">
<?php
if(isset($new_array)){
if (is_array($new_array) || is_object($new_array))
{
foreach ($new_array as $name => $val)
{
echo $name . " : " . $val[0] . " , " . $val[1]. " , " . $val[2];
}
}
}
unset($new_array);
?>
</div>
You are looking for isset()/empty() and perhaps a short if/else.
Example:
<div id="a1">
<?php
if (is_array($new_array) || is_object($new_array))
{
foreach ($new_array as $name => $val)
{
echo $name . " : " . $val[0] . " , " . $val[1]. " , " . $val[2];
}
}
unset($new_array);
?>
</div>
Let's say $new_array is not set/not an array/not and object. Your if statement will not continue, because it will receive false.
In case you wish to always execute your code you could do something like this: (see the notes for explanation).
<div id="a1">
<?php
$new_array = []; // [] = short for array();. $new_array will now always be an array.
// You could also do something like this:
$new_array = (! is_array($new_array)) ? $new_array = [] : $new_array; // Here you say $new_array is always set with his code and else it will be an empty array.
if (is_array($new_array)) //
{
foreach ($new_array as $name => $val)
{
echo $name . " : " . $val[0] . " , " . $val[1]. " , " . $val[2];
}
}
unset($new_array);
?>
</div>
http://php.net/manual/en/control-structures.if.php // Shorthand if/else
http://www.php.net/manual/en/function.is-array.php // is_array
You can check first if array exists or not. If it exists then check if it is empty(if it is an array) or count the number of elements in it is greater than zero (in case of object array)
<div id="a1">
<?php
if (is_array($new_array) || is_object($new_array)) {
if (isset($new_array)) {
if (empty($new_array) || count($new_array) > 0) {
foreach ($new_array as $name => $val) {
echo $name . " : " . $val[0] . " , " . $val[1] . " , " . $val[2];
}
}
}
}
unset($new_array);
?>
</div>
data type mismatch in php 7 result in this error.
instead of
$new_array='';
Initialize like
$new_array=array();
Once you unset it destroys that array. So intialize that before first block code

correct way of writing form data inside php tag

what i hoped to achieve is to echo each data as they come out from sql with checkboxes by theur side but it just ignores the form data inside the php
<form action = "index.php" method = "post">
<input type = "checkbox" name = "kona"/>
<?php
echo $selcat . "<br>";
if (isset ( $price_data )) {
$price_query = "SELECT * FROM titem WHERE comment = '$price_data'";
$price_result = mysql_query ( $price_query, $connection );
if (! $price_result) {
echo 'no' . mysql_error ();
}
while ( $price_row = mysql_fetch_array ( $price_result ) ) {
echo "<h3>" . $price_row['item'] . "</h3><br>";
echo "<input type = checkbox name = selitem" . $selitem . "/><br>";
echo 'Price = ';
if (is_numeric ( $price_row ['price'] )) {
echo $price_row ['price'] . " naira" . "<br>";
} else {
echo $price_row ['price'] . "<br>";
}
}
} else {
echo '';
}
?>
</form>
Any ideas as to how i can make this work?
You're outputting two tags mixed up together, like this:
<input type =checkbox name =selitem<h3>...</h3><br> />
Perhaps you meant to do:
echo '<input type="checkbox" name="selitem" /><h3>' . $price_row['item'] . '</h3><br />';
This would output:
<input type="checkbox" name="selitem" /><h3>...</h3><br />
Why are you concat 2 strings without PHP varaibles between that?
echo "<input type =" . "checkbox" . " name =" . "selitem" . "<h3>" . $price_row['item'] . "</h3><br>" . "/>";
It should be:
echo "<input type=\"checkbox\" name=\"selitem\"<h3>. $price_row['item']. "</h3><br> />";
You have to use array for name:
echo "<input type=\"checkbox\" name=\"selitem[]\"<h3>. $price_row['item']. "</h3><br> />";
And in PHP you can loop foreach on $_POST['selitem'] array - each element is checked element.

Echo in one line in PHP

I want to change the original code I have,
echo "<p><strong>" . __('Area:', 'honegumi') . "</strong> " . number_format($productarea) . " m² (";
echo metersToFeetInches($productarea) . " ft²)" . "</p>";
into a single echo line as shown here:
echo "<p><strong>" . __('Area:', 'honegumi') . "</strong> " . number_format($productarea) . " m² (" . metersToFeetInches($productarea) . " ft²)" . "</p>";
But I'm getting some strange line breaks in this second case for metersToFeetInches($productarea).
Generated HTML:
24,757
<p>
<strong>Area:</strong>
2,300 m² ( ft²)
</p>
Output:
24,757
Area:
2,300 m² ( ft²)
How can I solve it? Is there any documentation I could read to learn how to do it by myself in the future?
I'm pretty sure I know what's going on here, your function metersToFeetInches is echoing a value rather than returning it.
function metersToFeetInches() {
echo 'OUTPUT';
}
echo 'FIRST '.metersToFeetInches().' LAST';
// Outputs: OUTPUTFIRST LAST
echo metersToFeetInches() is actually redundant.
This is because the function runs before the string you built is actually output. Note that both examples you posted would have this problem. Change your function to return a value instead. Afterwards, any places where you have used it like so:
echo 'Something';
metersToFeetInches();
echo 'Something Else';
You'll have to use an echo:
echo 'Something';
echo metersToFeetInches();
echo 'Something Else';
Functions should pretty much always return a value. Lesson learned, perhaps?
If you are really in a bind and cannot change the function, you'll have to resort to output buffering:
ob_start();
metersToFeetInches($productarea);
$metersToFeetInches = ob_get_clean();
echo "<p><strong>" . __('Area:', 'honegumi') . "</strong> " . number_format($productarea) . " m² (" . $metersToFeetInches . " ft²)" . "</p>";
...which is rather silly to have to do.

if else function issue?

I have the following code with the if...else statement within a while loop.
$colour = array("50305A", "E33600", "DBDD02", "73BE58");
$nextcolr = next($colour);
if ($nextcolr == FALSE)
{
reset($colour);
echo current($colour);
}
else
{
echo next($colour);
}
I can't work out why what ever is in the else statement isn't being executed, even if I switch the two statements and reverse the operator. Could anyone help me?
The entire while loop:
while($row = mysql_fetch_array($result))
{
echo "by <a href='/neuro/profile.php?userid=$row[MemberID]'>" . $row['FirstName'] . " " . $row['LastName'] . "</a> on " . $row['Timestamp'] . " | " . $row['NumberOfComments'] . " comments.";
echo "<div id='blog' style='background-color:#";
if ($nextcolr == FALSE)
{
reset($colour);
echo current($colour);
}
else
{
echo next($colour);
}
echo "'><a href='blog.php?threadid=" . $row['tID'] . "'>" . $row['Title'] . "</a></div>";
}
$colour = array("50305A", "E33600", "DBDD02", "73BE58");
while ... {
$nextcolr = next($colour);
if ($nextcolr === FALSE)
{
reset($colour);
}
echo current($colour);
}
is how your while loop should look like. If I am right, you are also defining $colour in the while loop, which might cause problems.
If all this is in the while loop, then you are re-declaring the array on each iteration, thus returning the array internal pointer to the beginning with each iteration.
If you want to iterate this array multiple times, you could do it this way:
$colour = array("50305A", "E33600", "DBDD02", "73BE58");
$i = 0;
while ... {
...
echo $colour[$i++ % count($colour)];
...
}
So you don't need this if-else block.
The problem with your original while loop is that you never change the value of $nextcolr.
Thus, it always remains FALSE and the else part never gets executed.

PHP looped data will not echo outside the while function OR how can I pass looped data by echoing out of the while function?

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";
?>

Categories