Passing variable via submit button - php

Im loading content for my website from database. It loads data and fills a table.
My problem is that i have put a button next to each row. When i click on the button it has to show me the Name, Price ,Stock etc of every row.
When i click on the button i get an error.
Here you can find the code i have written in de document User_Koeken.php
<?php
if (isset($_POST[$ID]))
{
$URL = $_POST['S_URL'];
$Naam = $_POST['S_Naam'];
$Inhoud = $_POST['S_Inhoud'];
$Stock = $_POST['S_Stock'];
$Prijs = $_POST['S_Prijs'];
echo $URL."".$Naam."".$Inhoud."".$Stock."".$Prijs;
}
else
{$supermarket = mysql_connect("localhost", "root", "Password") or die(mysql_error());
mysql_select_db("supermarket", $supermarket);
$sql = " select * from koeken";
$result = mysql_query($sql, $supermarket);
while ($row = mysql_fetch_array($result)) {
$ID = $row['ID'];
$URL = $row['URL'];
$Naam = $row['Naam'];
$Inhoud = $row['Inhoud'];
$Stock = $row['Stock'];
$Prijs = $row['Prijs'];
$_SESSION['ID']=$ID;
echo "<form action='User_Koeken.php' method='post'>
<tr class='rien' >
<td name='S_URL'><a href=$URL><img src=$URL alt='product'></a></td>
<td name='S_Naam'>$Naam</td>
<td Name='S_Inhoud'>$Inhoud</td>
<td name='S_Stock'>$Stock</td>
<td name='S_Prijs'>€ $Prijs</td>
<td><input type='submit' value=$ID name='$ID'></td>
</tr>
</form> ";
}; }?>
Here you can find a picture of my code in color
http://postimg.org/image/n6wrb0d13/
http://postimg.org/image/n6wrb0d13/

$ID must be initialized before the line
if (isset($_POST[$ID]))
Otherwise, this will always return false, or an error.
Instead, use an array in your HTML names to catch the row being posted:
<tr class='rien' >
<td name='myform[S_URL]'><a href='$URL'><img src='$URL' alt='product'></a></td>
<td name='myform[S_Naam]'>$Naam</td>
<td Name='myform[S_Inhoud]'>$Inhoud</td>
<td name='myform[S_Stock]'>$Stock</td>
<td name='myform[S_Prijs]'>€ $Prijs</td>
<td><input type='submit' value='$ID' name='myform[id]'></td>
</tr>
and the PHP:
if (isset($_POST['myform']) ) {
$post = $_POST['myform'];
$ID = $post['id'];
$URL = $post['S_URL'];
....
}

Related

Failing to update the new data entered by administrator

Look like everything is working fine with this code but in fact fails to update the database, Data are displayed correctly while fetching data but when i press update Button the data disappear but no update has been executed. It look fine to me but seems i am wrong.
This is a project for my professor so i don't care for the SQL injection and others.
<html>
<head>
<link rel="stylesheet" type="text/css" href="btnstyle.css">
<title>Managament System</title>
</head>
<body>
<h1>TU Chemnitz Student managament system</h1>
<br>
ADD Person
Edit Person
Manage Boards
Manage Departments
Search N&S
Triple Search
Membership
<br>
<br>
<?php
// set database server access variables:
$host = "localhost";
$user = "";
$pass = "";
$db = "";
// open connection
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
// select database
mysql_select_db($db) or die ("Unable to select database!");
// create query
$querys = "SELECT * FROM tblperson";
// execute query
$result = mysql_query($querys) or die ("Error in query: $query. ".mysql_error());
echo "<table border=1 align=center>
<tr>
<th>Personal ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Deparment</th>
<th>Board</th>
<th>Marticulation Number</th>
<th>Reg Date</th>
<th>Action</th>
</tr>";
while($row = mysql_fetch_array($result)) {
?>
<?php
echo '<tr>';
echo '<td>'. $row['personid'].'</td>';
echo '<td>'. $row['personname'].'</td>';
echo '<td>'. $row['personsurname'].'</td>';
echo '<td>'. $row['persondepartment'].'</td>';
echo '<td>'. $row['personboard'].'</td>';
echo '<td>'. $row['martinumber'].'</td>';
echo '<td>'. $row['personregdate'].'</td>';
echo '<td>'.' EDIT '.'</td>';
}
?>
</body>
</html>
and this is the edit file which seems to problematic.
<?php
include_once('coneksioni.php');
if(isset($_GET['edit']))
{
$personid = $_GET['edit'];
$res = mysql_query("SELECT * FROM tblperson WHERE personid='$personid'");
$row = mysql_fetch_array($res);
}
if(isset($_POST['newpersonname']))
{
$newpersonname = $_POST['newpersonname'];
$personid = $_POST['personid'];
$sql = "UPDATE tblperson SET personname = '$newpersonname' WHERE personid = '$personid'";
$res = mysql_query($sql) or die ("Cant be updated");
echo "< meta http-equiv='refresh' content='0;url=home.php'>";
}
?>
<form action="edit20.php" method="POST">
<table border="0">
<tr>
<td>First Name</td>
<td><input type="text" name="newpersonname" value="<?php echo $row[1];?>" maxlength="30" size="13"></td>
</tr>
<tr>
<td>Last Name</td>
<td> <input type="text" name="personsurname" value="<?php echo $row[2];?>" maxlength="30" size="30"></td>
</tr>
<tr>
<td>Department</td>
<td>
<select name='persondepartment'>
<option>Production</option>
<option>Sales</option>
</select>
</td>
</tr>
<tr>
<td>Board</td>
<td>
<select name='personboard'>
<option>Evaluation</option>
<option>Executive</option>
<option>Research</option>
</select>
</td>
</tr>
<tr>
<td>Marticulation Number</td>
<td> <input type="text" name="martinumber" maxlength="60" size="30"></td>
</tr>
<tr>
<td>Date of Registration</td>
<td><input type="date" name="personregdate" maxlength="7" size="7"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value=" Update"></td>
</tr>
</table>
</form>
You are looking for personid when the Update button is pressed on the form in edit20.php but that value has never been set so it will be empty and the update will fail.
After
<form action="edit20.php" method="POST">
add:
<input type="hidden" name="personid" value="<?php echo $personid; ?>">
On edit page seem your confusing the same variable with different values. If you state $personid variable to contain the edit value from get, then just re-use the variable don't assign new value. On this line you assign new value :
$personid = $_POST['personid'];
Don't assign new value since it has the initial value already to use just set the variable global for usage
$personid = $_GET['edit'];
Or else create a hidden element and pass edit value into it.
Please add name attribute for your update button
<td colspan="2"><input type="submit" name="update" value=" Update"></td>
and chk whether the update button set or reset as in the place of
if(isset($_POST['newpersonname'])) // change text 'newpersonname' as 'update'
You use a variable that doesn't excist:
<?php
include_once('coneksioni.php');
if(isset($_GET['edit']))
{
$personid = $_GET['edit'];
$res = mysql_query("SELECT * FROM tblperson WHERE personid='$personid'");
$row = mysql_fetch_array($res);
}
if(isset($_POST['newpersonname']))
{
$newpersonname = $_POST['newpersonname'];
$personid = $_POST['personid']; // this doesn't excist
$sql = "UPDATE tblperson SET personname = '$newpersonname' WHERE personid = '$personid'";
$res = mysql_query($sql) or die ("Cant be updated");
echo "< meta http-equiv='refresh' content='0;url=home.php'>";
}
?>
$personid = $_POST['personid']; doesn't excist in your code. Its simply a piece of code you put in there to probably proces, but forgot to define the variable in the code. Place the following in your form.
<input type="hidden" name="personid" value="<?php echo $_GET['edit']; ?>">
You only use this just once because you send the form back after proces to your home, hence it wont be used anymore. You can also use the avariable you defined as $personid; on that position.
If that fails, something maybe wrong in your query. Try to echo out the query (remove qucikly the meta command) by simply just do echo $sql after you do the sql query. 9 out of 10 times, it's a typo.

get multiple ID while POST multiple selection option value to next form

how can I get multiple ID while POST multiple selection option value to next form? I only get the first selection ID from array. Can you guys can suggest any ideas to me?
here is my code when select the value.
<tr>
<label>Auditor: </label>
<select class="form-control" name="auditor[]" multiple="multiple" >
<?php
$result = $db->query("SELECT * FROM auditor");
while($row = mysqli_fetch_array($result))
{
echo '<option value="'.$row["auditor_name"].'">'.$row["auditor_name"].'</option>';
}
echo "</select>";
?>
</tr>
here is another code while POST to the next page.
$myselected = $_POST["auditor"];
if(count($myselected)>1){
$auditor = implode ("','",$myselected);
}else{
$auditor =$myselected;
}
$query10 = "SELECT * FROM auditor WHERE auditor_name IN ('$auditor') ";
$result10 = $db->query($query10);
$row10 = $result10->fetch_array();
?>
<form action="audit_action/audit_action.php" role="form" method="post" name="auditformdetails" onsubmit="return(validate());">
<table width='100%' border='0' class="table">
<tr>
<td colspan=6>Audit details</td>
<td colspan=6>Outlet details</td>
</tr>
<tr>
<td><b>Auditor:</b></td>
<td colspan='5'>
**<?php
echo'<input type="hidden" name="auditor_id" value="'.$row10["id"].'">';
foreach ($myselected as $auditor){
echo $auditor."<br>\n";
}
?>**
</td>
You can not compare string with mysql IN Clause. So, you have to connect each of your value with or condition in query as i written below.
$myselected = $_POST["auditor"];
$sql_cond = "";
if(count($myselected)>1){
foreach($myselected as $selected){
if($sql_cond != "")
$sql_cond.=" or auditor_name = ".$selected;
else
$sql_cond.=" auditor_name = ".$selected;
}
}else{
$auditor =$myselected;
}
$query10 = "SELECT * FROM auditor WHERE ".$sql_cond;

Create histogram based from multiple selected checkbox

i have a list of checkboxes, right now i am able to retrieve data at database from multiple selected checkbox, and display them in a table.. below this is the code..
But my problem is how to display similar output data just like in comparetable.php to a histogram..i tried to used google chart but it just display data of a histogram exactly from the database, not getting from multiple selected checkboxes. Thank you very much for your time...
history.php
<FORM NAME ="form1" METHOD ="POST" action="comparetable.php">
<table>
<tr>
<th></th>
<th>TITLE</th>
<th>ACTION</th>
</tr>
<?php
$query = "SELECT * FROM compareresult where idmember='$idmembersession'";
$sql_query = mysql_query($query) or die('Error 3 :'.mysql_error());
while($data = mysql_fetch_array($sql_query,MYSQL_ASSOC)){
$title = $data['subject'];
?>
<tr>
<td><input type="checkbox" name="selectedcheck[]"
value="<?php echo $title ?>"/></td>
<?php
echo "<td>$title</td>"
}
?>
</tr>
</table>
<INPUT TYPE = "Submit" Name = "submit1" VALUE = "COMPARE SELECTED"></form>
comparetable.php
<body>SUSTAINABILITY OF PERCENTAGE </br></br></br>
<table border='1'>
<tr>
<th>TITLE</th>
<th>PERCENTAGE RESULT</th>
</tr>
<?php
if(isset ($_POST["submit1"]))
{
$checkbox = isset($_POST['selectedcheck']) ? $_POST['selectedcheck'] : array();
foreach($checkbox as $title)
{
$query = "SELECT * FROM compareresult where subject='".$title."'";
$sql_query = mysql_query($query) or die('Error 3 :'.mysql_error());
while($data = mysql_fetch_array($sql_query))
{
$result = $data['result'];
echo "<tr>";
echo "<td>".$title."</td>";
echo "<td>".$result."</td>";
echo "</tr>";
}
}
}
?>
</table></body></html>

Button to perform a PHP script in a table issue

I have set a script to show all members of my database in a table that have so called 'Pending Points' . In that table there's a button that an admin can click to send those pending points to 'Points' to the user in that row of the table and resetting the 'Pending Points' to 0. I have made the script to send these points but it doesn't seem to change anything even though it does give the success message. Any help is appreciated !
Here's an image that will clarify:
Code to send the points (sendpoints.php):
<?
include ("connect.php");
$result = mysqli_query($conn,"SELECT * FROM members WHERE pendingpoints > 0 ");
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$send = $_POST['send'];
if ($send) {
mysqli_query($conn,"UPDATE members SET points='$newpoints' WHERE
username='$username'");
mysqli_query($conn,"UPDATE members SET pendingpoints='0' WHERE
username='$username'");
$username = $row['username'];
$pendingpoints = $row['pendingpoints'];
$points = $row['points'];
$newpoints = $points + $pendingpoints;
echo "Succesfully changed points for that user";
}
?>
Code to show the table:
<?
include ("connect.php");
$submit = $_POST['submit'];
if ($submit) {
$result = mysqli_query($conn,"SELECT * FROM members WHERE pendingpoints > 0 ");
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
while ($row = mysqli_fetch_assoc($result))
{
$username = $row['username'];
$pendingpoints = $row['pendingpoints'];
$points = $row['points'];
$newpoints = $points + $pendingpoints;
$ip = $row['ip'];
echo "<table border='1'>
<tr>
<td><b>Username:</b></td>
<td><b>Pendingpoints:</b></td>
<td><b>IP:</b></td>
<td><b>Confirm Points:</b></td>
</tr>
<tr>
<form id='1' action='sendpoints.php' method='post'>
<td> $username </td>
<td> $pendingpoints </td>
<td> $ip </td>
<td><input type='submit' class='classname' name='send' value='Send'></form></td>
</tr>
<br> </table>";
}
}
?>
As per my understanding you want to send points on button click only to specific person but in your code your doing something else..
note: i added hidden variable in your form to send points to only that specific user
<?
include ("connect.php");
if (isset($_POST['send'])) {
$username=$_POST'username'];
$result = mysqli_query($conn,"SELECT * FROM members WHERE username='$username' ");
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$pendingpoints = $row['pendingpoints'];
$points = $row['points'];
$newpoints = $points + $pendingpoints;
$q=mysqli_query($conn,"UPDATE members SET points='$newpoints',pendingpoints=0 WHERE
username='$username'");
if($q){
echo "Succesfully changed points for that user";
}
}
?>
Code to show the table:
<?
include ("connect.php");
$submit = $_POST['submit'];
if ($submit) {
$result = mysqli_query($conn,"SELECT * FROM members WHERE pendingpoints > 0 ");
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
while ($row = mysqli_fetch_assoc($result))
{
$username = $row['username'];
$pendingpoints = $row['pendingpoints'];
$points = $row['points'];
$newpoints = $points + $pendingpoints;
$ip = $row['ip'];
echo "<table border='1'>
<tr>
<td><b>Username:</b></td>
<td><b>Pendingpoints:</b></td>
<td><b>IP:</b></td>
<td><b>Confirm Points:</b></td>
</tr>
<tr>
<td> $username </td>
<td> $pendingpoints </td>
<td> $ip </td>
<td><form id='1' action='sendpoints.php' method='post'><input type='submit' class='classname' name='send' value='Send'><input type='hidden' name='username' value='$username'></form></td>
</tr>
<br> </table>";
}
}
?>
In the first script $row is not defined.
Edit: since the code was updated, the logic seems to be incorrect. You need to pull username from $_POST, and use this in the update.
However, two big problems: you are not handling escaping of special chars like '. This can break the form, and open up mysql injection security holes.

Unable to update database table from php page

I am trying to update whatever content in the textbox that has been edited and post to database. However, only the second record is update but the first record is not. I think should be the while loop problem but I don't what is the mistake.
Here's my edit page code:
viewadmindb.php
<?php
session_start();
include('adminconfig.php');
$sql = "SELECT * FROM admin ORDER BY ID";
$result = mysql_query($sql);
?>
<body>
<div id="wrap">
<div id="status"></div>
<form method="POST" action="adminsave.php" onSubmit="return validate(this);">
<table class="viewdb" contentEditable="true">
<tr><td id='fcolor' style='border:2px solid black' align=center> ID </td>
<td id='fcolor' style='border:2px solid black' align=center> Name </td>
<td id='fcolor' style='border:2px solid black' align=center> Password </td>
<td id='fcolor' style='border:2px solid black; width:auto;' align=center>
Department</td>
<td id='fcolor' style='border:2px solid black' align=center> Email </td></tr>
<div id="content">
<?php
while($row = mysql_fetch_array($result)){ ?>
<tr>
<td style='border:2px solid black; width:auto' align=center><?php echo $row[] =
$row['ID'] ?></td>
<td style='border:2px solid black' align=center> <?php echo $row[]
= $row['name'] ?> </td>
<td style='border:2px solid black' align=center> <?php echo $row[] =
$row['password'] ?> </td>
<td style='border:2px solid black; width:200px' align=center> <?php echo $row[] =
$row['department'] ?> </td>
<td style='border:2px solid black' align=center> <?php echo $row[] = $row['email']
?> </td>
<tr>
<td><input id='edit' type = 'text' name="ID[]" value='<?php echo $row['ID'] ?>'
maxlength="50"></td>
<td><input id='edit' type = 'text' name="name[]" value='<?php echo $row['name']
?>'
maxlength="50"></td>
<td><input id='edit' type = 'text' name="password[]" value='<?php echo
$row['password'] ?>' maxlength=50"></td>
<td><input id='edit' type = 'text' name="department[]" value='<?php echo
$row['department'] ?>' maxlength="50"></td>
<td><input id='edit' type = 'text' name="email[]" value='<?php echo
$row['email']?>'
style='width:300px' " maxlength="50"></td>
<?php } ?>
<td><input id='edit' type='submit' name='<?php $row['ID'] ?>' value='Submit'/>
</td></tr>
</table>
</form>
<?php
$ID=$row['ID'];
$name=$row['name'];
$password=$row['password'];
$department=$row['department'];
$email=$row['email'];
?>
adminsave.php
<?php
session_start();
include('adminconfig.php');
$ids=$_POST['ID'];
$name_arr=$_POST['name'];
$password_arr=$_POST['password'];
$department_arr=$_POST['department'];
$email_arr=$_POST['email'];
foreach(($ids as $key=>$id) {
$name = $name_arr[$key];
$password = $password_arr[$key];
$department = $department_arr[$key];
$email = $email_arr[$key];
$sql = "UPDATE admin SET name = '$name',password = '$password',
department ='$department',email = '$email' WHERE ID = '$id'";
}
$result = mysql_query($sql);
if(!$result){
die('invalid query:'.mysql_error());
}
else
echo ("<tr><td>" . "Data updated succesfully..." . "</td></tr>");
header('Refresh:5; url=viewadmindb.php');
die;
?>
You really should look up into how ID's are supposed to work in html. The basic things is that ID must be unique. You should not have two or more elements with same ID. But in your case it's the name-attribute that is the issue.
If you have a loop like this...
while($row = mysql_fetch_array($result)){ ?>
<tr>
<td><input id='edit' type = 'text' name="ID" value='<?php echo $row['ID'] ?>'
maxlength="50"></td>
</tr>
}?>
...and you have two rows from the $result-recordset, you will echo out html something like this:
<tr>
<td><input id='edit' type = 'text' name="ID" value='1'
maxlength="50"></td>
</tr>
<tr>
<td><input id='edit' type = 'text' name="ID" value='2'
maxlength="50"></td>
</tr>
Your then saving values into the database based on a element with name ID. But the problem is that PHP doesn't know which of the rows above it should use (How could PHP know?). When refering to an element that has a duplicate the last element in the DOM is used. Therefore only this row is take into account:
<tr>
<td><input id='edit' type = 'text' name="ID" value='2'
maxlength="50"></td>
</tr>
There are no loop in adminsave.php that indicates you want to save several values. It just tells that you want to save content into database with a specific ID.
$sql = "UPDATE admin SET name = '$name',password = '$password',
department ='$department',email = '$email' WHERE ID = '$ID'";
and because the last row in the DOM is used, the update-statement would be:
$sql = "UPDATE admin SET name = '$name',password = '$password',
department ='$department',email = '$email' WHERE ID = '2'";
You can solve this by making the name-element an array by adding brackets to name-elements: (Also make edit a class instead of an id because it's ok to have duplicate classes but not duplicate ids)
<tr>
<td><input class='edit' type = 'text' name="ID[]" value='<?php echo $row['ID'] ?>'
maxlength="50"></td>
</tr>
But then you would also have to loop through the array
<?php
$ids = $_POST['ID']; //Get array from form
$name_arr = $_POST['name'];
$password_arr = $_POST['password'];
$department_arr = $_POST['department'];
$email_arr = $_POST['email'];
foreach($ids as $key=>$id) {
//Get specific element in each array
$name = $name_arr[$key];
$password = $password_arr[$key];
$department = $department_arr[$key];
$email = $email_arr[$key];
//Create sql and execute
$sql = "UPDATE admin SET name = '$name',password = '$password',
department ='$department',email = '$email' WHERE ID = '$id'";
$result = mysql_query($sql);
}
The row:
$sql = "SELECT * FROM admin WHERE $ID = '$ID'";
is pointless because the variable $sql is overritten on the next row.
Note that above is just for demonstrating how the basic concepts of ids, names and arrays works when handling forms. You should really not just mysql_* functions, but instead read up on PDO or mysqli instead. You should sanitize (make sure unwanted data is not injected into db) before updating.
The whole Logic is wrong.
Just pass in the query string from main page to another php page ex from:admin_detail.php to edit_admin.php
Then query db for data based on passed query string
echo them in desired textbox.
then call update statement.
viewadmindb.php
The var $row you didnot set. Just ad this $row = mysql_fetch_array($reslult); before you access to table values.
What is this $row[] = $row['name'] ? You refill $row, and after you cannot access the original value from database. Use ony labels, no vars like <td> E-mail: </td>
adminsave.php
You rewrited the $sql var. The line $sql = "SELECT * FROM admin WHERE $ID = '$ID'; you donot need to use.
Good tip: use the css syntax ` and border the varchars with {$var}:
"UPDATE `admin` SET `name` = '{$name}', `password` = '{$password}', `department` = '{$department}', `email` = '{$email}' WHERE `ID` = '{$ID}'"
It seems you are new to php.
Your code is not well formated and not really readable.
Don't do $_POST['...'] and write this value directly into database (security issue => mysql injection) So please insert mysql_real_escape_string($value) before you insert into database.
What the hack is that? echo $row[] = $row['password'] don't do that! only echo is enough.
Solution of your answer:
It's normal that your code update only the last iteration of the while loop, because only the last value will be stored into the $_POST array.
If you wanna fix that you have to make the form as array like:
<input id='edit' type = 'text' name="name[]" value='<?php echo $row['name'] ?>'
maxlength="50">
Then in your viewadmindb.php you have to iterate over this values again and make for each value an extra update query which updates the value in the database.
UPDATE:
The foreach loop should look like this in adminsave.php:
$arrIds = array();
$arrNames = array();
$arrDepartments = array();
$arrPasswords = array();
// ... add all necessary vars you wan a fetch from the post request
$arrIds[] = $_POST['name'][];
$arrNames[] = $_POST['name'][];
$arrDepartments[] = $_POST['department'][];
$arrResults = array(); // To store result data if necessary
foreach($arrIds as $key => $item) {
// Build sql query
$sql = "UPDATE admin SET name = '". $arrNames[$key] . "',password = '". $arrPasswords[$key] . "',
department ='". $arrDepartments[$key] . "',email = '". $arrEmailss[$key] . "' WHERE ID = '$item'";
// Execute query!
$arrResults[] = mysql_query($sql);
}
So now you should be able to get it running...

Categories