PHP Variable changes its own value on equal loops - php

I have a variable putting out the coordinates of a address. I am printing the coordinates before the name to test at the moment. On odd number loops (it is in a foreach loop) it works fine, putting the variable in the data-latLng attribute. While on Even number loops it gives out different values - not coordinates. values like: 2 and ..
Here is what I mean:
An odd numbered loop would print this out:
Meanwhile on an even loop number, the data-latLng attribute puts out different values:
Here is the code:
$area_lat_long = isset($area_lat_long[$mapCounter])?$area_lat_long[$mapCounter]:"-26.2041028, 28.047305100000017";
echo $area_lat_long;
echo '<strong>area: '. $streetAdd[$count] .' <a class="glyphicon glyphicon-new-window" type="button" data-toggle="modal" data-target="#mapModal" data-latLng="'. $area_lat_long .'" style="cursor:pointer;"></a><br>';
$mapCounter++;
The PHP code runs above the table code, the code above gives the line of the coordinates and then the area.
As you can see, the $area_lat_long gives coordinates before every area, but when using the EXACT same variable for the data-latLng it changes on even loops?
Edit
To the guys who wanted the whole loop in the comments:
foreach ($streetAdd as $key){
print_r($area_lat_long);
//LAT LONG
$area_lat_long = isset($area_lat_long[$count])?$area_lat_long[$count]:"-26.2041028, 28.047305100000017";
echo $area_lat_long;
echo '<strong>area: '. $streetAdd[$count] .' <a class="glyphicon glyphicon-new-window" type="button" data-toggle="modal" data-target="#mapModal" data-latLng="'. $area_lat_long .'" style="cursor:pointer;"></a><br>';
$mapCounter++;?>
<input type="hidden" id="street_address" name="street_address[<?php echo $count; ?>]" value="<?php echo $streetAdd[$count];?>">
<table class="table table-striped">
<thead>
<tr>
<th>Media Type</th>
<th>Quantity Required</th>
<th>Average Asset Price</th>
<th><!-- Remaining Total --></th>
<th>More Options</th>
</tr>
</thead>
<tbody class="assetCounter">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<?php
$j = 0;
$total_used = 0;
$total_bal = isset($budget)?$budget:0;
$qty = 1;
$i = 0;
foreach ($my_categories as $key) { //loop thru chosen media types
foreach ((array)$key as $data) {
// print_r($data);
//check valid description
$j++;
$data_description = isset($data->mec_description)?$data->mec_description:'';
$latitude_longitude = explode(",",$area_lat_long); //print_r($latitude_longitude);
$latitude = $latitude_longitude[0];
$longitude = isset($latitude_longitude[1])?$latitude_longitude[1]:$latitude;
//pricing
$min_price = isset($data->asg_min_price)?$data->asg_min_price:0;
$max_price = isset($data->asg_max_price)?$data->asg_max_price:0;
$average_p = ($min_price + $max_price)/2;
$total_used += $average_p;
$total_bal -= $average_p;
if($total_bal < 0){
$total_bal = 0;
}
if($average_p == 0){
$title = "Pricing information not yet available from Media Owners";
} else {
$title = "NOTE: These are just estimates/guidelines, latest pricing information will be received from Media Owners quotations";
}
?>
<tr class="asset_<? echo $counterForAsset; ?>">
<td><?php
echo strtoupper($mec_stuff[$i]);
?>
<input type="hidden" id="media_category" name="mec_id[]" value="<?php
foreach($mec_stuff as $ms) {
echo $ms . ',';
}
?>">
<input type="hidden" id="media_category" name="media_category[]" value="<?php echo $data_description; ?>"></input></td>
<td><input type="text" class="form-control q_asset_<? echo $counterForAsset; ?> med_quantity" name="med_quantity[]" id="med_quantity" placeholder="Quantity Required" value="1"/></td>
<td><input type="text" readonly="true" name="avg_total[]" id="asset_<? echo $counterForAsset; ?>" class="form-control avg_asset_<? echo $counterForAsset; ?>" value="<?php echo number_format($total_bal,2); ?>" title="<?php echo $title;?>"/></td>
<!-- <td><input type="text" readonly="true" name="avg_total[]" id="avg_total--><?php //echo $j; ?><!--" class="form-control asset_--><?// echo $i; ?><!--" value="--><?php //echo number_format($total_bal,2); ?><!--" title="--><?php //echo $title;?><!--"/></td>-->
<td><input type="text" readonly="true" name="rem_total[]" id="asset_<? echo $counterForAsset; ?>" class="form-control rem_asset_<? echo $counterForAsset; ?>" value="<?php echo number_format($total_bal,2); ?>"/></td>
<!-- <td><input type="text" readonly="true" name="rem_total[]" id="rem_total--><?php //echo $j; ?><!--" class="form-control --><?// echo $i; ?><!-- asset_--><?// echo $i; ?><!--" value="--><?php //echo number_format($total_bal,2); ?><!--"/></td>-->
<td><?php echo "<a class='js-fire-modal btn btn-info' type='button' data-toggle='modal' data-mecid='$mec_stuff[$i]' href='#' name='size_button' onclick=\"sizeModal2(1, $j, '$latitude','$longitude','$description')\">>>></a>";?></td>
</tr>
<tr>
<td></td>
<td colspan="4" id="<?php echo $j; ?>"></td>
</tr>
<?php $i ++; $counterForAsset++; }
}?>
<tr>
<td> </td>
<td> <input type="hidden" id="hidSubtotal<?php echo $j;?>" value="<?php echo number_format($total_used,2); ?>"></td>
<td> Subtotal</td>
<td> <span id="lblSubtotal<?php echo $j; ?>"><?php echo number_format($total_used,2); ?></span> </td>
</tr>
</tbody>
</table>
<?php $count++;
}

foreach($a as $b) {
$x = isset($x[$c]) ? $x[$c] : "foo7";
echo $x;
}
Let us "run" that piece of code, assuming
$x = array('c' => 'lat,lng');
before the loop.
So loop #1 prints 'lat,lng'.
Loop #2 checks if isset('lat,lng'[$c]), evaluates to false, so $x will be 'foo'.
'foo' will be printed.
Loop #3 does the same as #2, but checks if isset('foo'[$c]), again evaluating to false.
Again 'foo' will be printed.
That's the reason.
I don't know what else you are doing outside that loop and most of the code seems to do nothing or nothing intended really.

Related

PHP Array and foreach Combination calculation

In a quiz app, I am taking user answer using a form. I am retrieving correct answer from database table. I want to compare the correct answer with the user's answer and count how many answer was right and how many answer was wrong.
Here is my form:
<form id="question" class="" action="quiz_ans.php" method="post">
<table id="quiz-question" align="center" class="row-border compact order-column stripe">
<input class="form-control" type="hidden" name="NumberofQuestions" id="NumberofQuestions" value="<?php echo $NumberofQuestions; ?>">
<thead>
<?php
if($QuizQuestions) {
$i=1;
foreach($QuizQuestions as $row):
?>
<tr>
<th><?php echo $i; ?>. <?php echo $row->Question; ?>
<br>
<?php if(isset($row->Screenshot)) { ?>
<img src="<?php echo htmlspecialchars($row->Screenshot); ?>" alt="test" height="300" width="980">
<?php } ?>
</th>
</tr>
</thead>
<tbody>
<?php if(isset($row->Option1)) { ?>
<tr class="info">
<td><input type="radio" name="AnswerId[<?php echo $row->Id; ?>]" value="0"><?php echo $row->Option1; ?></td>
</tr>
<?php } ?>
<?php if(isset($row->Option2)) { ?>
<tr class="info">
<td><input type="radio" name="AnswerId[<?php echo $row->Id; ?>]" value="1"> <?php echo $row->Option2; ?></td>
</tr>
<?php } ?>
<?php if(isset($row->Option3)) { ?>
<tr>
<td><input type="radio" name="AnswerId[<?php echo $row->Id; ?>]" value="2"> <?php echo $row->Option3; ?></td>
</tr>
<?php } ?>
<?php if(isset($row->Option4)) { ?>
<tr>
<td><input type="radio" name="AnswerId[<?php echo $row->Id; ?>]" value="3"><?php echo $row->Option4; ?></td>
</tr>
<?php } ?>
<tr>
<td><label for="AnswerReason">Why?</label><input class="form-control" type="text" name="AnswerReason[]" id="AnswerReason" value=""></td>
</tr>
<?php if(isset($row->Id)) { ?>
<tr>
<td><input class="form-control" type="hidden" name="QuestionId[]" id="QuestionId" value="<?php echo $row->Id; ?>"></td>
</tr>
<?php } ?>
</tbody>
<?php
$i++;
endforeach;
}
?>
</table>
<br>
<input type="submit" name="submit" value="Submit" class="btn btn-success">
</form>
I am getting the user answer from the form submit:
$NumberofQuestions = $_POST['NumberofQuestions'];
$ans = implode("", $_POST['AnswerId']);
I am retreiving the correct answer from the database table:
try {
$sql = "CALL spQuizAnswers(:quiz_num)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':quiz_num', $quiz_num, PDO::PARAM_STR, 50);
$stmt->execute();
$QuizAns=$stmt->fetchAll();
$stmt->closeCursor();
} catch (PDOException $e) {
die("Error occurred:" . $e->getMessage());
}
I am comparing the user's answer and the correct answer:
for ($i=0; $i<$NumberofQuestions; $i++) {
if($QuizAns) {
foreach($QuizAns as $row):
if($row->CorrectAns == $ans[$i]){
$right++;
} elseif($ans[$i] == 4){
$not_answered++;
} else {
$wrong++;
}
endforeach;
}
}
$CorrectAnswer = $right;
$WrongAnswer = $wrong;
$NotAnswered = $not_answered;
$TotalQuestion = $right+$wrong+$not_answered;
It does not give correct calculation. For 5 questions it gives $TotalQuestion=25.
How can I achieve the correct calculation? Any help would be much appreciated.

Insert data from while loop into a table with php

I'm creating a form using HTML and PHP. I have created a form which I want to submit and save that data in database.
I'm trying to submit a form with data that comes from a while loop. All input values are getting generated by while loop.
The code looks like this.
<table width="1348" border="0" class="table table-striped" >
<tr>
<td width="106"> </td>
<td width="332"><strong>Product Code</strong></td>
<td width="375"><strong>Product Name</strong></td>
<td width="211"><strong>QTY</strong></td>
</tr>
<?php
$i = 0;
$rowset = mysql_query("select * from product_detail where productID='".$data['productCode']."'");
while($stuff = mysql_fetch_array($rowset)){
?>
<tr>
<td><input type="text" name="code[<?php echo $i?>]" value="<?php enter code hereecho $stuff['code'];?>"/></td>
<td><input type="text" name="name[<?php echo $i?>]" value="<?php echo $stuff['name'];?>" size="50"/></td>
<td><input type="text" name="qty[<?php echo $i?>]" value="<?php echo $stuff['qty'];?>" size="10"/></td>
</tr>
<?php $i++; }?>
<tr id="last">
</table>
<input type="submit" name="save id="save" class="btn btn-primary btn-lg"/>
This is the code to add the data to database.
$code=$_POST['code'.$i];
$name=$_POST['name'.$i];
$qty=$_POST['qty'.$i];
$query = mysqli_query($con,"insert into stock(productCode, productName, qty) values ('".$code."', '".$name."','".$qty."')") or die(mysqli_error($con));
First, use prepared statement with bind_param as your script is totally exposed to sql injection.
Second, you can add input type hidden for the number of rows
<form action="" method="POST">
<table width="1348" border="0" class="table table-striped" >
<tr>
<td width="106"> </td>
<td width="332"><strong>Product Code</strong></td>
<td width="375"><strong>Product Name</strong></td>
<td width="211"><strong>QTY</strong></td>
</tr>
<?php
$data['productCode'] = "1"; // sample data
$stmt = $con->prepare("SELECT * FROM product_detail WHERE productID = ?");
$stmt->bind_param("i", $data['productCode']);
$stmt->execute();
$result = $stmt->get_result();
$i = 0;
while($stuff = $result->fetch_assoc()) {
?>
<tr>
<td></td>
<td><input type="text" name="code[<?php echo $i; ?>]" value="<?php echo $stuff['code'];?>"/></td>
<td><input type="text" name="name[<?php echo $i; ?>]" value="<?php echo $stuff['name']; ?>" size="50" /></td>
<td><input type="text" name="qty[<?php echo $i; ?>]" value="<?php echo $stuff['qty']; ?>" size="10" /></td>
</tr>
<?php
$i++;
}
?>
<input type="hidden" name="count" value="<?php echo $i; ?>" />
<tr id="last">
</table>
<input type="submit" name="save" id="save" class="btn btn-primary btn-lg"/>
</form>
post count with the form
<?php
if (isset($_POST['save'])) {
$count = $_POST['count'];
for ($i = 0; $i < $count; $i++) {
$code = $_POST['code'][$i]; // check empty and check if interger
$name = $_POST['name'][$i]; // check empty and strip tags
$qty = $_POST['qty'][$i]; // check empty and check if interger
$stmt = $con->prepare("INSERT INTO stock (productCode, productName, qty) VALUES (?, ?, ?)");
$stmt->bind_param("iss",$code,$name,$qty);
$stmt->execute();
}
}
?>
You may also want to check if post values are empty with other necessary validation before insert
Since the table is dynamically filled, you need to use an array as the name attribute
<table>
<tr>
<th>Name</th>
<th>Present</th>
<th>Excused</th>
<th>Unexcused</th>
<th>Ext</th>
</tr>
<?php
$query = "select * from TbCard";
$sql = mysqli_query($connect, $query);
$count = 0;
while ($data = mysqli_fetch_array($sql)) {
?>
<tr>
<td>
<input name="tableRow[<?php echo $count; ?>]['dataName']" id='name' type='text' value="<?php echo $data['Name'];?>" readonly style='border:none;width:350px'></input>
</td>
<td>
<input name="tableRow[<?php echo $count; ?>]['status']" type="radio" value="Present"> Present
</td>
<td>
<input name="tableRow[<?php echo $count; ?>]['status']" type="radio" value="Excused"> Excused
</td>
<td>
<input name="tableRow[<?php echo $count; ?>]['status']" type="radio" value="Unexcused"> Unexcused
</td>
</tr>;
<?php
$count++;
}
?>
</table>
The php would be something like this, assuming that the data has values in it:
$tableRow = $_POST['tableRow'];
foreach($tableRow as $row){
/* here insert data from post */
echo $row['dataName'].' '.$row['status'].'<br/>';
}
To see the content of the array, use print_r($tableRow)
in this case i use a name tableRow

Echo Array into new lines

I have an edit page where a user can edit an invoice form. I need to echo the array into a table but separate each array into a new line on the table.
When i echo the value, its bunched up into one line. When i echo the value into an input field, i only get one record from the array.
Here's what it looks like in my table:
<?php
$id = $_GET['id'];
$result = mysqli_query($mysqli, "SELECT * FROM invoices WHERE id=$id");
while($res = mysqli_fetch_array($result))
{
$partnumber = $res['partnumber'];
$partdescription = $res['partdescription'];
$partprice = $res['partprice'];
$partquantity = $res['partquantity'];
}
>
And then the table:
<tr>
<td><input type="text" class="input-small" name="partnumber[]" value=<?php echo $partnumber;?>></td>
<td><input type="text" class="input-small" name="partdescription[]" value=<?php echo $partdescription;?>></td>
<td><input type="text" class="input-small" name="partprice[]" size="4" value=<?php echo $partprice;?>></td>
<td><input type="text" class="input-small" name="partquantity[]" size="4" value=<?php echo $partquantity;?>></td>
</tr>
I get this:
<tr>
<td><?php echo $partnumber;?></td>
<td><?php echo $partdescription;?></td>
<td><?php echo $partprice;?></td>
<td><?php echo $partquantity;?></td>
</tr>
I get this:
I tried the following but they both result in a blank echo:
<tr>
<td><? echo $res['partnumber']; ?></td>
</tr><tr>
<td><? echo $res['partdescription']; ?></td>
</tr><tr>
<td><? echo $res['partprice']; ?></td>
</tr><tr>
<td><? echo $res['partquantity']; ?></td>
</tr>
And
<? foreach ($res as $row) { ?>
<tr>
<td><? echo $row['partnumber']; ?></td>
<td><? echo $row['partdescription']; ?></td>
<td><? echo $row['partprice']; ?></td>
<td><? echo $row['partquantity']; ?></td>
</tr>
<?
}
?>
This is the GOAL:
Please help
EDIT***************
I will fix the security issue once i have the table working.
I tried this and the output is still on ONE line.
<?php
$id = $_GET['id'];
$result = mysqli_query($mysqli, "SELECT * FROM invoices WHERE id='".mysql_real_escape_string($id)."' ");
while($res = mysqli_fetch_array($result))
{
?>
<tr>
<td><input type="text" class="input-small" name="partnumber[]" value=<?php echo $res['partnumber'];?>></td>
<td><input type="text" class="input-small" name="partdescription[]" value=<?php echo $res['partdescription'];?>></td>
<td><input type="text" class="input-small" name="partprice[]" size="4" value=<?php echo $res['partprice'];?>></td>
<td><input type="text" class="input-small" name="partquantity[]" size="4" value=<?php echo $res['partquantity'];?>></td>
<?php
}
?>
Does this help?
Please note, its only displaying 1 record because i have multiple values in one record and them i'm separating them with a comma. Please check screenshots above. Here's the code:
$partnumber = $_POST['partnumber'];
$partnumberarray = implode( ", ", $partnumber);
$partdescription = $_POST['partdescription'];
$partdescriptionarray = implode( ", ", $partdescription);
$partprice = $_POST['partprice'];
$partpricearray = implode( ", ", $partprice);
$partquantity = $_POST['partquantity'];
$partquantityarray = implode( ", ", $partquantity);
$result = mysqli_query($mysqli, "INSERT INTO invoicespartnumber, partdescription, partprice, partquantity, login_id) VALUES('$partnumberarray', '$partdescriptionarray', '$partpricearray', '$partquantityarray', '$loginId')");
Is there anyway i can echo the values from the 1 record which is separated by a comma into multiple lines on the table?
You have to put your html inside while loop that you do over result array.
It will look like this.
<?php
$id = $_GET['id'];
$result = mysqli_query($mysqli, "SELECT * FROM invoices WHERE ID='".mysql_real_escape_string($id)."'");
while($res = mysqli_fetch_array($result)){ //close php here to easier write html. ?>
<tr>
<td><input type="text" class="input-small" name="partnumber[]" value="<?php echo $res['partnumber'];?>"></td>
<td><input type="text" class="input-small" name="partdescription[]" value="<?php echo $res['partdescription'];?>"></td>
<td><input type="text" class="input-small" name="partprice[]" size="4" value="<?php echo $res['partprice'];?>"></td>
<td><input type="text" class="input-small" name="partquantity[]" size="4" value="<?php echo $res['partquantity'];?>"></td>
</tr>
<?php //open php tag again to add end scope to while loop
}
?>
<table width = "100%">
<thead>
<tr>
// here will be all columns names in th
</tr>
</thead>
<tbody>
<?php
$id = $_GET['id'];
$result = mysqli_query($mysqli, "SELECT * FROM invoices WHERE id=$id");
while($res = mysqli_fetch_array($result))
{ ?>
<tr>
<td><?php echo $res['partnumber']; ?></td> <!-- Also use input box here -->
<td><?php echo $res['partdescription'];?><td>
<td><?php echo $res['partprice']; ?></td>
<td><?php echo $res['partquantity'];?></td>
</tr>
<?php
}
?>

Looping through (and displaying) multiple table rows from SQL

Having trouble looping through multiple rows in a SQL table and getting the info to display correctly. The closest I have got is the following:
<table border="1" cellpadding="10">
<th>Stock</th><th>Price</th><th>Shares</th><th>Value</th><th>Sell Stock</th>
<?php
$transactions = mysql_query("SELECT * FROM transactions WHERE email='$email'");
while ($rows = mysql_fetch_assoc($transactions)) {
foreach($rows as $row) {
$symbol = $row["symbol"];
$price = $row["price"];
$shares = $row["shares"];
$value = $price * $shares;
?>
<form name="sellStock" action="sell.php" method="get">
<tr>
<td><input name="symbol" type="hidden" value="<?php echo $symbol ?>"><?php echo $symbol ?></td>
<td><input name="price" type="hidden" value="<?php echo $price ?>"><?php echo $price ?></td>
<td><input name="shares" type="hidden" value="<?php echo $shares ?>"><?php echo $shares ?></td>
<td><input name="value" type="hidden" value="<?php $value ?>" /><?php $value ?></td>
<td><input name="sell" type="submit" value="Sell"></td>
</tr>
<?php
}
}
?>
</table>
The while/foreach loop goes on to display the info from the rows into a HTML table, but it displays the first character from every column as opposed to all the characters from the columns I echo to be displayed (symbol, price, and shares). Any ideas?
<table border="1" cellpadding="10">
<th>Stock</th><th>Price</th><th>Shares</th><th>Value</th><th>Sell Stock</th>
<?php
$transactions = mysql_query("SELECT * FROM transactions WHERE email='$email'");
while ($row = mysql_fetch_assoc($transactions)) {
$symbol = $row["symbol"];
$price = $row["price"];
$shares = $row["shares"];
$value = $price * $shares;
?>
<form name="sellStock" action="sell.php" method="get">
<tr>
<td><input name="symbol" type="hidden" value="<?php echo $symbol ?>"><?php echo $symbol ?></td>
<td><input name="price" type="hidden" value="<?php echo $price ?>"><?php echo $price ?></td>
<td><input name="shares" type="hidden" value="<?php echo $shares ?>"><?php echo $shares ?></td>
<td><input name="value" type="hidden" value="<?php $value ?>" /><?php $value ?></td>
<td><input name="sell" type="submit" value="Sell"></td>
</tr>
<?php
}
?>
</table>
You just had one loop too many. The while loop continues until !$row, with one row per execution, so you don't want the foreach loop you had.

multi checkbox that can check all and uncheck all

How can I put the name of checkbox in correct way then it can run with the javascript
<?php $i=1; ?>
<?php do { $i++; ?>
<tr>
<td><input name="<?php echo 'checkbox[$i]' ; ?> " type="checkbox" id="<?php echo $row_RsActivitynoteMem['id']; ?>" value="<?php echo $row_RsActivitynoteMem['id']; ?>" />
<label for="checkbox"></label></td>
<td><?php echo $row_RsActivitynoteMem['Sname']; ?> <?php echo $row_RsActivitynoteMem['Ssurname']; ?></td>
<td width="20"><?php echo $row_RsActivitynoteMem['idactivity']; ?></td>
<td><?php echo $row_RsActivitynoteMem['kname']; ?></td>
<td> </td>
</tr>
<?php } while ($row_RsActivitynoteMem = mysql_fetch_assoc($RsActivitynoteMem)); ?>
<tr>
<td> </td>
<td> </td>
<td width="20"> </td>
<td> </td>
<td> </td>
</tr>
</table>
<input type="button" name="CheckAll" value="Check All"
onClick="checkAll(document.form1.checkbox)">
<input type="button" name="UnCheckAll" value="Uncheck All"
onClick="uncheckAll(document.form1.checkbox)">
<br>
</form>
</body>
</html>
<?php
mysql_free_result($RsActivitynoteMem);
?>
How can I make CheckAll at the bottom work and handle the check box variable when sending to another page?
This javascript worked:
function checkAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = true ;
}
function uncheckAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = false ;
}
// End --
You should probably change your 5th code lines "name"-attribute, because PHP doesn't parse variables in single quotes.
It should be
<?php echo "checkbox[$i]"; ?>
or even better
<?php echo sprintf( 'checkbox[%s]', $i ); ?>
Otherwise the name in your HTML-File will in fact be like <input name="checkbox[$i]" type="checkbox" ... />

Categories