Last ID is added to DB [duplicate] - php

This question already has an answer here:
Multiple hidden input with same name, always retrieve the last input [duplicate]
(1 answer)
Closed 4 years ago.
index.php
<form method="POST" action="add_to_db.php">
<?php
foreach ($response->getGraphEdge() as $graphNode) :
echo
"<div class='form-check mb-3'>" .
"<input type='radio' name='fb_name' class='form-check-input mt-3' value='".$graphNode['name']."'>" .
"<img class='mx-2' src='" . $graphNode['picture']['url'] . "'>" .
"<label class='form-check-label' for='fb_name'>" . $graphNode['name'] . '</label>' .
"<input type='hidden' name='fb_id' value='" . $graphNode['id'] . "'>" .
"<input type='hidden' name='fb_access_token' value='" . $graphNode['access_token'] . "'>" .
"</div>";
endforeach; ?>
</form>
add_to_db.php
if(isset($_POST['submit'])) {
$query = new db;
$b = $query->Query('SELECT * FROM user WHERE user_ID = 1');
$fb_id = $_POST['fb_id'];
$fb_name = $_POST['fb_name'];
$fb_access_token = $_POST['fb_access_token'];
$update = $query->Query("UPDATE user
SET user_fb_page_id = '$fb_id',
user_fb_page_name = '$fb_name',
user_fb_page_access_token = '$fb_access_token'
WHERE user_ID = 1 ");
if(!$update) {
echo '<div class="alert alert-success" role="alert">Updated Successful!</div>';
} else {
echo '<div class="alert alert-danger" role="alert">Oh no! Something went wrong ☹️</div>';
}
}
Problem:
When a user clicks on the Facebook Page that they want, the value to their name & access token is successfully updated to the database however it'll update the last fb_id to the db which is clearly not what I want! I am not sure at all why the ID does this yet none of the other attributes do it

The form input fields in one iteration of your foreach loop have the same names as the input fields in the other iterations.
This produces a form where all of the input fields that hold an id have the exact same name. (The same goes for the input fields that hold an access token and the radio buttons.) Because the fields have the same name, only the last value of each set is submitted to the server, with exception of the radio button which just submits the selected value.
To fix this, you need to give all of the fields in your form an unique name. I've done so here by adding a $key (alternatively you can use the fb_id, if that's unique).
When the form is submitted, only one value should exist in the POST array for $_POST['key'], this is the key of the selected radio button. You can then use this key to find the id, name and access token that go with it:
<form method="POST" action="add_to_db.php">
<?php
foreach ($response->getGraphEdge() as $key => $graphNode) :
echo
"<div class='form-check mb-3'>" .
"<input type='radio' name='key' class='form-check-input mt-3' value='".$key."'>" .
"<img class='mx-2' src='" . $graphNode['picture']['url'] . "'>" .
"<label class='form-check-label'>" . $graphNode['name'] . '</label>' .
"<input type='hidden' name='fb_name[".$key."]' value='" . $graphNode['name'] . "'>" .
"<input type='hidden' name='fb_id[".$key."]' value='" . $graphNode['id'] . "'>" .
"<input type='hidden' name='fb_access_token[".$key."]' value='" . $graphNode['access_token'] . "'>" .
"</div>";
endforeach; ?>
</form>
and
if(isset($_POST['submit'])) {
$query = new db;
$b = $query->Query('SELECT * FROM user WHERE user_ID = 1');
$key = $_POST['key'];
$fb_id = $_POST['fb_id'][$key];
$fb_name = $_POST['fb_name'][$key];
$fb_access_token = $_POST['fb_access_token'][$key];
$update = $query->Query("UPDATE user
SET user_fb_page_id = '$fb_id',
user_fb_page_name = '$fb_name',
user_fb_page_access_token = '$fb_access_token'
WHERE user_ID = 1 ");
if(!$update) {
echo '<div class="alert alert-success" role="alert">Updated Successful!</div>';
} else {
echo '<div class="alert alert-danger" role="alert">Oh no! Something went wrong ☹️</div>';
}
}
(I've removed the "label for" because it wasn't working. To get it to work you can add id='$key' to the radio input, and label for='$key' to the label.)

Related

Form to update row in database where form is generated from php while loop

I have an interesting challenge that I haven't been able to get my head around, I have a html table that is generated from php while loop and a mysql database, each generated row of this table has a button that allows someone to modify a row in a database, but whenever the button is pressed the action is performed across the whole generated table thanks to the while loop, and I don't know how to only get that row to perform an action.
Here is the code that I have so far in this section.
while ($submissionrow = mysqli_fetch_array($currentsubmissions)) {
if ($submissionrow[approved] === '1') {
$approvedtick = 'Approved';
}else {
$approvedtick = '';
}
if ($submissionrow[rejected] === '1') {
$rejectedsymbol = 'Rejected';
}else {
$rejectedsymbol = '';
}
if ($approvedtick == $blanksymbol && $rejectedsymbol == $blanksymbol) {
$inreviewmessage = 'In Review';
}else {
$inreviewmessage = '';
}
echo "<tr>";
echo "<td>" . $submissionrow[submission_ID] . "</td>";
echo "<td>" . $submissionrow[Username] . "</td>";
echo "<td>" . $currentyear . "</td>";
echo "<td>" . $submissionrow[CSEvent] . "</td>";
echo "<td>" . "";?>
<form method='post' action='<?php $_PHP_SELF ?>'>
<?php
echo "<button type='submit' name='$submissionrow[submission_ID]' id='accept_cs'>Approve</button>";
echo "<button type='submit' name='$submissionrow[submission_ID]' id='reject_cs'>Reject</button>";
?>
</form>
<?php echo "
" . "</td>";
echo "<td>" . $approvedtick . $rejectedsymbol . $inreviewmessage . "</td>";
if(isset($_POST['accept_cs'])) {
$accept_cs_sql = 'UPDATE CommunityService SET approved =1 WHERE submission_ID =' . $submissionrow[submission_ID];
printf($accept_cs_sql);
$retval = $dbcon->query("$accept_cs_sql");
echo "Updated Accepted Status successfully\n";
}
if(isset($_POST['reject_cs'])) {
$reject_cs_sql = 'UPDATE CommunityService SET rejected =1 WHERE submission_ID =' . $submissionrow[submission_ID];
printf($reject_cs_sql);
$retval = $dbcon->query("$reject_cs_sql");
echo "Updated Rejected Status successfully\n";
}
}
I can make the code submit the performed action, but it enacts this action on the ID of every row in the table, not just the row with that button that was pressed.
Thank you in advance
-jx

PHP Dropdown list maintain on reload

I am new to PHP and have just started the professional development in this language. I have created a dynamic dropdown list in php as under:
$sql="select DISTINCT State from branchinfo";
$result = $conn->query($sql);
if($result->num_rows > 0)
{
echo "< SELECT NAME='states'>";
while($row=$result->fetch_assoc())
{
echo "< OPTION NAME = '" . $row['State'] . "'" . " VALUE = '" . $row['State'] . "'>" . $row["State"];
}<br>
echo "< /SELECT>";
}
echo "< INPUT TYPE='submit' name='submit' value='submit'>";
Problem is when I select a state and click on submit, the list reloads and my selection is lost, the first option gets selected by default. I have tried to embed the script within OPTION but it didn't worked, I tried it as under:
echo "< OPTION NAME='" . $row['State'] . "'" . " VALUE='" . $row['State'] . "'" . if(isset($_POST["submit"])){ if($_POST["states"] == $row['State']) echo "selected";} . " >" . $row["State"];<br>
I am not using any javasrcipt / jquery till now on this page and not planning to use it either. plz provide a solution within this code. Please help.
Some additional information
The mthod i tried as mentioned above, works fine on hardcoded static drop downlist items written in html form. It stops working for dynamically generated list.
You have to add dropdown inside form tag, then it will work.
$sql = "select DISTINCT State from branchinfo";
$result = $conn->query($sql);
echo "<form method='POST'>";
if ($result->num_rows > 0) {
echo "<SELECT NAME='states'>";
while ($row = $result->fetch_assoc()) {
$sel = ( $_POST['states'] == $row['State'] ) ? "selected" : "";
echo "< OPTION NAME = '" . $row['State'] . "'" . " VALUE = '" . $row['State'] . "' " . $sel . ">" . $row["State"] . "</OPTION>";
}
echo "</SELECT>";
}
echo "<INPUT TYPE='submit' name='submit' value='submit'>";
echo "</form>";
Use session to remember your choice. And when the page is reloaded just retrieve your previous selected value.
like
while($row=$result->fetch_assoc())
{
if($sessionvalue==$row['State']){
echo "< OPTION SELECTED NAME = '" . $row['State'] . "'" . " VALUE = '" . $row['State'] . "'>" . $row["State"];
}else{
echo "< OPTION NAME = '" . $row['State'] . "'" . " VALUE = '" . $row['State'] . "'>" . $row["State"];
}
}

PHP - POST form will not pass numeric value for checkbox, but accepts all other values

$squery = $cbdbc->prepare("SELECT * from sitedata");
$squery->execute();
while ($srow = $squery->fetch(PDO::FETCH_ASSOC)) {
if ($rresult[$srow['siteName']] !== $srow['siteID']) {
echo "<tr><td><input type='checkbox' id='" . $srow['siteID'] . "' name='" . $srow['siteID'] . "' value='" . $srow['siteID'] . "'><label for='".$srow['siteID']."'>" . str_replace('_',' ',$srow['siteName']) . "</label></td></tr>";
} else {
echo "<tr><td><input type='checkbox' id='" . $srow['siteID'] . "' name='" . $srow['siteID'] . "' value='" . $srow['siteID'] . "' checked='checked'><label for='".$srow['siteID']."'>" . str_replace('_',' ',$srow['siteName']) . "</label></td></tr>";
}
}
echo "<tr><td><input type='submit' value='Submit'></td></tr></table></form>";} elseif (null !== filter_input(INPUT_GET, 'setromstores')) {
$rid = filter_input(INPUT_GET, 'setromstores');
$squery = $cbdbc->prepare("SELECT * FROM sitedata");
$squery->execute();
while ($srow = $squery->fetch(PDO::FETCH_ASSOC)) {
$sid = filter_input(INPUT_POST, (string)$srow['siteID']);
if ($sid !== null) {
$uquery = $cbdbc->prepare("UPDATE roms SET " . $srow['siteName'] . "=:sid WHERE romID = :rid");
$uquery->bindParam(':sid', $sid);
$uquery->bindParam(':rid', $rid);
$uquery->execute();
} else {
$uquery = $cbdbc->prepare("UPDATE roms SET " . $srow['siteName'] . "= '0' WHERE romID = :rid");
$uquery->bindParam(':rid', $rid);
$uquery->execute();
}
}
So I'm trying to do a system where a user known as a ROM can be assigned 'sites' using checkboxes.
For every type of value except pure numbers for 'siteID' (which is VARCHAR(5) on the MySQL table), e.g. abc, abc12, 0001, the value of siteID passes correctly and the value is updated correctly in the table 'roms'.
If I have a pure number as a value for siteID, e.g. 1, 15, 2339, it will pass no value through POST and will always result in 0 being set in the 'roms' table.
I have tried making sure that at every step the value being passed is converted into a string, but this doesn't seem to help.
While typically site IDs are in the format AXXXX, I would prefer to see if this is fixable then force users to put in siteIDs of AXXXX, especially as this may change in the future to pure numbers.
Value is not the same as name or id. You can't send forms with only-number names, nor ids. Change your line to something like this:
<input type='checkbox' id='yourUniqueId" . $srow['siteID'] . "' name='checkboxes[" . $srow['siteID'] . "]' value='" . $srow['siteID'] . "' checked='checked'>
Well, as you can see, your checkboxes are named now checkboxes and it's an array of data!! You can receive in PHP
$_POST['checkboxes']; // array(value1, value2, value3)
And you fix your problem.
Form field name must be a string. You can use this method:
echo "<tr><td><input type='hidden' name='siteID[" . $srow['siteID'] . "]' value='0'><input type='checkbox' id='" . $srow['siteID'] . "' name='siteID[" . $srow['siteID'] . "]' value='" . $srow['siteID'] . "'><label for='".$srow['siteID']."'>" . str_replace('_',' ',$srow['siteName']) . "</label></td></tr>";
I change checkbox name like this name="siteId[12]", and add hidden field (it`s not necessary).
After that siteID is an associated array of checked sites, where key is siteId, and value 1, if checked, and 0 if not.
$sids = filter_input(INPUT_POST, 'siteID', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
while ($srow = $squery->fetch(PDO::FETCH_ASSOC)) {
$sid = $sids[$srow['siteID']];
// ...
}

How do I store the contents of tables rows and use them on another page?

I am a beginner to web development and am just wondering how I can store the values of a table row and use them on another page.
At the moment I am retrieving values from a database and putting them into a table. Each row has a submit button which should take them to a pay.php page where it should list the details of the particular row that they selected to pay.
while($row = mysql_fetch_array($result))
{
echo "<td>" . $row['P_name'] . "</td>";
echo "<td>" . $row['P_amount'] . "</td>";
echo "<td>" . $row['P_dateStart'] . "</td>";
if(is_null($row['P_datePaid'])){
echo "<td>Not Paid</td>";
}
else{
echo "<td>" . $row['P_datePaid'] . "</td>";
}
if($row['P_status'] == 0){
echo "<td bgcolor='#FF0000'>" . $row['P_status'] . "</td>";
}
else{
echo "<td bgcolor='#00FF00'>" . $row['P_status'] . "</td>";
}
echo "<td><form name = 'viewMore' action = 'viewMore.php'><input type = 'submit' value = 'View More'></form></td>";
echo "<td><form name = 'pay' action = 'pay.php'><input type = 'submit' value = 'Pay'></form></td>";
echo "</tr>";
}
echo "</table>";
?>
You can add the record ID (assuming in my example that is P_id) in the form like this. I also added method='post' to avoid someone to try pay.php?id=... :
echo "<td><form name = 'pay' action = 'pay.php' method='post'>
<input type='hidden' name='id' value='" . $row['P_id'] . "'>
<input type = 'submit' value = 'Pay'></form></td>";
And then in pay.php using $_POST["id"] to query the table and retrieve the data.
You can google PHP Session
Here is an example.
session_start();
// store session data
$_SESSION['views']=1;
on another page you can use
echo "Pageviews=". $_SESSION['views'];
and I think your requirement is not releted to session.
Do you know how to use the form?
You should post the data of the certain line to the page you want.
And you can get the in _POST['XXXX'];

PHP mulitiple checkboxes

I am stuck on a script and need another pair of eyes to see if I am missing something. The script is for a bookshop. When a student number is in-putted and searched for the student is displayed with the books that he is suppose to get for each subject. The student, course and book data comes from a MySQL database.
This is all done with this script:
<?php
if (isset($_POST['submit'])){
$btnClick = $_POST['submit'];
switch($btnClick){
case "Logout" :
session_destroy();
header("location:index.php");
break;
case "Search" :
$Validate = $_POST['txtStud'] ;
$StudNr = ValidateTxt($Validate);
$showStud = findStud($StudNr);
$cid = $showStud[4];
$showBooks = findBooks($cid);
echo "<form action='issue_book.php' method='post'>";;
echo "<table class='table3'>";
echo "<tr>";
echo "<td>" . $showStud[0] . " " . $showStud[1] . " " . $showStud[2] ."</td>";
echo "</tr>";
echo "<tr><td></td><td>" . $showStud[3] . "</td></tr>";
$array_count = count($showBooks);
$num = 0;
while ($num != $array_count) {
$bookNum = $showBooks[$num]['bid'];
echo $bookNum . "<br>";
echo "<tr><td>" . $showBooks[$num]['bid'] . "</td>" . "<td>" . $showBooks[$num]['bname'] . "</td>" ;
echo "<td><input type='checkbox' name='booknum[]' value='<?php echo $bookNum; ?>'></td></tr>";
$num++;
}
echo "</table>";
echo "<br>";
echo "<table class = 'table3'>";
echo "<tr><td></td><td><input type='submit' name='submit' value='Issue'></td>
<td><input type='submit' name='submit' value='Clear'></td></tr>";
echo "</form>";
break;
case "Issue":
$mybooks = $_POST['booknum'];
$h = count($mybooks);
echo $h . "<br>";
print_r ($mybooks);
break;
}
}
?>
At the bottom of the dynamic created data there is 2 buttons. When I click on the Issue button I am presented with this data.
This comes from the code as it is in the script at this moment. I want to send the data from here to the database.
Array ( [0] => [1] => [2] => )
An empty array?? Not sure what happened to the names that I assigned each check box??
I tried to adapt my script according to this forum post Check box link
I am not sure where I am missing something.
This is because you have a syntax error here
echo "<td><input type='checkbox' name='booknum[]' value='<?php echo $bookNum; ?>'></td></tr>";
^php tags are opened ^
You are already printing your table inside php tags, you cannot open other tags
value='<?php echo $bookNum; ?>
This is why your array's values are empty but keys exists. You just need to concatenate
echo "<td><input type='checkbox' name='booknum[]' value='".$bookNum."'></td></tr>";

Categories