I have a table with rows that are in the form:
ID, Name, First Name, IntA, IntB, IntC, ...
The last columns are textfields.
I want to select multiple rows with a Checkbox and send the ID and the recorded integers with POST to another PHP-File.
This is my code-example (with a little bit German in it):
echo "<td><input type='checkbox' name='auswahl[]' value='$daten[0]'></td>";
echo "<td>" . $daten['ID'] . "</td>";
echo "<td><input type='number' name='Schr' value='".$punkte['PktSchr']."'></td>";
echo "<td><input type='number' name='Mdl' value='".$punkte['PktMdl']."'></td>";
So in the other PHP-File I want to SQL for all checked rows like this (in a Loop):
$Eintraege = $_POST['auswahl'];
$Schr = $_POST['Schr'];
$Mdl = $_POST['Mdl'];
foreach ($Eintraege as $i){
$sql = "INSERT INTO aufnahme (IDSchueler, PktSchr, PktMdl) Values ('$i', '$Schr', '$Mdl')";
}
My problem is this: $Eintraege contains only the IDs of the selected rows (because of value='$daten[0]').
$Schr and $Mdl contains the values of the textfields of the last row (doesn't matter, wich rows are selected).
So I tried to set value='$daten' and use it lika an array, but then I get an Exception.
I think I have to change value='$daten[0]', but don't know how.
Thanks for your help!
Change two other names to array type too and you will get all values.
So do like below:-
echo "<td><input type='number' name='Schr[]' value='".$punkte['PktSchr']."'></td>";
echo "<td><input type='number' name='Mdl[]' value='".$punkte['PktMdl']."'></td>";
And then you can do like below:-
foreach ($Eintraege as $k=> $i){
$sql = "INSERT INTO aufnahme (IDSchueler, PktSchr, PktMdl) Values ('$i', '$Schr[$k]', '$Mdl[$k]')";
}
As #Alive-to-Die mentioned, turn the names into arrays.
<input type='checkbox' name='auswahl[]' value='$daten[0]'>
This itself doesn't look good. Consider making it
<input type='checkbox' name='auswahl[]' value='{$daten[0]}'>
or
<input type='checkbox' name='auswahl[]' value='".$daten[0]."'>
These are two proper ways to use variables inside strings.
Related
I've written this code for a user to edit one row and update it in MySQL, but it always posts the last row no matter which row you have selected (there are 3 rows).
What's the problem?
<?php include("includes/db_connection.php"); ?>
<?php
global $connection;
$sid="s5";
/**select all salesman from store 5**/
$sql ="SELECT * FROM employees WHERE e_type='Salesperson' AND store_assigned='".$sid."';";
/**get the result and put into table, which can be edited by user**/
$result = mysql_query($sql);
echo "<form method='post' action='update_salesman.php'>";
echo "<table border='1'><tr><th>Employee ID</th><th>Name</th><th>Address</th><th>Email</th><th>Job Title</th><th>Store</th><th>Salary</th></tr>";
while ($row = mysql_fetch_assoc($result)) {
echo "<tr><td><input type='text' name='eid' value='".$row['eid']."' readonly /></td>";
echo "<td><input type='text' name='e_name' value='".$row['e_name']."' /></td>";
echo "<td><input type='text' name='e_addr' value='".$row['e_addr']."' /></td>";
echo "<td><input type='text' name='e_email' value='".$row['e_email']."' /></td>";
echo "<td><input type='text' name='e_type' value='".$row['e_type']."' /></td>";
echo "<td><input type='text' name='store_assigned' value='".$row['store_assigned']."'/></td>";
echo "<td><input type='text' name='e_salary' value='".$row['e_salary']."' /></td>";
echo "<td><input type ='submit' value='update' /></td></tr>";
}
echo "</table>";
echo "</form>";
print($sql);
?>
Get the posted data, and update it in MySQL database:
<?php include("includes/db_connection.php"); ?>
<?php
$eid = $_POST['eid'];
$ename = $_POST['e_name'];
$eaddr = $_POST['e_addr'];
$eemail = $_POST['e_email'];
$etype = $_POST['e_type'];
$estore = $_POST['store_assigned'];
$esalary = $_POST['e_salary'];
$sql = "UPDATE employees SET e_name='" . $ename . "', e_addr='" . $eaddr . "', e_email='" . $eemail . "', e_type='" . $etype . "', store_assigned='" . $estore . "', e_salary='" . $esalary . "' WHERE eid='" . $eid . "' ;";
$result = mysql_query($sql);
print("</br>" . $sql);
?>
The result is always this:
UPDATE employees SET e_name='Norah ', e_addr='111 Melwood,PA', e_email='anorahm#gmiil.com', e_type='Salesperson', store_assigned='s5', e_salary='4000.00' WHERE eid='e334' ;
Your problem is twofold. First, when generating the HTML code, you use a while loop to echo the fields. Note that the names of these fields are the same every time the loop runs. (You can see this in the generated HTML (source code). Note that on submitting, one one of the multiple same-named fields will be posted.
Second, in the PHP form handler code, you read the post data and then do one update query, while you may want to update more than one field.
The easiest way to solve this is to make sure that the field names in the HTML form are different for each of the rows, and to use a loop structure when updating the sql table such that there's an update for each row.
even though it may appear fine on the html side, it's clear what's happening on the server side when it gets the form
When the server gets the form it will only see the last record because each record will overwrite the values that come before it resulting in only getting the data from the last record
What you can do is give each set of values its own form (Wouldn't suggest). But with this method, you can leave your code almost as is, just move the form tags into the while loop. OR write the input names as e_name[], etc.
This way it will be passed as an array to the server and you can loop through to get all your values
On the server end, to get the array you would do something like
$e_names = $_POST['e_name']; //Value will be an array
I'm using a while loop and mysql_fetch_array to display info on a page from a database. How can I give a variable name to certain radio button elements that are echoed on the page, and then use those variable names for the radio buttons as $_POST variables when the form is submitted?
Here is the code:
session_start();
include 'acdb.php';
$prodid = $_SESSION['prodid'];
$e = "SELECT * FROM Images WHERE product_id=$prodid AND active='yes'";
$e_result = mysql_query($e,$connection) or die ('Could not get the list of all Images for this Product and Service');
$amount = mysql_num_rows($e_result);
while ($e_data = mysql_fetch_array($e_result)) {
echo "<img src='images/thumbnails/" .$e_data[1]. "' border='0'>";
echo "<label class='sel-photo'>DISPLAY PICTURE:</label> <input type='radio' name='{radio" .$e_data[0]. "}' value='1'>";
echo "<br>";
echo "<label class='sel-photo'>DO NOT DISPLAY PICTURE:</label> <input type='radio' name='{radio" .$e_data[0]. "}' value='0' checked>";
}
You will get the result you are after by doing this
echo "<label class='sel-photo'>DISPLAY PICTURE:</label> <input type='radio' name='radio" .$e_data[0]. "' value='1'>";
So assuming $e_data[0] = 'xxx' you would get html of
name='radioxxx'
PS. Its best, especially when using SELECT * to use the form $e_data['fieldname']. This is because the columns will be returned in the order they were created on the table when using *. If you/someone else decides to reorganise the table columns at a later date, they will be returned in a different order and $e_data[0] may now point to a different column.
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){
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);
}
I am trying to create a search function with multiple variables. Basically I have a standard style form, and each element has a name. Those names on submit are retrieved via POST then the search query is conducted. I have posted my code and I know I have probably gone about this a terrible way but I am looking for direction on how to make it suitable. Still very new to PHP so advice on better ways to structure this that I can then go and learn/implement would be appeciated. Currently it does search via the first variable $search but I'm not sure how to implement the rest. The user should be able to input 1 or multiple variables then the search is conducted. At this point it is only searching one table and I would like it to search multiple tables long term, all the columns in the different tables have the same name, just different data. Any guidance appreciated here. Cheers.
//define variables to be used
$table = 'aecm';
$search = #$_POST['search'];
$status = #$_POST['status'];
$repair = #$_POST['repair'];
$upgrade = #$_POST['um'];
$pm = #$_POST['pm'];
$nofault = #$_POST['nf'];
//Connect to database
include '/../connect.php';
//conduct a search
$result = mysql_query("SELECT * FROM $table
WHERE (part LIKE '%$search%')
OR
(serial LIKE '%$search%')
OR
(mac LIKE '%$search%')
OR
(ip LIKE '%$search%')
OR
(status LIKE '%$search%')
ORDER BY part ASC");
if (!$result) {
die("Query to show fields from table failed");
}
Added the form code showing the variables.
echo '<form ENCTYPE=multipart/form-data form name=benchsearch
action=benchsearchresults.php method=post>';
//search selection
echo '<table>';
echo '<tr><td>Standard Search </td>';
echo "<td><input type=text maxlength=30 name=search /></td>";
echo '<tr><td>Search Status of Equipment </td>';
echo "<td><select name=status>";
echo "<option> </option>";
echo "<option> SERVICEABLE </option>";
echo "<option> UNSERVICEABLE </option>";
echo "<option> BEYOND ECONOMICAL REPAIR </option></select></td>";
echo "<tr><td>Search Type of Repair :</td>";
echo "<tr><td>Repair </td>";
echo "<td><input type=checkbox name=repair value=rep /></td>";
echo "<tr><td>Updrade/Modification </td>";
echo "<td><input type=checkbox name=upgrade value=um /></td>";
echo "<tr><td>Preventitive Maintenance Check </td>";
echo "<td><input type=checkbox name=pm value=pm /></td>";
echo "<tr><td>No Fault Found </td>";
echo "<td><input type=checkbox name=nofault value=nf /></td>";
echo "</table>";
echo '<center><input type="submit" class="button" id="submit" value="Search"/> </center>';
echo "</form>";
My tables are as follows
Table aecm, aicm etc
Columns - part, serial, mac, ip, status
Table aecmhis, aicmhis etc
Columns - serial, repair, upgrade, pm, nofault
I want to use a form as above (or similair) to conduct a search and show results from all tables. The serial number is common between aecm-aecmhis and aicm-aicmhis etc. Status is only 1 of 3 options and the repair, upgrade, pm, nofault columns are either empty or have yes in them. Just looking for the best way to go about this.
why not take table as an argument too i mean use post to let the user specify the table they want to search the rest of the code can remain the same. I am not very sure i understood what you really needed so let me know if this is not what u wanted
If you want to be able to query multiple tables with multiple query terms on each search, sql my not be the best solution. Something like Apache Lucene may be a place to start looking. I know Zend Framework has a component that implements an indexed Lucene search engine and may be a place to start (you can use just the components you want with ZF).
P.S. This is not simple!
Good Luck.