Hidding a column from a table - php

I have this table with checkboxes, my idea is to be able to delete the rows where the checkboxes have been checked.
With the help of Charaf jra, I was able to POST the uniqID of the row so I could DELETE it using mysql query on my delete.php page.
My problem now is in order to pass the uniqID I had to add it on the table, which doesnt look good. I mean, I dont want the ID number showing on the table. I have been reading on how to hide it, but none of the explanations I have read apply to my case.
Here is my code updated:
if ($arch = $pdo->prepare("SELECT name, age, uniqID FROM table WHERE id = ?")) {
$arch ->execute(array($id));
$data = $arch->fetchAll();
echo '<div class="coolTable" ><form method="post" action="delete.php"><table><tr><td>Name</td><td>Age</td><td>Check</td></tr>';
foreach ($data as $row){
echo '<tr>';
foreach ($row as $col){
$col=nl2br($col);
echo '<td>'.$col.'</td>';
}
echo '<td><input type="checkbox" name="checkbox[]" value="'.$col.'" id="checkbox"></td>'; //this captures the column ID so I can pass it through the `POST`
echo '</tr>';
}
echo '</table><input type="submit" value="Delete Selected"/></form></div>';
}
This works perfect. The only big problem is that I dont want the uniqID to be shown. Can anyone tell me how to hide it from the table and still be able to pass it through the POST?

if ($arch = $pdo->prepare("SELECT name, age, uniqID FROM table WHERE id = ?")) {
$arch ->execute(array($id));
$data = $arch->fetchAll();
echo '<div class="coolTable" ><form method="post" action="delete.php"><table><tr><td>Name</td><td>Age</td><td>Check</td></tr>';
foreach ($data as $row){
echo '<tr>';
echo '<td>'.nl2br($row['name']).'</td>';
echo '<td>'.nl2br($row['age']).'</td>';
echo '<td><input type="checkbox" name="checkbox[]" value="'.nl2br($row['uniqID']).'" id="checkbox"></td>'; //this captures the column ID so I can pass it through the `POST`
echo '</tr>';
}
echo '</table><input type="submit" value="Delete Selected"/></form></div>';
}
PHP arrays can be used as dictionaries (if you've seen python or ruby). PDO returns an array of pairs key-value, where your key is the name your column and the value, the value of your column. So you can access those values via
iteration (foreach)
iteration (index - direct access if you know the position of your element inside the array)
key (direct access without knowing the position of your element inside the array)

Assuming you want to loop the columns in each row, as opposed to manually echoing them as alkis suggests, get the results as an associative array and then unset $row['uniqID'];
if ($arch = $pdo->prepare("SELECT name, age, uniqID FROM table WHERE id = ?")) {
$arch ->execute(array($id));
$data = $arch->fetch(PDO::FETCH_ASSOC);
echo '<div class="coolTable" ><form method="post" action="delete.php"><table><tr><td>Name</td><td>Age</td><td>Check</td></tr>';
foreach ($data as $row){
if ( isset($row['uniqID']) ) {
unset($row['uniqID']);
}
echo '<tr>';
foreach ($row as $col){
$col = nl2br($col);
echo '<td>'.$col.'</td>';
}
echo '<td><input type="checkbox" name="checkbox[]" value="'.$col.'" id="checkbox"></td>'; //this captures the column ID so I can pass it through the `POST`
echo '</tr>';
}
echo '</table><input type="submit" value="Delete Selected"/></form></div>';
}

Related

php submit only giving last value from array that populates form

Struggling with a one page form that i want to first populate a form from a mysql query, then enable a user to update some of the values in each of several table rows from text input fields in the form.
The code's intent is to update the field by referencing the row ID.
But for some reason I'm only able to update the last row in the form (the last row from the array). I've included some troubleshooting code to see what the ID variable is and it always comes up as the last iteration of the array. I think I'm either overwriting the ID variable in the while loop or the for loop.
I have tried moving the POST/update to a 2nd file but get the same results. Any thoughts/suggestions would be greatly appreciated
Here is the code minus the db connection:
$saveClicked = $_POST["saveClicked"];
{ // SAVE button was clicked
if (isset($saveClicked)) {
unset($saveClicked);
$ID = $_POST["ID"];
$win = $_POST["Winner"];
$winScr = $_POST["WinnerScore"];
$losScr = $_POST["LoserScore"];
$tschedule_SQLupdate = "UPDATE tschedule SET ";
$tschedule_SQLupdate .= "Winner = '".$win."', ";
$tschedule_SQLupdate .= "WinnerScore = '".$winScr."', ";
$tschedule_SQLupdate .= "LoserScore = '".$losScr."' ";
$tschedule_SQLupdate .= "WHERE ID = '".$ID."' ";
if (mysql_query($tschedule_SQLupdate)) {
echo '<p> the number of mysql affected rows is '.mysql_affected_rows().'</p>';
echo 'this is the value for post id '.$ID;
} else {
echo '<span style="color:red; ">FAILED to update the game.</span><br /><br />';
echo mysql_error();
}
}
// END: SAVE button was clicked ie. if (isset($saveClicked))
}
{ // Get the details of all associated schedule records
// and store in array: gameArray with key >$indx
$indx = 0;
$tschedule_SQLselect = "SELECT * ";
$tschedule_SQLselect .= "FROM ";
$tschedule_SQLselect .= "tschedule ";
$tschedule_SQLselect .= "WHERE week = 1 ";
$tschedule_SQLselect_Query = mysql_query($tschedule_SQLselect);
while ($row = mysql_fetch_array($tschedule_SQLselect_Query, MYSQL_ASSOC)) {
$gameArray[$indx]['ID'] = $row['ID'];
$gameArray[$indx]['Date'] = $row['Date'];
$gameArray[$indx]['week'] = $row['week'];
$gameArray[$indx]['Favorite'] = $row['Favorite'];
$gameArray[$indx]['Line'] = $row['Line'];
$gameArray[$indx]['Underdog'] = $row['Underdog'];
$gameArray[$indx]['OU'] = $row['OU'];
$gameArray[$indx]['Winner'] = $row['Winner'];
$gameArray[$indx]['WinnerScore'] = $row['WinnerScore'];
$gameArray[$indx]['LoserScore'] = $row['LoserScore'];
$indx++;
}
$numGames = sizeof($gameArray);
mysql_free_result($tschedule_SQLselect_Query);
}
{ // Output
echo '<form name ="postGame" action="'.$thisScriptName.'" method="post">';
echo '<table border="1">';
echo '<tr>
<th>ID</th>
<th class="date">Date</th>
<th class="num">Week</th>
<th>Favorite</th>
<th class="num">Line</th>
<th>Underdog</th>
<th class="num">OU</th>
<th>Winner</th>
<th>WScore</th>
<th>LScore</th>
<th>Save</th>
</tr> ';
for ($indx = 0; $indx < $numGames; $indx++) {
$thisID = $gameArray[$indx]['ID'];
$saveLink = '<input type = "submit" value = "Save" />';
$fld_ID = '<input type="text" name="ID" value="'.$thisID.'"/>';
$fld_saveClicked = '<input type="hidden" name="saveClicked" value="1"/>';
echo $fld_ID;
echo $fld_saveClicked;
echo '<tr>
<td>'.$gameArray[$indx]['ID'].'</td>
<td>'.$gameArray[$indx]['Date'].'</td>
<td>'.$gameArray[$indx]['week'].'</td>
<td>'.$gameArray[$indx]['Favorite'].'</td>
<td>'.$gameArray[$indx]['Line'].'</td>
<td>'.$gameArray[$indx]['Underdog'].'</td>
<td>'.$gameArray[$indx]['OU'].'</td>
<td><input type="text" size =5 name="Winner">'.$gameArray[$indx]['Winner'].'</td>
<td><input type="number" size=5 name="WinnerScore">'.$gameArray[$indx]['WinnerScore'].'</td>
<td><input type="number" size=5 name="LoserScore">'.$gameArray[$indx]['LoserScore'].'</td>
<td>'.$saveLink.'</td>
</tr> ';
}
echo '</table>';
echo '</form>';
echo' View Schedule';
}
You're using the same names for each field in each row, so when you post the form, only the last is accessible. Use array notation for the fields like this:
<input type="text" size =5 name="Winner[]">
^^
This will give you an array for $_POST['Winner'] instead of a single value. Do the same for the other <input> elements.
Also, the code that processes the form after it's submitted only processes one value. You'll need to modify that to loop through these arrays.
Warnings:
don't use mysql_*() for new code - it's depracated. Switch to mysqli_*() or PDO now.
Your code is susceptible to SQL injection. Escape your input variables with mysql_real_escape_string() (or the mysqli equivalent) or better, switch to prepared statements.
After some more research I think I understand the two answers already shared much better. However I have chosen a different path and have resolved my issue -I wrapped the form tags directly around each row:
echo '<form name ="postGame'.$indx.'" action="'.$thisScriptName.'" method="POST">';
$fld_saveClicked = '<input type="hidden" name="saveClicked" value="1"/>';
echo $fld_saveClicked;
$fld_ID = '<input type="text" name="ID" value="'.$thisID.'"/>';
echo $fld_ID;
echo '<tr>
<td>'.$gameArray[$indx]['ID'].'</td>
<td>'.$gameArray[$indx]['Date'].'</td>
<td>'.$gameArray[$indx]['week'].'</td>
<td>'.$gameArray[$indx]['Favorite'].'</td>
<td>'.$gameArray[$indx]['Line'].'</td>
<td>'.$gameArray[$indx]['Underdog'].'</td>
<td>'.$gameArray[$indx]['OU'].'</td>
<td><input type="text" size=5 name="Winner" id="Winner">'.$gameArray[$indx]['Winner'].'</td>
<td><input type="number" size=5 name="WinnerScore" id="WinnerScore">'.$gameArray[$indx]['WinnerScore'].'</td>
<td><input type="number" size=5 name="LoserScore" id="LoserScore">'.$gameArray[$indx]['LoserScore'].'</td>
<td><button type="submit" />Save</button></td>
</tr></form>';
}
One of the key trouble shooting steps was to use var_dump to validate that the $_POST actually contained data. I understand there are several ways this could be done including the responses shared by Hobo and Syed, as well as using javascript, but was really glad I could accomplish my goal with just php.
Your For Loop is storing the last value of the array in your form.
$fld_ID = '<input type="text" name="ID" value="'.$thisID.'"/>';
Store the ID value as an array in HTML form and when a form is posted get all the ID values and update using your same mysql update query.
Your winner and loser score are also returning the last array values.

form with array of checkboxes send incomplete data

I try to pass a form which contains other forms (same inside forms, dynamic) , but I have checked that the data which are sent to the 'script handler' (php) are incomplete data. I think somewhere buffer is overwriting or something. Here is the code :
<?php
if(isset($_POST['submit_num']))
{
$number=$_POST['sky'];
if($number== 0)
{
header('Location: /ceid_coffee/user_order_form.php');
}
else
{
$_SESSION['number'] = $number;
echo '<form action="user_order_form.php" method="POST">';
for($i=0;$i<$number;$i++)
{
$item = $_SESSION['item'];
echo $item;
$rec_query = "SELECT * FROM ylika";
$rec_result= mysql_query($rec_query) or die("my eroors");
while($row_rec = mysql_fetch_array($rec_result))
{
echo '<br>';
echo '<input type="checkbox" name="yliko[][$i]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';//<~~~~this line is form's data
}
echo '<br>';
}
echo '<input type="submit" name="submit" value="FINAL_ORDER">';
echo '</form>';
}
}
?>
And this is the handling script:
<?php
if (isset($_POST['submit']))
{
$number= $_SESSION['number'];
$item = $_SESSION['item'];
$max_id = "SELECT MAX(id_order) FROM id_of_orders";
$x=mysql_query($max_id) or die("my eroors");
$id= mysql_fetch_array($x);
$xyz = $id['MAX(id_order)'];
for($i=0;$i<$number;$i++)
{
$temp = $_POST['yliko'][$i]; // <~~~~ this line is the form's data
$temp2 = implode("," , $temp);
$inserts = ("INSERT INTO orders (order_id,product,ulika) VALUES ('$xyz' , '$item','$temp2')");
$inc_prod=("UPDATE proion SET Counter = Counter + 1 WHERE proion.onomasia='$item'");
mysql_query($inserts) or die(mysql_error());
mysql_query($inc_prod) or die(mysql_error());
}
}
?>
This line here contains the data of each form , but i have echo them ($temp2) and i saw that they are incomplete.
$temp = $_POST['yliko'][$i];
If i select more than 1 checkbox for each item ($i) I get only one value from the checkboxes into the sql.
Do you see if I miss something ?
Ok i found the error. I replace this row :
echo '<input type="checkbox" name="yliko[][$i]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';//<~~~~this line is form's data
with this row :
echo '<input type="checkbox" name="yliko['.$i.'][]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';
I do not know how (i'm new to php) but it worked.
You will only get one value for each form because you are assigning the value of $i to each one:
echo '<input type="checkbox" name="yliko[][$i]" value='. etc.
is your problem line.
Have a look at the HTML that your code produces (ctrl-u in most browsers) and you will see why you get the wrong answer. All your checkboxes need to have unique names.
I would do it by assigning each checkbox a name that relates to the line in the database from which they are drawn eg:
name="checkbox_"'.$row['ylikaprimarykey']."etc.
This will get you up and running fairly quickly. For what it is worth, the ids of your table keys can give attackers information about your site so it is best practice to obfuscate them in some way. There are a number of excellent classes available free on the net that will do this for you.
If you really need to deal with what would have been in each form as a separate chunk of data, you can easily change the checkbox names vis:
name="checkbox_$formnumber_$obfuscatedkeynumber"
then loop through them with nested loops in your handling page.

PHP retrieving content of database

I have a database with a few tables in it. The table i'm working on has 6 columns in it,
school_id, title, location, content, class_date and user_id
The school_id is unique (ranging from 1-20) and there are 4 different user_id (ranging from 1-4).....I'm working on a site which has a table that displays the information about the user and it's correspondence. I have a ReadMore link in the last column of the displayed table, my question is this, when I click the ReadMore link I want it to display the content field in the database based on which event is clicked.
For the login, the user is asked their user_id as their password.
//$T is called from a previous page which is the user_id or the password
$T = $_SESSION["ID"];
$INFO= $dbc->query("SELECT content FROM events where school_id='$T'");
$a = $INFO->fetch();
$b = $a['content'];
print_r($b);
THE ABOVE CODE IS HOW I TRY TO PRINT OUT THE CORRECT CONTENT BUT ONLY THE FIRST INSTANCE IS PRINTED OUT
THE BELOW CODE IS HOW THE TABLE IS DISPALYED ON MY SITE
<?php
$gold= $dbc->query("SELECT * FROM events WHERE user_id='$idcheck' ORDER BY event_dateLIMIT 10");
$x = $gold->fetchAll();
echo "<table border = '1'>";
echo "<tr>
<td> Event </td>
<td> Date of Event </td>
<td> Location </td>
<td> Event Information</td>
</tr>";
foreach ($r as $back) {
$title = $back['title'];
$eventdate = $back['class_date'];
$location = $back['location'];
echo "<tr>";
echo "<td>$title</td>";
echo "<td>$eventdate</td>";
echo "<td>$location</td>";
echo "<td>";
?>
<form action="displaycontent.php" method="post">
<input type="submit" value="Read More">
</form>
<?php
echo "</td>";
echo "</tr>";
}
echo "</table>";
?>
fetch method returns next found row from your statement. You have to iterate over your result to get all rows.
Something like
while ($row = $INFO->fetch()) {
$b[] = $row;
}
Then have a look at print_r($b). It should look like
array(0=>array('content'=>'Some content1'),
1=>array('content'=>'Some content2'), ....)
And your way of outputting the result should work.

Two values from an array checkbox

So I have a mysql table for the charges of a hospital. My program currently only gets the price of the checked procedure. But now, I also want to get the procedure name when it is checked.
transaction.php
while($row = mysql_fetch_array($result))
{
echo ' <tr> <td>'.$row[0].'</td> <td>'.$row[1].'</td><td>'.$row[2].'</td>';
$procedure=$row['procedure'];
echo '<td><input type="checkbox" name="er[]" value="$price."|".$procedure"></td>';
echo "</tr>";
}
echo '</table>';
computation.php
<?php
if(isset($_POST['er']))
{
$ercharge=$_POST['er'];
$totalofer = array_sum($ercharge);
}
if(isset($_POST['ultrasound']))
{
$x=$_POST['ultrasound'];
$totalofultrasound = array_sum($x);
}
if(isset($_POST['confinement']))
{
$y=$_POST['confinement'];
$totalofconfinement = array_sum($y);
}
$total = $totalofer + $totalofultrasound + $totalofconfinement;
$p = explode("|", $ercharge);
echo $p;
echo $total;
?>
It only gets the row for price. Can the value attribute have two values? I can't just make another checkbox cause that would be inappropriate.
edit: the explode function doesnt work. It says: Warning: explode() expects parameter 2 to be string, array given in C:\xampp\htdocs\computation.php on line 18
You should split your parameters in the HTML:
echo '<td><input type="checkbox" name="checked[$row_index][]" value="1">';
echo '<input type="hidden" name="prices[$row_index][]" value="$price">';
echo '<input type="hidden" name="procedures[$row_index][]" value="$procedure"></td>';
where $row_index is incremented on each row (tr tag)
By the way, explode will work on the items of the er array, not on the array itself. Try:
foreach ($er as $item) {
var_dump( explode( "|", $item ) );
}
I'm not sure I understand your question but couldn't you set the name attrtibute for your checkbox to the name of the procedure? It looks like you are setting the name to the er[] array but you never reference that later.

I need this script to print the id field one per iteration no all row by iterations help

I don't know how to set up that the id field to print one by one per row in the script below which works wonders.
$tree = array();
$sql = "select * from products
left join product_varieties on product_varieties.product_id = products.id";
$sth = query($sql);
while($row = fetch($sth)) {
$id = $row['id'];
$tree[$id]['name'] = $row['name'];
if($row['variety'])
$tree[$id]['varieties'][] = $row;
}
foreach($tree as $product)
<div>
echo $product['name']
foreach($product['varieties'] as $variety)
etc etc
</div>
I have been trying to use the id generated in the while loop inside the form action url string inside the foreach parent as you use the name index in the partent foreach. I have tried echoing and printing some how it won't display the id or if I print it, then it will appear three rows of ids per rows like 111333444555, I just want to be able to have the id per row like echo $product['name'] does, each iteration only prints one row of the index [ 'name'].
The form below won't echo anything, and I I change it to print then it will print 111222333444 help..
foreach($tree as $product){
<form action="cart.php?id="'. echo $product['id']. '">
</form>
<div> echo $product['name'] echo $procude['id']
foreach($product['varieties'] as $variety) {
etc etc
</div>
}
}
not sure i understand correctly what you want.. but let me try:
foreach($tree as $id=>$product){
echo "<div>".$id." ".$product['name'];
foreach($product['varieties'] as $variety){
// whatever
}
echo "</div>";
}

Categories