How can i use $_POST if the name is a variable? - php

I have a button that generates after each table row is generated in the loop, the name of each consecutive button is generated by $a++ variable. How do i use the $_POST method on my edit_contact.php page so i can use the variable from the $_POST array?
The variable is stored in the $_POST array, i have checked with Print_r($_POST); for example when i click on the third row edit button of the table, it will display as:
Array ( [3] => edit )
Here is the code of the loop on my list_contact.php page:
$a = "0";
// print whether success or not
if ($rst)
{
if (mysql_num_rows($rst)>0) // chech there are records
{
echo "<form name=addcontact method=post action=edit_contact.php>";
echo "<table border=\"1\" cellspacing=\"0\">";
/*** print out feild names ***/
while ($row = mysql_fetch_array($rst)) // fetch each row
{
echo "<tr>";
for ($i=0; $i<mysql_num_fields($rst); $i++) //for ech row print out field values
{
echo "<td>" . $row[$i] . "</td>";
}
echo "<td>" . "<input id=button type=submit name=" . $a++ . " value=Edit" . "</td>";
echo "</tr>";
}
echo "</table>";
echo "</form>";
}
else
{
echo "There are no records in the database";
}
}
And here is the code i am having trouble with on my edit_contact.php:
$qry = "SELECT * FROM contacts WHERE ContactID = " . $_POST;
How can i get that post to reflect just my variable? ie 3

You can do it once. You don't need any more fields. Just use foreach to access its key
foreach($_POST as $key => $value){
if(strtolower(trim($value)) == "edit"){ // Validate if editing being sent
// Display it if true
echo $key; // and this is the variable you want
}
}

you could use a hidden input field so instead of:
echo "<td>" . "<input id=button type=submit name=" . $a++ . " value=Edit" . "</td>";
you could do:
echo '<td><form method="post"><input type="hidden" name="ContactID" value="'.($a++).'"><input id="button" type="submit" value="Edit"></form></td>';
then retrieve the hidden input field like:
$ContactID = $_POST['ContactID'];
Note: You will still need to properly escape your POST data before using it for SQL queries, but hopefully this will point you in the right direction.

Restructure the code so that the name is actually a constant, and the value is dynamic.
echo "<td><input id=button type=submit name=\"edit\" value=\"" . $a++ . "\"></td>";
This way you can access it with:
$_POST['edit'];
And it will yield the value of: value=\"" . $a++ . "\" for the button that was clicked.
Which will return something like 3, as you desire.

Related

How do I update a row of data with a button click

First of all I am kind of new to PHP.
I've been asked to change up a bit of code and add the option to see the status of a field and mark the rows which are completed. So I've added a status field to my MySQL database which has a standard value of 0. Then on button click I'd like this to change to the value 1. Based on this I can either project a cross glyph icon with a button to update this, or project a checkmark so that the status is "done".
Now I'm having issues with the update part. I just cannot seem to get it to work with clicking the button and updating only that row. Field "prdh_num" is my unique value if that is usefull.
Here's the code I work with:
function uren_error(){
global $mysql;
$sql = "
SELECT *
FROM uren_error, medw
WHERE uren_error.uren_datum between adddate(now(),-14) and now() AND medw.medw_num = uren_error.medw_num
ORDER BY uren_error.prdh_num";
$query = $mysql->query($sql);
echo "<h1>Niet in MKG verwerkte uren van de afgelopen 14 dagen</h1>";
echo "<div class='row' id='urenTabel'>";
echo "<div class='col-xs-0 col-md-0'></div>";
echo "<div class='col-xs-12 col-md-12'>";
echo "<table class='table'>";
echo "<thead>";
echo "<th>Verwerkingsdatum</th>";
echo "<th>Medewerker</th>";
echo "<th>Productieorder</th>";
echo "<th>Productieorder regel</th>";
echo "<th>Bewerking</th>";
echo "<th>Duur</th>";
echo "<th>Status</th>";
echo "<th>Actie</th>";
echo "</thead>";
while($row = mysqli_fetch_array($query)){
$hours = floor($row['uren_tijd_man_std'] / 3600);
$mins = floor($row['uren_tijd_man_std'] / 60 % 60);
echo "<tr>";
echo "<td>" .$row['uren_datum']. "</td>";
echo "<td>" .$row['medw_roepnaam'] . " " . $row['medw_tussenvoegsel'] . " " . $row['medw_naam'] . "</td>";
echo "<td>" .$row['prdh_num']. "</td>";
echo "<td>" .$row['prdr_num']. "</td>";
echo "<td>" .$row['bewerk_num']. "</td>";
echo "<td>" .$hours.":".$mins. "</td>";
if($row['uren_status'] == "0"){
echo "<td><div class='glyphicon glyphicon-remove' style='color:red'></div></td>";
echo "<td><form action'' method='POST'><input type='submit' name=".$row['prdh_num']."></input></form></td>";
} else if($row['uren_status'] == "1"){
echo "<td><div class='glyphicon glyphicon-ok' style='color:green'></div></td>";
}
echo "</tr>";
}
echo "</table>";
}
my update code so far:
$productieorder = $row['prdh_num'];
$updateStatus = "UPDATE uren_error SET uren_status = 1 WHERE prdh_num=".$productieorder."";
$query2 = $mysql->query($updateStatus);
In more simple way you can use <a> tag to update your record ,instead of <form> , just attached your parameter which you need to passed . i.e :
echo "<td><a href='currentphppagename.php?prdh_num=".$row['prdh_num']."'></a></td>";
And to get prdh_num use $_GET on same page i.e :
//check if have some value or not
if (isset($_GET['prdh_num'])) {
//getting value passed in url
$productieorder = $_GET['prdh_num'];
$updateStatus = "UPDATE uren_error SET uren_status = 1 WHERE prdh_num=".$productieorder."";
$query2 = $mysql->query($updateStatus);
}
And other way using form you can have one hidden field and assign row value to that :
echo "<td><form action='' method='POST'><input type='hidden' value=".$row['prdh_num']." name='prdh_num'/><input type='submit' name='submit'></input></form></td>";
Now on click of submit check below on same page :
//check if have some value or not
if (isset($_POST['submit'])) {
//getting value passed in url
$productieorder = $_POST['prdh_num'];
$updateStatus = "UPDATE uren_error SET uren_status = 1 WHERE prdh_num=".$productieorder."";
$query2 = $mysql->query($updateStatus);
}
You can do this with javascript. You should put "ondblclick" event on tr tag.
<tr ondblclick="Update(rowno)" />
And in javascript tag, there must be a function like
<script type="text/javascript">
function Uptdate(row) {
window.location.href ="update.php?row="+row;
}
</script>

Retrieve data from sql database and display in tables - Display certain data according to checkboxes checked

I have created an sql database(with phpmyadmin) filled with measurements from which I want to call data between two dates( the user selects the DATE by entering in the HTML forms the "FROM" and "TO" date) and display them in a table.
Additionally I have put, under my html forms, some checkboxes and by checking them you can restrict the amount of data displayed.
Each checkbox represent a column of my database; so along with the date and hour column, anything that is checked is displayed(if none is checked then everything is displayed).
So far I managed to write a php script that connects to the database, display everything when none of my checkboxes is checked and also managed to put in order one of my checkboxes.
Problem: The data that I call for are been displayed twice.
Question: I want to have four checkboxes.
Do I need to write an sql query for every possible combination or there is an easier way?
<?php
# FileName="Connection_php_mysql.htm"
# Type="MYSQL"
# HTTP="true"
$hostname_Database_Test = "localhost";
$database_Database_Test = "database_test";
$table_name = "solar_irradiance";
$username_Database_Test = "root";
$password_Database_Test = "";
$Database_Test = mysql_pconnect($hostname_Database_Test, $username_Database_Test, $password_Database_Test) or trigger_error(mysql_error(),E_USER_ERROR);
//HTML forms -> variables
$fromdate = $_POST['fyear'];
$todate = $_POST['toyear'];
//DNI CHECKBOX + ALL
$dna="SELECT DATE, Local_Time_Decimal, DNI FROM $database_Database_Test.$table_name where DATE>=\"$fromdate\" AND DATE<=\"$todate\"";
$tmp ="SELECT * FROM $database_Database_Test.$table_name where DATE>=\"$fromdate\" AND DATE<=\"$todate\"";
$entry=$_POST['dni'];
if (empty($entry))
{
$result = mysql_query($tmp);
echo
"<table border='1' style='width:300px'>
<tr>
<th>DATE</th>
<th>Local_Time_Decimal</th>
<th>Solar_time_decimal</th>
<th>GHI</th>
<th>DiffuseHI</th>
<th>zenith_angle</th>
<th>DNI</th>
";
while( $row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $row['DATE'] . "</td>";
echo "<td>" . $row['Local_Time_Decimal'] . "</td>";
echo "<td>" . $row['Solar_Time_Decimal'] . "</td>";
echo "<td>" . $row['GHI'] . "</td>";
echo "<td>" . $row['DiffuseHI'] . "</td>";
echo "<td>" . $row['Zenith_Angle'] . "</td>";
echo "<td>" . $row['DNI'] . "</td>";
echo "</tr>";
}
echo '</table>';}
else
{
$result= mysql_query($dna);
echo
"<table border='1' style='width:300px'>
<tr>
<th>DATE</th>
<th>Local_Time_Decimal</th>
<th>DNI</th>
";
while($row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $row['DATE'] . "</td>";
echo "<td>" . $row['Local_Time_Decimal']."</td>";
echo "<td>" . $row['DNI'] . "</td>";
echo "</tr>";
}
echo '</table>';
}
if($result){
echo "Successful";
}
else{
echo "Enter correct dates";
}
?>
<?php
mysql_close();
?>
Try to create your checkbox like below:
Solar_Time_Decimal<checkbox name='columns[]' value='1'>
GHI<checkbox name='columns[]' value='2'>
DiffuseHI<checkbox name='columns[]' value='3'>
Zenith_Angle<checkbox name='columns[]' value='4'>
DNI<checkbox name='columns[]' value='5'>
And try to hange your PHP code to this:
<?php
//HTML forms -> variables
$fromdate = isset($_POST['fyear']) ? $_POST['fyear'] : data("d/m/Y");
$todate = isset($_POST['toyear']) ? $_POST['toyear'] : data("d/m/Y");
$all = false;
$column_names = array('1' => 'Solar_Time_Decimal', '2'=>'GHI', '3'=>'DiffuseHI', '4'=>'Zenith_Angle','5'=>'DNI');
$column_entries = isset($_POST['columns']) ? $_POST['columns'] : array();
$sql_columns = array();
foreach($column_entries as $i) {
if(array_key_exists($i, $column_names)) {
$sql_columns[] = $column_names[$i];
}
}
if (empty($sql_columns)) {
$all = true;
$sql_columns[] = "*";
} else {
$sql_columns[] = "DATE,Local_Time_Decimal";
}
//DNI CHECKBOX + ALL
$tmp ="SELECT ".implode(",", $sql_columns)." FROM $database_Database_Test.$table_name where DATE>=\"$fromdate\" AND DATE<=\"$todate\"";
$result = mysql_query($tmp);
echo "<table border='1' style='width:300px'>
<tr>
<th>DATE</th>
<th>Local_Time_Decimal</th>";
foreach($column_names as $k => $v) {
if($all || (is_array($column_entries) && in_array($k, $column_entries)))
echo "<th>$v</th>";
}
echo "</tr>";
while( $row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $row['DATE'] . "</td>";
echo "<td>" . $row['Local_Time_Decimal'] . "</td>";
foreach($column_names as $k => $v) {
if($all || (is_array($column_entries) && in_array($k, $column_entries))) {
echo "<th>".$row[$v]."</th>";
}
}
echo "</tr>";
}
echo '</table>';
if($result){
echo "Successful";
}
else{
echo "Enter correct dates";
}
?>
<?php
mysql_close();?>
This solution consider your particular table columns but if your wish a generic solution you can try to use this SQL too:
$sql_names = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '$database_Database_Test' AND TABLE_NAME = '$table_name'";
and use the result to construct the $column_names array.
Solution for your problem : Change the mysql_fetch_assoc with mysql_fetch_array
If you have the same problem try to print your result with print_r
Answer : Use the bit datatype in mysql for store and read your checkboxes.
When you're receiving thr value from the database then you can use
in the parameter checked you can use the php code as exist :
$value = ...get the value from db ( 1 or 0 )
echo '<input type="checkbox" name="thename" value="thevalue" '.($value==1?'checked=checked'.'').'/>';

Couldn't display a second word in my database output

I have a strange problem here.
I'm doing a admin page to edit movie info. I have a movie for exemple called "Blood Diamonds" in my database, but on the oage it only show "Blood" without the second word "diamonds", I couldnt find whyyy.
require('../classes/movie_class.php');
$moviecinemas = movie::get_movie_info( $_GET['movie_id']);
foreach ($moviecinemas as $movie)
{
$movie_id = $movie['movie_id'];
$movie_name = $movie['movie_name'];
$movie_category = $movie['movie_category'];
$movie_display = $movie['movie_display'];
echo "<input name='movieid' type='hidden' id='movieid' value=" . $movie_id . '><br/>';
echo "Movie Name :";
echo "<input name='moviename' type='text' id='moviename' value=" . $movie_name . '><br/>';
echo "Movie Category :";
echo "<input name='moviecategory' type='text' id='moviecategory' value=" . $movie_category . '><br/>';}
?>
In the class page :
public static function get_movie_info($movie_id)
{
$query = mysql_query(
"SELECT *
FROM movie
WHERE movie_id = {$movie_id}"
);
while( $movie = mysql_fetch_assoc( $query ) )
{
$results[] = $movie;
}
return $results;
}
The value property in your input tags should have quotes surrounding the movie name. Otherwise, when there's a space, it interprets the next words as more properties of the input.
echo "<input name='moviename' type='text' id='moviename' value='" . $movie_name . "'><br/>";
Your HTML tags are not set properly, missing " in value attribute :
replace
echo "<input name='moviename' type='text' id='moviename' value=" . $movie_name . '><br/>';
by
echo "<input name='moviename' type='text' id='moviename' value=" . $movie_name . '"><br/>';
In addition you should probably encode values so that a " in a database value will not corrupt your html code (htmlentities for instance).

Updating MYSQL DB with checkbox and textarea data (in PHP)

I'm using a table to update a database, the table has 264 checkboxes which can be checked and unchecked then updated on the database.
I'm doing this by posting data on the form, using a while loop to set all fields to blank ( the value of the checkbox and the textarea value) for each respective field, then using a foreach loop to update each row in the database with the value of the checkbox.
Now, what I want to do is add the textarea value for each ticked checkbox into the database as well, what i cant figure out is how to do this?
This is my update code:
if (isset($_POST["update"])) {
$seolistRes2 = mysql_query($seolistQ) or die(mysql_error());
while ($seolistRow2 = mysql_fetch_array($seolistRes2)) {
$wsID1 = $seolistRow2["worksheetID"];
$updateWSQ2 = "UPDATE seo_work SET taskValue=0, taskInfo='' WHERE worksheetID=$wsID1 AND userID=$userID";
mysql_query($updateWSQ2) or die(mysql_error());
}
$item = $_POST;
foreach($item as $key => $value) {
$wsID = str_replace("checkbox","",$key);
if (is_numeric($wsID)) {
$updateWSQ = "UPDATE seo_work SET taskValue=$value taskInfo=$value WHERE worksheetID=$wsID AND userID=$userID";
mysql_query($updateWSQ) or die(mysql_error());
header("Location: worksheet.php?y=".$seoworkyear."&userID=$userID&action=success");
}
}
}
This is checkbox and textarea code: (please note this is within a form)
$currentTask = '';
echo "<tr class='tr'>";
while ($seolistRow = mysql_fetch_array($seolistRes)) {
$taskValue = $seolistRow["taskValue"];
$worksheetID = $seolistRow["worksheetID"];
$taskName = $seolistRow["taskName"];
$taskInfo = $seolistRow["taskInfo"];
if ($taskValue == 1) {
$taskDone = "<input type='checkbox' value='1' class='checkbox' name='checkbox".$worksheetID."' id=checkbox'".$worksheetID."' checked='checked' />".
"<textarea class='textarea' name='textarea".$worksheetID."' id=textarea'".$worksheetID."'>" . $taskInfo . "</textarea>";
}
else {
$taskDone = "<input type='checkbox' value='1' class='checkbox' name='checkbox".$worksheetID."' id='checkbox".$worksheetID."' />".
"<textarea class='textarea' name='textarea".$worksheetID."' id=textarea'".$worksheetID."'>" . $taskInfo . "</textarea>";
}
if ($currentTask != $taskName) {
echo "</tr>";
echo "<tr class='tr'>";
echo "<td class='task'>".$taskName."</td>";
}
echo "<td class='tick'>".$taskDone."</td>";
$currentTask = $taskName;
}
echo "</tr>";
Use your HTML form like shown below.
$currentTask = '';
echo "<tr class='tr'>";
while ($seolistRow = mysql_fetch_array($seolistRes)) {
$taskValue = $seolistRow["taskValue"];
$worksheetID = $seolistRow["worksheetID"];
$taskName = $seolistRow["taskName"];
$taskInfo = $seolistRow["taskInfo"];
if ($taskValue == 1) {
$taskDone = "<input type='checkbox' value='1' class='checkbox' name='checkbox[".$worksheetID."]' id='checkbox[".$worksheetID."]' checked='checked' />".
"<textarea class='textarea' name='textarea[".$worksheetID."]' id='textarea[".$worksheetID."]'>" . $taskInfo . "</textarea>";
}
else {
$taskDone = "<input type='checkbox' value='1' class='checkbox' name='checkbox[".$worksheetID."]' id='checkbox[".$worksheetID."]' />".
"<textarea class='textarea' name='textarea[".$worksheetID."]' id='textarea[".$worksheetID."]'>" . $taskInfo . "</textarea>";
}
if ($currentTask != $taskName) {
echo "</tr>";
echo "<tr class='tr'>";
echo "<td class='task'>".$taskName."</td>";
}
echo "<td class='tick'>".$taskDone."</td>";
$currentTask = $taskName;
}
echo "</tr>";
See the modified name and id of your textarea and checkbox. I have modified it to textarea[SOME_WORKSHEET_ID] and checkbox[SOME_WORKSHEET_ID] respectively.
So, when you submit the form, you will receive those checkbox and textarea value as an array, with worksheetId as an index. You can use this [] technique to retrieve the values of the textarea and checkbox, or as many field you want to add in form.
Use above HTML structure and check the $_POST array.
Hope this will help..
Thanks!
Hussain.
You should be able to get the value in the textarea using $_POST['textarea' . $wsID] after your call to is_numeric.
Here is another approach, not completely tested, but hopefully you get the idea...
if (isset($_POST["update"]))
{
// All to blank
$seolistRes2 = mysql_query($seolistQ) or die(mysql_error());
while ($seolistRow2 = mysql_fetch_array($seolistRes2))
{
$wsID1 = $seolistRow2["worksheetID"];
$updateWSQ2 = "UPDATE seo_work SET taskValue=0, taskInfo='' WHERE worksheetID=$wsID1 AND userID=$userID";
mysql_query($updateWSQ2) or die(mysql_error());
}
// Re use your result from the select to go through all the known IDs
foreach($seolistRow2 as $i => $data)
{
// Obtain the ID
$id = $data['worksheetID'];
// Get the checkbox value for current ID
$checkbox_wsID = $_POST['checkbox' . $id];
// Get the textarea value for current ID
$textarea_wsID = $_POST['textarea' . $id];
// Update the Row using mysql_escape
$updateWSQ = "UPDATE seo_work " .
"SET taskValue = '" . mysql_escape_string($checkbox_wsID) ."' taskInfo = '" . mysql_escape_string($textarea_wsID) ."'" .
"WHERE worksheetID=$id AND userID=$userID";
mysql_query($updateWSQ)
or die(mysql_error());
header("Location: worksheet.php?y=".$seoworkyear."&userID=$userID&action=success");
}
}

How can I send over multiple check box checks in POST to be deleted from a database?

I've been trying think of a way to do this. I want it to where users can check off items, hit submit and it goes to the code on the next page and deletes all of the checked items from the database. Problem one is that in the post its only sending over the last checked item. Here is how I have it set up right now.
echo "<form name='fm1' METHOD ='POST' ACTION ='displaydelete.php' > ";
//Draws up the table headers
echo "";
echo "";
echo "Fund Number ";
echo "Hours ";
echo "Percentage";
echo "Delete";
echo "";
//While there are query results data is pushed into table cells
while ($row = mysql_fetch_array($queryResult2))
{
$hours = $row['hours'];
$percentage = $hours / 160 * 100;
echo "<tr>";
echo "<td>";
echo $row['funnumber'];
echo "</td>";
echo "<td>";
echo $hours;
echo "</td>";
echo "<td>";
echo $percentage ."%";
echo "</td>";
echo "<td>";
echo "<input type='checkbox' name='id' value='$row[id]'/>";
echo "</td>";
echo "</tr>";
}
//End of tabel
echo "</table>";
echo" ";
echo "";
What I would like to do is push all of the items into a variable and maybe delete them that way. I'm not really sure how you would handle multiple deletes. I'm doing my delete like this for something else if this helps any.
$query = "DELETE FROM users
WHERE ninenumber = '$ninenumber'";
$result = mysql_query($query)
or die("Query Failed: " .mysql_error());
mysql_close($conn);
In your form:
<input type='checkbox' name='id[]' value='$row[id]'/>
Then, in the file you post to:
if(is_array($_POST['id'])){
foreach($_POST['id'] as $id){
...do something to $id;
}
}
Instead of this:
echo "<input type='checkbox' name='id' value='$row[id]'/>";
You need this:
echo "<input type='checkbox' name='id[]' value='$row[id]'/>";
Note the difference. I added [] after the input name. This tells the client and server that there are multiple inputs with that name. $_POST['id'] will be an array you can loop through on the next page.
foreach ($_POST['id'] as $checkbox) {
// DELETE FROM users WHERE ninenumber = $checkbox
}
isset, is_array, and mysql_real_escape_string omitted for brevity.
In the form-generating code, make the name in the html have" []" after it:
...
echo "<input type='checkbox' name='id[]' value='$row[id]'/>";
...
Then, in the form-reading code, your post'ed id will be an array.
$id_array = isset($_POST['id']) && is_array($_POST['id']) ? $_POST['id'] : array();
foreach( $id_array as $id ) {
$query = "DELETE FROM users WHERE ninenumber = '" . mysql_real_escape_string($id) . "'";
// execute the delete query
}
Putting [] after the name of a control will turn it into an array in the superglobal that you can then iterate over to get all the values from.
You need to have the same name for all of your checkboxes, then all values are passed as array POST variable.
<input type='checkbox' name='id[]' value='$row[id]'/>
Change
name=id
to
name=id[]
this will then give you an array.

Categories