listing post keys to make it easier to use - php

I have 12 keys inside my $_post[].
I can reach them without any issue but I want to make it easier, as there will be more keys (I am thinking of 30+).
Here is an example of what I have inside my $_post:
$_post['var1']
$_post['qty1']
$_post['var2']
$_post['qty2']
$_post['var3']
$_post['qty3']
This continues till 12 (at the moment).
It is being posted this way:
$count = 0;
foreach ($results as $mat) {
$count++;
echo "<tr><td>{$count}</td>";
echo "<td><input type='text' name='var{$count}' value='{$mat['var']}' /></td>";
echo "<td><input type='text' name='qty{$count}' value='{$mat['qty']}' /></td></tr>";
}
I need to use those variables later to update my sql table, and to have it done one-by-one is a nightmare ( as I am still not sure how many it will be ).
What can I do to achieve it in an easier way ?

you can make name as array like this. var[] and qty[]
echo "<td><input type='text' name='var[]' value='{$mat['var']}' /></td>";
echo "<td><input type='text' name='qty[]' value='{$mat['qty']}' /></td></tr>";
and receive in php like this
$arr_var = $_POST['var'];
$arr_qty = $_POST['qty'];
foreach($arr_var as $key=>$value)
{
$var = $value;
$qty = $arr_qty[$key];
}

foreach($_POST as $key=>$value)
{
$$key = $value; // notice the $$, it's known as variable variable
// remove the below comment if you want to see how they are coming out
// echo "$".$key." = ". $value."<br />";
}
This will create variables names based on the name attribute of the input box.

Related

Checkbox looping in php while posting to database

I am building at the moment an achievement system that works on the foundation of checkboxes (since its not post related) However, I bumped into a problem, and I cant seem to wrap my head arround it, since I am not that handy with loops and Arrays.
Okay, So I made group of checkboxes, that are posted on this page and filled appropiately, as see the code below that helps me fill that part of the page.
function MakeProfessionlist(){
$result = LoadListProffesion();
$i = 0;
echo '<table class="Overview">';
while($row = mysqli_fetch_array($result)){
$i++;
if(($i % 2) == 0){
echo "<td class='small'><td><input id='achievementHidden' type='hidden' value='0' name='IsChecked[]'>";
echo "<input type='checkbox' id='achievement' name='IsChecked[]' value = '1'>";
echo "<input name='AchievementId[]' type='hidden' value='".$row['AchievementId']."'></td>";
echo "<td class='big'>".$row["AchievementName"]."</td></tr>";
}else{
echo "<tr><td class='small'><input id='achievementHidden' type='hidden' value='0' name='IsChecked[]'>";
echo "<input type='checkbox'id='achievement' name='IsChecked[]' value = '1'>" ;
echo "<input name='AchievementId[]' type='hidden' value='".$row['AchievementId']."'></td>";
echo "<td class='big'>".$row["AchievementName"]."</td>";
}
}
echo '</table>';
}
As you see, i try to shoot through 2 variables, namely the AchievementId, and the IsChecked value (can be either 0 or 1)The problem occurs when I am going to save this information. I set up a table within the database that acts as mediator (The Achievement_User, with just 3 entries, which are UserId, AchievementId and the IsChecked Value)
My start was that I shoot through all the achievements that come through here with the AchievementId's that are posted together with the checkbox through the code down below.
if(isset($_POST['AchievementSaveData']))
{
// print_r($_POST);
$checkbox = isset($_POST['IsChecked']) ? $_POST['IsChecked'] : array();
$Achievement = isset($_POST['AchievementId']) ? $_POST['AchievementId'] : array();
foreach (array_combine($checkbox, $Achievement) as $IsChecked => $AchievementId){
$sql="SELECT * FROM Achievement_User WHERE UserId='".$UserId."' AND AchievementId ='".$AchievementId."'" ;
$result=mysqli_query($sql);
$count=mysqli_num_rows($result);
if ($count==1){
echo 'Update datarow with UserID '.$UserId.', AchievementId '. $AchievementId.' and with a value of '.$IsChecked;' <br>';
}
else{
echo 'Create datarow with UserID '.$UserId.', AchievementId '. $AchievementId.' and with a value of '.$IsChecked.' <br>';
}
}
}
Now the problem lies in the fact that when I check a checkbox, appearantly the Array gets increased. Instead of the 40 entrees it makes (which is how many AchievementId's are posted, and when checked everything off is the default) it creates an extra array space for each checked value, which makes my comparison useless, cause i get an error then that the arrays can be combined.
Is there any way I can work arround it what would make my array of AchievementId's match up with my IsChecked Value?
Edit: Next to that, the whole foreach loop doesn't seem to work anymore when I tried to merge the arrays (even if they match in values). So my thought here is maybe is there a way I can post the array from IsChecked with already the value of the AchievementId attached to it. If that is so, how could I work this out?
why don't you just give the checkbox the value of the achievement and get rid of the hidden input
<input type='checkbox' id='achievement' name='IsChecked[]' value = '<?php echo $row['AchievementId'];?>'>
then in the php
foreach ($IsChecked as $AchievementId){

Is it possible to pass a variable of value from associative array, using hidden input, to another page?

I am trying to get the $w['id'] value for a mysql row and pass it to another page using a hidden input field and variable $blog_id. Here is the code for the first page:
$query = "SELECT * FROM blog WHERE username = '$username' ORDER BY created_date DESC;";
$result = $mysqli->query($query);
$rows = resultToArray($result);
// var_dump($rows);
foreach($rows as $r => $w) {
echo "<tr>\n";
echo "<td>{$w['title']}\n";
echo "<td>{$w['id']}\n";
echo "<td>{$w['created_date']}</td>\n";
echo "<td>{$w['updated_date']}</td>\n";
echo "<td style=\"border:none\">{$w['template']}</td>\n";
$blog_id = $w['id'];
echo "<input type=\"hidden\" name=\"id\" value=\"$blog_id\" />\n";
echo "<td style=\"border:none\"><button type=\"submit\" name=\"view\">View</button></td>\n";
echo "<td style=\"border:none\"><button type=\"submit\" name=\"edit\">Edit</button></td>\n";
echo "<td style=\"border:none\"><button type=\"submit\" name=\"delete\"><font color=\"red\">Delete</font></button></td>";
echo "</tr>\n";
}
?>
In my html table the values echo correctly but when I try to grab the $w['id'] value and pass it using, say, the edit button to the next page the value is always the lowest id value in the mysql table.
The code for the critical part in the second page is:
sec_session_start();
$username = $_SESSION['username'];
// $blog_id = $_SESSION['blog_id'];
if(isset ($_POST['edit'])) {
$blog_id = $_POST['id'];
$result = $mysqli->query("SELECT * FROM blog WHERE id = '$blog_id'");
if($result->num_rows > 0) {
$rows = resultToArray($result);
foreach($rows as $r => $w) {
?>
<body id="blog_editor">
<?php var_dump($_POST); ?>
The value of var_dump($_POST) is always ["id"]=>string(2) "43" whereas the foreach loop on the first page produces lots of different IDs.
Does anybody know what I am doing wrong or have an alternative way of doing the same kind of thing which might work?
You use a foreach and echo many different id.
I don't see any SUBMIT button or <form> tag.
What you can do is, inside the foreach loop, create a form with is own button:
<?php
foreach($rows as $r => $w) {
echo '<form action="page.php" ...>
echo ....
echo '<input type="submit">
}
?>
OR if you have multiple results inside one only form then you have to change the name of your element (which will be later give the value to `$_POST['id']) every time the loop loops.
To do this change this line:
echo "<input type=\"hidden\" name=\"id\" value=\"$blog_id\" />\n";
1) to this:
echo "<input type='hidden' name='id".$blog_id."' value='$blog_id' />\n";
and then when you call $_POST you'll have $_POST['idXX'] where XX = number of the ID
2) or TO this to create an array with all IDs on it:
echo "<input type='hidden' name='id[]' value='$blog_id' />\n";
and then $_POST['id'] will be an array

Getting multiple values of checkbox from a loop

while($row = mysql_fetch_array($result)){
echo '<tr>
<td>'.$row[0].'</td>
<td>'.$row[1].'</td>
<td>'.$row[2].'</td>';
$price=$row['price'];
echo "<td><input type='checkbox' name='er' value='$price'></td>";
echo "</tr>";
PHP file
<?php
$ercharge=$_POST['er'];
echo $ercharge;
?>
I have a list of charges that was from a mysql table and it has a checkbox for each item so it would compute the sum. The above code works and it outputs the price of the checked item. The problem is, it's only one item. When multiple items are checked, only one is outputted.
Try this:-
echo "<td><input type='checkbox' name='er[]' value='$price'></td>";
Try this it may help you
echo "<td><input type='checkbox' name='er[]' value='$price'></td>";
echo "</tr>";
$recharge=$_POST['er'];
foreach($recharge as $val)
{
echo $val;
}
Or
you can just do this without using foreach
$arra_val=array_sum($recharge);
you just need to put the value in to some variable and echo it.
If you want to pass a number of elements in an array append the name with square brackets, so it would be:
echo "<td><input type='checkbox' name='er[]' value='$price'></td>";
And the result of $_POST['er'] would be an array of all of the checkbox values.
The input box name should reflect that it's an array by adding the [] suffix:
echo '<td><input type="checkbox" name="er[]" value=" . htmlspecialchars($row['price']) . "></td>';
Then, to process the sum after making sure the input validates as proper values:
if ($ers = filter_input(INPUT_POST, 'er', FILTER_VALIDATE_FLOAT, FILTER_FORCE_ARRAY)) {
$ercharge = array_sum($ers);
}

Array is not populating the first record

I have this array populating from mysql. But it is not showing me the first record. I can't figure out what the problem is. It should be simple. Here is the code.
$result=mysql_query("SELECT user_instance.instance_name, user_instance.host_name FROM
dba_account, user_instance WHERE dba_account.account_id = user_instance.account_id AND
dba_account.account_id = '1'");
echo mysql_error();
$nume = mysql_fetch_row($result);
while($note = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td><input type='text' name='instance_name' class='instance_name'
disabled='disabled' value='$note[instance_name]' size='25' /></td>";
echo "<td><input type='text' name='host_name' class='host_name' disabled='disabled'
value='$note[host_name]' size='25' /></td>";
echo "</tr>";
}
You're fetching the first row in $nume = mysql_fetch_row. That pulls the first record. Then you're iterating through the rest of the records in your while loop. Remove that first line.
The first time you call mysql_fetch_row(), it advances the result resource pointer to the second result. Don't do that. Especially considering you are not using the variable $nume in your loop in any way, it is unnecessary and harmful to your logic.
// Don't do this!
//$nume = mysql_fetch_row($result);
// Instead just fetch the loop
while($note = mysql_fetch_array($result)) {
// etc...
}

PHP - trying to create an array of checkboxes,

I'm trying to create an Array from multiple checkboxes that are created via a while loop. the check boxes are named 'to_delete[1]', 'to_delete[2]', etc. etc.
the array statements i've tried are these:
$toDelete = array($_POST['to_delete']);
$toDelete = array($_POST['to_delete'][]);
to veryify there is an array, i go to print but find it is empty print_r($toDelete). What am i doing wrong?
the code is below. Yes, i'm doing this procedurally, and then will re-write as OOP.
big thanks for any help on this!,
$showQ = "SELECT * FROM urls";
$result = mysql_query($showQ);
$numRows = mysql_num_rows($result);
$row = mysql_fetch_array($result);
if(!$result) {
mysql_error();
} else {
echo "<form action='".$_SERVER["PHP_SELF"]."' method='post'>";
$i=0;
while($row = mysql_fetch_array($result)) {
echo "<input type='text' class='manId' name='manId[]' value=" . $row['id'] . " />";
echo "<input type='text' class='url' name='url[]' value=" . $row['url'] . " />";
echo "<input type='checkbox' name='to_delete[" .$i. "]' /><br/>\n";
$i++;
}
echo "<input type='submit' value='delete' name='submit' />";
echo "</form>";
}
$toDelete = array($_POST['to_delete[]']);
print_r($toDelete);
Ultimately, i want to traverse the array, see which ones are checked and then delete the corresponding row from the table.
You don't want to create an array with the array() call, but rather to access one. $_POST will receive input names ending with [] as arrays, so the corresponding array keys in $_POST will already be arrays. The way you've written your code, you are assigning a one-element array containing a sub-array from $_POST. Instead, try the following:
// Test if $_POST['to_delete'] is set and non-empty
// If it's empty, create an empty array, otherwise assign it to $toDelete
$toDelete = empty($_POST['to_delete']) ? array() : $_POST['to_delete'];
print_$($toDelete);

Categories