pass on a row ID onto another page in php - php

I am trying to pass on a row ID by user click on the specified row, onto another page. I have a table with ID and info column.
code below displays the wanted row ID and info
if ($info = $stmnt2->fetch()) {
echo '<p>Your Info:</p>';
do {
echo "$info[id] . $info[review] . <a href=edit.php?edit=$info[id]>edit</a></br> </br>" ; //The info id is contained in the $info['id']
} while ($info = $stmnt2->fetch());
} else {
echo "<p>No Info</p>";
}
I want the user to be able to click on any of the rows and the selected row to pass on its ID onto another page. How do I do this?
This is the code on the other page and I want the ID on which the user clicked to replace "$info[id]" in the sql query. This replaces the whole column and not the specified row.
if(isset($_POST['id'])){
$update=$_POST['id'];
$db->exec("UPDATE infos SET info = '$update' WHERE reviewid = '$info[id]'");
}
In the edit page I have an input which the user can write to replace the selcted row (from the ID that gets passed on)
<form action="edit.php" method="POST">
<input type="text" name="id" value="">
<input type="submit" value=" Update "/>
</form>
So I want the ID that was passed from the first page to be used to replace the info row with the user input from the edit page

Pass the ID to the URL to the next page, navigate to the next page, then use $id =$_GET['id'];
Your edit=$info['id'] part is right but you're using $_POST and $_POST['id'], on the next page. The GET global is needed and it's named edit, not id
if ($info = $stmnt2->fetch()) {
echo '<p>Your Info:</p>';
do {
echo "$info[id] . $info[review] . <a href=edit.php?edit=$info[id]>edit</a></br> </br>" ; //The info id is contained in the $info['id']
} while ($info = $stmnt2->fetch());
} else {
echo "<p>No Info</p>";
}
edit.php:
if(isset($_GET['edit'])){
$update = $_GET['edit'];
$db->exec("UPDATE infos SET info = '$update' WHERE reviewid = '$info[id]'");
}
Also for future expansion and learning, read into how to do prepared statements with bound parameters if you are going to be using queries with variables built in. You're prone to sql injection currently and it's good practice to learn the newer and safer methods.

you can get the parameter value by using $_REQUEST
$update = $_REQUEST['edit'] in edit.php file
when you use $_REQUEST method you can catch both $_GET and $_POST values.

Related

How to INSERT multiple rows with multiple values, but only for items that have checkboxes ticked next to them

I am coding a discography tool for a music database.
Artists are able to insert tracks, singles, EPs, and albums all into separate tables on the database.
Having tracks be in their own separate table allows the same tracks to be attached to multiple singles, EPs and albums while only requiring there to be one record for that track in the database.
Which means individual track pages can have an automatically generated list of links back to the Singles, EPs and albums that they appear on. Making navigating the database through the website a much smoother experience.
I have come to the point where I am coding a tool to attach any existing tracks in the database for a given artist onto an album page.
I am using another table in the database called 'trackconnections' to create the relational links between the track ids from the track table and the album id from the album table, with an additional column called albumtracknum available to be able to output the tracks in the right order when queried on the album page.
The code for the tool is behind a button labelled 'Attach existing track(s) to album'. The code for this tool is as follows:
if (isset($_POST['attachexistingtracktoalbum-submit'])) {
require "includes/db_connect.pdo.php";
$artistid = $_POST["artistid"];
$albumid = $_POST["albumid"];
echo '<strong>Select each track you would like to add to this album below and type in the track number you want it to have on the album in the box underneith the name of each selected track.</strong><br><br>';
$stmt = $pdo->query("SELECT * FROM track WHERE artist_id = '$artistid'
order by trackname");
while ($row = $stmt->fetch())
{
echo '<form action="includes/attachexistingtracktoalbum.inc.php" method = "post">';
echo '<div class="checkbox">';
echo '<label>';
echo "<input type='checkbox' name='trackid[]' value='".$row['id']."' />";
echo '<span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>';
echo ' '.$row['trackname'];
echo '</label>';
echo "<br><label for='albumtracknum'>Track number:</label><br>
<input type='text' name='albumtracknum[]'>
<input type='hidden' name='albumid[]' value='".$albumid,"'>
<br><br>";
echo '</div>';
}
?>
<input type="hidden" name="albumidforreturn" value="<?php echo $albumid;?>">
<button type="submit" name="attachexistingtracktoalbum-submit">Attach track(s) to album</button>
<?php }
else {
header("Location: /index.php");
exit();
}?>
(NB: The post data here is not sanitised for the sql query as it has been passed along in a hidden form from the original album page)
This generates a page with all track names for the current artist available on a list with checkboxes, with each track name being followed by a data entry box to enter the track number for the album being added to.
Submission of the form then hands off to the following include code:
if (isset($_POST['attachexistingtracktoalbum-submit'])) {
require "db_connect.pdo.php";
$albumid = implode(',',$_POST['albumid']);
$trackid = implode(',',$_POST['trackid']);
$albumtracknum = implode(',',$_POST['albumtracknum']);
$albumidforreturn = $_POST['albumidforreturn'];
// echo 'albumid: '.$albumid.'<br>';
// echo 'trackid: '.$trackid.'<br>';
// echo 'albumtracknum: '.$albumtracknum.'<br>';
$sql = "INSERT INTO trackconnections (albumid, trackid, albumtracknum) VALUES (?,?,?);";
$stmt= $pdo->prepare($sql);
$stmt->execute([$albumid,$trackid,$albumtracknum]);
header("Location: ../albumdetail.php?albumid=$albumidforreturn");
exit();
}
else {
header("Location: ../index.php");
exit();
}
(NB: The commented out echos are there to test what the output is from the previous form)
The 2 problems I am having are that my 'Attach existing tracks to album' form submit:
1. Passes on too much data.
The generated form should only pass on the track ids, album number, and track numbers that have had their checkboxes ticked. For insertion into the 'trackconnections' table.
Instead it narrows down the ticked checkbox track ids only and then creates comma separated values for every available track to select, rather than just those actually selected.
Which leads to annoying outputs such as the following when passing on data from form to include:
albumid: 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4
trackid: 30,14
albumtracknum: ,2,3,,,,,,,,,,,,,,,,,,,,,
Where it should only read as:
albumid: 4,4
trackid: 30,14
albumtracknum: 2,3
Having too much data get passed through means that the row inserts won't be correct on multiple INSERTS once I do get this working, as they won't align with one another in the correct order.
2. The include only INSERTS 1 row to the 'trackconnections' table.
It seems I am misunderstanding how to add multiple rows to the database with my code here.
As having multiple checkboxes ticked on my 'Attach existing tracks to album' form only inserts 1 single row to the database on submission of the form each time.
Consistently the only track that gets added to the 'trackconnections' table is the first track with its checkbox ticked and, because of issue no. 1 above, the albumtracknum is always 0 unless I type a number into the first albumtracknum box on the available checklist.
I need to make tweaks to this code so that both problem 1 and 2 are addressed together, meaning that ticking the checkboxes & adding track numbers into each box following the track names actually adds multiple rows to the database along with their corresponding album track numbers.
I hope someone can help.
EDIT TO SHOW REFINED AND WORKING CODE:
New code for checkbox and textbox sections -
if (isset($_POST['attachexistingtracktoalbum-submit'])) {
require "includes/db_connect.pdo.php";
$artistid = $_POST["artistid"];
$albumid = $_POST["albumid"];
echo '<strong>Select each track you would like to add to this album below and type in the track number you want it to have on the album in the box underneith the name of each selected track.</strong><br><br>';
$stmt = $pdo->query("SELECT * FROM track WHERE artist_id = '$artistid'
order by trackname");
echo '<form action="includes/attachexistingtracktoalbum.inc.php" method = "post">';
while ($row = $stmt->fetch())
{
echo '<div class="checkbox">';
echo '<label>';
echo "<input type='checkbox' name='trackid[]' value='".$row['id']."' />";
echo '<span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>';
echo ' '.$row['trackname'];
echo '</label>';
echo "<br><label for='albumtracknumber'>Track number:</label><br>
<input type='text' name='albumtracknumber_".$row['id']."'>
<input type='hidden' name='albumid[]' value='".$albumid,"'>
<br><br>";
echo '</div>';
}
?>
<input type="hidden" name="albumidforreturn" value="<?php echo $albumid;?>">
<button type="submit" name="attachexistingtracktoalbum-submit">Attach track(s) to album</button>
</form>
<?php }
else {
header("Location: /index.php");
exit();
}
New code for the include INSERT processing -
if (isset($_POST['attachexistingtracktoalbum-submit'])) {
require "db_connect.pdo.php";
$albumid = implode(',',$_POST['albumid']);
$trackid = implode(',',$_POST['trackid']);
$albumidforreturn = $_POST['albumidforreturn'];
foreach($_POST['trackid'] as $trackidloop) {
$albumtracknum = $_POST["albumtracknumber_{$trackidloop}"];
$sql = "INSERT INTO trackconnections (albumid, trackid, albumtracknum) VALUES (?,?,?);";
$stmt= $pdo->prepare($sql);
$stmt->execute([$albumid,$trackidloop,$albumtracknum]);
}
header("Location: ../albumdetail.php?albumid=$albumidforreturn");
exit();
}
else {
header("Location: ../index.php");
exit();
}
This isn't an entire solution but I see some problems:
You are looping through tracks and creating a new form for each one. The first problem is , you are missing the closing form tag. I guess the browser is automatically creating one, when it sees the next form start tag. ?? That's why you only get one single posted checkbox.
I would put all the track checkboxes into a single form. Then the posted trackid[] array will contain all the checked items.
[EDIT after your comment: The hidden fields albumid[] post the entire array, whereas the trackid[] checkboxes only post the actual checked boxes (HTML spec).
Instead of having albumid[], You could put the trackID and albumID together for the checkbox value, then parse them apart when you handle the post:
$value = $row['id']. ',' . $row['albumid'];
echo "<input type='checkbox' name='trackid[]' value='".$value."' />";
ALSO, the SQL, "INSERT INTO (..) .. VALUES (...) " only inserts one row.
It's easy to do that SQL in a loop for all the checked boxes.
foreach($_POST['trackid'] as $value) {
// parse the $value...
// SQL Insert...
}
EDIT 2: From my own comment:
Like hidden fields, input (text) field arrays also post the entire array (with empty values for blank inputs). (Again, this is not a PHP thing, it's a web browser standard to only post checked checkboxes and radio buttons. But ALL text and hidden INPUTs are posted.) So in your example, you need to code a mechanism to know which textbox goes with each checkbox. Quick and dirty...You could add a row index (0,1,2,3...) as another comma-separated number in your checkbox values, then you'll have the index into the posted textbox array. Alternatively, you could name the textboxes ' .. name="textinput_' . $row['trackid'] . '" ...' (not an array), then upon post, read them in your foreach loop with
$val = $_POST["textinput_{$trackid}"];

How to GET URL parameters with PHP inside if(isset) statement for update form

I know you can get the URL parameters by using if(isset($_GET['id'])){
$id = $_GET['id']; and this works great, if I then close that 'if' statement and create a new one for the update/append-entry form on this same page (its the display page for each ind. database entry), I can't get the id that's been passed to the URL in this next if statement.
It is the if-statement that submits a new row ("condition") to my child table ("conditions") that has a foreign key that connects it to the parent table of health providers (the display page gets the provider's id from the search engine selection and displays their information, then has this "append entry" form at the bottom if someone wants to add a new health condition treated by this doctor.)
Everything works if I give it the right id number directly in my PHP ($id = 56), but not if I try to grab it from the URL INSIDE this second if statement ($id = $_GET['id'];).
if (isset($_GET['providerid']))
{
$providerid = $_GET['providerid']; /*THIS WORKS GREAT*/
$sql = "SELECT *, GROUP_CONCAT(DISTINCT conditions.condition_name
SEPARATOR ', ') AS all_conditions FROM `providers` INNER JOIN
`conditions` ON `providers`.`id` = `conditions`.`prov_id` WHERE
`prov_id`= $providerid";
$data = mysqli_query($connection, $sql) or die('error');
if(mysqli_num_rows($data) > 0){
$numresults = mysqli_num_rows($data);
while($row = mysqli_fetch_assoc($data)){
$providerid = $row['id'];
$providerfirstname = $row['provider_first_name'];
/*etc....*/
$conditions = $row['all_conditions'];
/*table displays provider info:*/
echo "<br><h1>".$providerfirstname." ".$providerlastname."
</h1>";
echo '<TABLE id="myTable" width="350px" border="1">';
//etc....(cutting out details)
echo '<tr><td><div id="myTable"><a href="#" id="addNew">Add+ .
</a></div></td><td><b>Conditions Treated:</b></td> .
<td>'.$conditions.'</td></tr>';
/*If user wants to add a new condition treated by provider that's
not listed:*/
echo '<tr><td></td><td>Add a new condition:</td><td><form
action="profilebackup.php" method="POST"><input type="text"
size="40" name="newcond" value="" placeholder="Add a Condition" /> .
<input type="submit" name="add1" value="Add"><br></td></tr>';
}
echo '</TABLE>';
}
else {
echo "0 results";
}
}
/*sends added conditions to child table, EVERYTHING WORKS EXCEPT
GETTING ID (WHICH WORKED ABOVE):*/
if(isset($_POST['add1'])){
$providerid = $_GET['providerid'];
$condition = mysqli_real_escape_string($connection,
$_POST['condition']);
$insql = "INSERT INTO `conditions` (condition_name, prov_id) VALUES
('$condition','$providerid')";
if(mysqli_query($connection, $insql)){
echo "Thank you! Your provider has successfully been submitted
to the database!";
}
else {
echo "Sorry, there was an problem submitting your provider to
the database." . $insql . mysqli_error($connection);
}
}
Everything works EXCEPT the GET function in the second if-statement. It returns error code that it does not have the correct foreign key constraint: "Cannot add or update a child row: a foreign key constraint fails" because it's not grabbing the id.
You are submitting a form via post to profilebackup.php but the handler for this form is trying to get the providerid. You need to send the providerid as a query string in the form's action if you want to be able to access it via $_GET.
<form method="post" action="profilebackup.php?providerid=<?php echo $providerid; ?>" ...
The proper way to do this would be to include a hidden input in the form and then access it via $_POST consistently.
<form method="post" action="profilebackup.php">
<input type="hidden" name="providerid" value="<?php echo $providerid; ?>">
...
</form>
And the handler code.
<?php
...
// Notice that now you can use $_POST consistently.
if (isset($_POST['add1'])) {
$providerid = $_POST['providerid'];
...
The problem lines in $sql statement where it take variable $providerid as string, not a php variable. $_GET works fine even if sending a different protocals such as POST, PUT, DELETE,... Something like this should work as expected:
$sql = "SELECT *, GROUP_CONCAT(DISTINCT conditions.condition_name
SEPARATOR ', ') AS all_conditions FROM `providers` INNER JOIN
`conditions` ON `providers`.`id` = `conditions`.`prov_id` WHERE
`prov_id`= " . $providerid ;

PHP/MySQL Auto select option based on previous page

I have a music database with a PHP front end where you can add/edit/delete artists, albums, tracks using the web client. The last real problem I have is getting a select box to automatically select an option I pass to the page.
Example:
On a page called 'createCD.php' I have this code:
echo "<td><a href=\"editCD.php?cdTitle=".rawurlencode($row['cdTitle'])."&cdID=$row[cdID]&artID=$row[artID]&cdGenre=".rawurlencode($row['cdGenre'])."&cdPrice=$row[cdPrice]\" </a>Edit</td>";`
This is used as a link to the next page, and collects all the information about an album in the database and sends in to a page called 'editCD.php'.
Now on this page, all the information is used to fill out the webpage as shown here (there is more but for the purposes of this post, only the first select box matters):
Artist Name:
<!-- dropdown with artist name -->
<?php
echo '<select name= "artID" id="artID">';
while ($row = mysqli_fetch_assoc($result)){
echo '<option value="'.$row['artID'].'">'.$row['artName'].'</option>';
}
echo '</select>';
?>
<p>
Album Title:
<input id="cdTitle" type="text" name="cdTitle" value ="<?php echo htmlspecialchars($cdTitle); ?>" />
</p>
What I would like is for the "selected" option for 'artID' to be the value that is passed to the page. Using the associative array, I was able to display the 'artName' associated with the 'artID'. Currently, all the information about the album appears correctly apart from the 'artName' and it defaults to the first value. This is a problem as if a user simply clicks "Update" it will update the name to the default name, therefore changing the database entry by accident.
I know I need to be using
<option selected ...>
but I'm not sure on the syntax to use.
<?php
$artID = $_GET['artID']; // get the artID from the URL, you should do data validation
echo '<select name= "artID" id="artID">';
while ($row = mysqli_fetch_assoc($result)){
echo '<option value="'.$row['artID'].'"';
if ($artID == $row['artID']) echo ' selected'; // pre-select if $artID is the current artID
echo '>'.$row['artName'].'</option>';
}
echo '</select>';
?>
$artId = $_GET['artID'];
while ($row = mysqli_fetch_assoc($result)) {
$selected = $artId == $row['artID'] ? 'selected' : '';
echo '<option value="'.$row['artID'].'" '.$selected.'>'.$row['artName'].'</option>';
}
First you get the id via $_GET['artID']. (In a real scenario use intval or something to prevent sql injection)
Then check in the loop if the id from database is the same as the id from GET and when it is print "selected, else nothing.

Grabbing a value from a SELECT box in PHP

I've got a drop down select box that grabs each relevant value from an SQL database in a loop.
I'm creating a form so that when the "Submit" button is pressed it redirects to a PHP file that carries out the INSERT SQL statement. However because the select options are coming from a loop I'm unsure of how to grab the right value when its selected as it just grabs the last value gained from the loop.
I'm pretty sure that the way I have done it is the wrong way to go
<?php
echo"<select name='ModuleTitle' id='ModuleTitle' style='width:100%;'>";
echo"<option>Select...</option>";
//3. Perform database query
$result = mysql_query("SELECT * FROM Module
ORDER BY `ModTitle` ASC;", $connection);
if(!$result){
die("Database query failed: " . mysql_error());
}
//4. Use Returned Data
while ($row5 = mysql_fetch_array($result)) {
$module = $row5[2];
echo "<option name='{$module}'>".$row5[2]."</option><br />";
}
echo"</select>";
echo "<a href='submitREQ.php?id={$module}'><img src='images/submit.jpg' height='27'></a>";
?>
Instead of using <a href you should use <input type="image" value="submit" src="images/submit.jpg" />
To grab the value after the form is submitted you should use: $ModuleTitle = $_POST['ModuleTitle']; or $_GET if the method is get.

submit one or another query

I'm continuing to hack away at my newbie php/mySQL 'Invoicer' app.
I now have a form page in which I want to run one of two queries - either an INSERT or an UPDATE, depending on whether an ID is present. When present,
the ID is used to retrieve the record and pre-populate the form accordingly, which I have working. My problem now is that my conditional bits are
obviously not right because in either case when submitting the form the INSERT query is run, can't get the UPDATE to run, and I've exhausted my
understanding (and guess-ology).
I'd love to know why this ain't working, even if it's not the best approach, and I'm definitely open to suggestions to move the queries to a process.php,
etc. I'm also wondering if I should use 'if(isset($_GET['ID'])' to simply include one block or the other.
Many thanks in advance for any help or suggestions. (p.s. my intention is to overhaul for best practices/security once I've got the broad strokes wired up)
cheers, s
<?php
// CASE I: 'EDIT RECORD':
// If there's an ID ...
if (isset($_GET['ID']) && is_numeric($_GET['ID'])) {
$id = $_GET['ID'];
echo "<p class=\"status\"><strong>ID IS SET ... ergo we're editing/UPDATING an existing record</strong></p>";
// ... retrieve the record ....
$query = sprintf("SELECT * FROM Invoices WHERE ID = %s", $id);
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
// ... assign variables to pre-populate the form
$id = $row['ID'];
$invNumber = $row['invNumber'];
$invDate = $row['invDate'];
// [ snip: more variables > field data ]
// on submit: get the form values ...
// no worky: if (isset($_GET['ID']) && isset($_POST['submit'])) {
if (isset($_POST['submit'])) {
$invNumber = $_POST['invoice-number'];
$invDate = $_POST['invoice-date'];
$projNumber = $_POST['project-number'];
// [ snip: more variables > field data ]
// ... and UPDATE the db:
$qUpdate = "UPDATE Invoices SET invNumber='$invNumber', invDate='$invDate', projNumber='$projNumber', client='$client', task='$task', issueDate='$issueDate', subTotal='$subTotal', tax='$tax', invTotal='$invTotal', datePaid1='$datePaid1', datePaid2='$datePaid2', comments='$comments' WHERE ID='3'";
$result = mysql_query($qUpdate) or die(mysql_error());
if($result) {
echo "<p class=\"status\"><strong>SUCCESS: RECORD UPDATED!</strong></p>";
}
else die("DAMMIT JIM I'M A DOCTOR NOT A DB ADMIN!" . mysql_error());
} // CLOSE '(isset($_POST['submit']))
} // END CASE I: ID present
// CASE II: 'NEW RECORD'; query = INSERT
elseif (empty($_GET['ID'])) {
echo "<p class=\"status\"><strong>No ID ... ergo we're INSERTING a new record:</strong></p>";
// on submit: get the form values ...
if (isset($_POST['submit'])) {
$invNumber = $_POST['invoice-number'];
$invDate = $_POST['invoice-date'];
$projNumber = $_POST['project-number'];
// [ snip: more variables > field data ]
$qInsert = "INSERT INTO Invoices (invNumber,invDate,projNumber,client,task,issueDate,subTotal,tax,invTotal,datePaid1,datePaid2,comments)
VALUES('$invNumber','$invDate','$projNumber','$client','$task','$issueDate','$subTotal','$tax','$invTotal','$datePaid1','$datePaid2','$comments')";
$result = mysql_query($qInsert) or die(mysql_error());
if($result) {
echo "<p class=\"status\"><strong>SUCCESS: NEW RECORD INSERTED!</strong></p>";
}
else die("DAMMIT JIM I'M A DOCTOR NOT A DB ADMIN!" . mysql_error());
} // CLOSE '(isset($_POST['submit']))
} // END CASE II: No ID present
?>
and:
<form id="invoiceData" method="post" action="/html/form.php">
When you submit the form, you need to include the ID again, otherwise it is silently dropped off since you are posting to the hard-coded value /html/form.php (with ID removed). This will cause the empty($_GET['ID']) part to match and run, causing the INSERT. You can simply include the ID value back into the action of every form post like this:
<form
id="invoiceData"
method="post"
action="/html/form.php?ID=<?php echo $_GET['ID']; ?>"
>
This should work in both the cases of the UPDATE and the INSERT, because if there was no ID to begin with, this will render as /html/form.php?ID=, which will match the case of ID being empty, I believe. You may want to test this logic out for sure.
Hope this helps!
$_GET[ID] will be set if you pass it as a URL parameter. So if you change your <form> action to
<form id="invoiceData" method="post" action="/html/form.php?ID=12">
Where 12 is whatever ID you want, you should be getting the results you're wanting -- as long as you do have a <input type="hidden" name="submit" value="1" /> (value can be whatever) in your form somewhere as well.

Categories