Multiple actions for a single form - php

I have an html homepage which has a form. The form submit button sends the query to a single php page called First.php which gives the necessary data from the database in a tabular format. A single column from the table contains links as the contents of the column are too large to display on the same page. Once the link is selected, it gives the exact column information of only that query which I submitted on the homepage.
My general idea was to give two actions to the form action which can be used on two different pages but that to no result.
Here's the homepage :
<form action="First.php" action ="Second.php" method="POST">
<input type="text" size="90" name="search1">
<input type="hidden" size="90" name="search1">
<input type="submit" name="submit" value="Search..">
</form>
First.php after connecting to database and the firing the sql query :
if($ant>0)
{
while($row=mysql_fetch_array($res))
{
echo "<tr>";
echo "<td>" . $row['A'] . "</td>";
echo "<td>" . $row['G'] . "</td>";
echo "<td><b href='Second.php'>Link</b></td>";
echo "</tr>";
}
}
Please do help me for the Second.php.
Any help would be deeply appreciated.
Thank you!

This is common pagination problem. You should use extra parameter in your form.
do something like
if($ant>0)
{
while($row=mysql_fetch_array($res))
{
echo "<tr>";
echo "<td>" . $row['A'] . "</td>";
echo "<td>" . $row['G'] . "</td>";
echo "<td><b href='First.php?page=2'>Link</b></td>";
echo "</tr>";
}
}

You do not need a second action at all (and you cannot have one). What you need is to pass the id of the row to Second.php as a GET parameter. If you are not familiar with the concept, look it up because you will need it. A lot.
In Second.php you do not need the search parameters anymore because you are showing the details about a single row and you have its id. You just make a query to the DB to retrieve it by id and the old search becomes irrelevant.
In good conscience I have to say that the mysql_-something functions are a BAD idea. They have been removed in newer versions of php and are dangerous to use in the old ones. I strongly suggest that you use PDO and prepared statements ot at least the mysqli_ family of functions.

Related

Switch between different views using href

I'm coming here after some head banging. Still learning php/mysql and coming across an issue which is bothering me for a while.
Currently I print a table with all the data without any condition. The values below the lower values and above are printed in this table. The snippet of my code is below:
while ($result = mysql_fetch_assoc($records)){
echo "<tr>";
echo "<td>" .$result['id']. "</td>";
if ($result['time'] > $limit[lower]){
echo "<td bgcolor=#ff0000>" $result['time']. "</td>";
} else {
echo "<td>" .$result['time']. "</td>";
}
echo "<td>" .$result['name']. "</td>";
echo "</tr>";
}
I want to create a href link so that by dafault only values above the lower are printed and on clicking the link, say detailed_view will give the table as it does above i.e. all value including below and above the lower value. Shall I create two methods and use them in href separately. In that case there will be two while loops which I want to avoid. Any pointer on this?
The name of the script is display.php, so before the loop I tried using:
echo "<a href='display_jobid.php?view=$num'>Show All</a>";
It does create a hyperlink Show All but how to get the functionality working, am not sure.
Thanks

Passing a <td> value to a php script

Sorry if this is a noob question, but I'm still getting up to speed with PHP and can't find an answer to this one.
I have a php script that queries a mySQL table and then builds an HTML table from the results. This all works just fine. As part of that script, I add a <td> to each <tr> that gives the user a chance to delete each specific record from the database, one by one, if they so choose.
To make this work, I have to be able to pass over to the php script the unique identifier of that record, which exists as one of the values. Problem is, I don't know how to pass this value.
Here is my php script that builds the HTML table:
while ($row = mysql_fetch_array($result)) {
echo
"<tr class=\"datarow\">" .
"<td id=\"id_hdr\">" . $row['id'] . "</td>" .
"<td id=\"name_hdr\">" . $row['name'] . "</td>" .
"<td id=\"btn_delete\">
<form action=\"delete_item.php\">
<input type=\"image\" src=\"images/delete.png\">
</form>
</td>" .
"</tr>";
}
So, somehow I either need to explicitly pass 'id' along with "delete_item.php" and/or find a way on the php side to capture this value in a variable. If I can accomplish that I'm home free.
EDIT: Trying to implement both suggestions below, but can't quite get there. Here is how I updated my form based on how I read those suggestions:
"<td id='btn_delete'>".
"<form action='scripts/delete_item.php'>".
"<img src='images/delete.png'>".
"<input type='hidden' id='uid' value='" . $row['id'] . "'>".
"<input type='submit' value='Submit'/>".
"</form>".
"</td>" .
Then, in delete_item.php, I have this:
$id = $_POST['uid'];
$sql = "DELETE FROM myTable WHERE id=$id";
$result = mysql_query($sql);
if (!$result) {
die("<p>Error removing item: " . mysql_error() . "</p>");
}
But when I run it, I get the error:
Error removing item: You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near '' at line 1
And one final thing: this approach gives me a button with the word 'submit' directly under my image. I'd prefer not to have this if possible.
Thanks again!
<form action=\"delete_item.php\">
<input type=\"hidden\" value=\"$row['id']\" name=\"uid\" >
<input type=\"image\" src=\"images/delete.png\">
</form>
The unique id is placed in a hidden input. You can get this value using
$_POST['uid']
But you need to submit the form
<input type=\"submit\" name=\"submit\" value=\"delete\" ">
You could use an anchor tag with parameter for id.
ie, www.example.com/delete.php?id=20
Now you could get that id on page delete.php as $_GET['id']
Using that you could delete the data from the table and return to the required page by setting up header
If you required you could use the same logic with AJAX and with out a page reload you could permenently delete that data. I would recommend AJAX

Using an incremented value in a SELECT WHERE query MYSQL

Let me start off that I have only been coding for the past few months. I know I've probably got a ton of mistakes or bad practices everywhere. I like constructive criticism, so please let me know what i can do better, along with how to address my current issue.
This code's purpose is to create a table of part numbers, and their associated location column data (storage type, Rack number, Shelf number) based on previously entered information. I've got the entry form working perfectly. I type in a number of parts I want to search for, and it posts that number back to itself. I'm then presented with that number of text input fields to put in part numbers.
//this form is to submit the number of parts you're looking for,
//and posts back to itself
<form action=View2.php method="post">
<input type="text" name="num">
<button type="submit">Number of Parts</button>
</form>
//This form takes the posted number, and creates that many text fields,
//populated with the number part you are entering.
<form action="List.php" method="post">
<?php while ($i<=$num){
echo "<input type='text' name='part$i' value='part$i'><br><br>";$i++;}?><input type="hidden" name="num" value="<?php $num?>">
<button type="submit">Submit</button>
</form>
My problem comes with running a mysqli_query to populate the table. I'm stuck as to where to go from here. I know that i need to take each part number that gets posted, and use it as the criteria in a SELECT WHERE search, so i made this While loop:
<?php
echo "<table border='1'>
<tr>
<th>Part Number</th>
<th>Location</th>
<th>Rack</th>
<th>Shelf</th>
</tr>";
while($i<=$num){
$x=$_POST["part$i"];
$result = ($con,"SELECT * FROM parts WHERE pn ='$x'");
$row = ($result);
echo "<tr>";
echo "<td>" . $x . "</td>";
echo "<td>" . $row['rcb'] . "</td>";
echo "<td>" . $row['ra'] . "</td>";
echo "<td>" . $row['sh'] . "</td>";
echo "</tr>";
$i++;
}
echo "</table>";?>
The page crashes at this point, but if i comment out the $result line, i'll get the table with the part number fields populated with the values from the previous page.
Anyone have any idea what i'm doing wrong, or how i can do it better?
This line doesn't do anything good :
$result = ($con,"SELECT * FROM parts WHERE pn ='$x'");
You need to actually query the DB.
$mysqli = new mysqli("localhost", "my_user", "my_password", "...");
...
$result = $mysqli->query("SELECT * FROM parts WHERE pn ='$x'");
You should use prepared statements so your code isn't open to sql injections though...

Loop through data creating multiple forms to submit

I am opening a file (formatted in rows and columns) with PHP, looping through the rows on the file and echoing out rows into a table that meet a certain criteria. On each row that I echo out I am wrapping it in form tags. Ultimately, if I echo out 20 rows I will echo out 20 forms, each of them having a button. I am also echoing out a column with a comments box. I want the end user to be able to go to this page, enter comments on each row, and then hit the submit button to store the results of the row into a database. I have 2 problems that I do not know how to overcome.
1.) When echoing out the results to the table I do not create a static variable to reference when I go to create my SQL insert statement. How do I label each piece of data so I can call it later?
2.) There are going to be multiple forms, and the user will only be using one at a time. How do I ensure that when the user clicks submit, it only submits the data fields from the same row?
Hopefully this makes sense. If not Im happy to add as much clarification as needed. Im definitely a newbie when it comes to PHP, so I'm certain this is a poor design but Im on a tight timeline and I just need a working product for now. Next week I can go back and perhaps implement a better solution I'm sure one you kind people will suggest:)
<?php
if (($handle = fopen("name of file to open here", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
if ($data[4] == $login){
$num = count($data);
echo "<form action='analyzer.php' method='post'>";
echo "<tr>";
echo "<td>";
echo $data[1];
echo "</td>";
echo "<td>";
echo $data[2];
echo "</td>";
echo "<td>";
echo $data[3];
echo "</td>";
echo "<td>";
echo $data[4];
echo "</td>";
echo "<td>";
echo $data[5];
echo "</td>";
echo "<td>";
echo $data[6];
echo "</td>";
echo "<td>";
echo $data[7];
echo "</td>";
echo "<td>";
echo $data[8];
echo "</td>";
echo "<td>";
echo "<input type='text' name='comments' />";
echo "</td>";
echo "<td>";
echo "<input class='mybutton' type='submit' name='#' value='Submit' />";
echo "</td>";
echo "</tr>";
echo "</form>";
}
fclose($handle);
}
}
?>
1.) When echoing out the results to the table I do not create a static variable to reference when I go to create my SQL insert statement. How do I label each piece of data so I can call it later?
You need some way of uniquely identifying the piece of data. You can do this using hidden input variables.
2.) There are going to be multiple forms, and the user will only be using one at a time. How do I ensure that when the user clicks submit, it only submits the data fields from the same row?
You can name the forms or assign them a sequence in an array. For example:
<input type="submit" name="form[5]" />
You can also simplify your code by using a loop like this:
foreach( $data as $key=>$val ) {
echo "<td>$val</td>";
}
I know there is already an accepted answer here, but I feel like suggesting another way of doing this. Having a bunch of forms on one page each with their own submit button and requiring a page load every time is kind of cumbersome from a UI perspective.
My suggestion is that you start the long, painful, and rewarding process of learning Ajax. I have been learning jQuery AJAX and I use it to do similar things.
Example:
I have a table with 30 rows, each of which represent a process.
Each row has a checkbox.
I have a submit button down at the bottom, where a user can submit all the rows with checked boxes.
But, I also have buttons in each row (right next to the checkboxes actually). The buttons are simply labeled "now", and when you click them, that row is processed in the background without a page reload.
So I have allowed users to submit many rows with the normal form submit button if they want, OR to submit any individual row and not have to wait for the page to reload.
I can perhaps add some code here if anyone is ever interested.

How to delete a record from HTML table?

I have this codes so far:
This form is generated during a query loop
while ($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td>" . $row['breed'] . "</td>";
if($row['neuteredOspayed']=="1"){
echo "<td>" . "neutered" . "</td>";
}else
echo "<td>" . "spayed". "</td>";
echo "<td>" . $row['priceFee'] . "</td>";
if($row['housebroken']=="1"){
echo "<td>" . "yes" . "</td>";
}else
echo "<td>" . "no". "</td>";
if($row['goodwithdogs']=="1"){
echo "<td>" . "yes" . "</td>";
}else
echo "<td>" . "no". "</td>";
if($row['goodwithcats']=="1"){
echo "<td>" . "yes" . "</td>";
}else
echo "<td>" . "no". "</td>";
echo "<td>" . $row['status'] . "</td>";
echo "</tr>";
}
echo "</table>";
Now, is there a way to put a link saying "delete" next to every result? For example next to the status field?
Here is what it's looking like:
To get this deleted I guess that I need to spot the record somehow. What I need is to take the name of the animal. For example, how can I get the value "Sparky" from the table and assign it to a variable? If I have the name I would be able to make the checks and run a query witch will delete the record.
You will have to use Javascript and AJAX.
Basically, you'll want to put a button in a cell, one per row, and when it's clicked, pass the id of the record to be deleted back to a PHP script via AJAX, then remove the record from the database. It should also hide the row when it is clicked.
I'd recommend using jQuery's .ajax(), as raw XHR is painful at best.
There is no way to do this with just PHP, because HTTP is stateless. Once your web page is loaded, the HTML and PHP parts are done, and fixed. You'll HAVE to use Javascript to make consecutive requests.
Alternatively, as bcmcfc points out, you can also just have a hyperlink to a script that will delete a record from your database.
You'd need something like this in your while loop:
echo '<td>Delete</td>';
Using the table's primary key would be better than the name though - is the name unique in the db? Assuming there is a PK and it's called id:
echo '<td>Delete</td>';
Php just is for page generation, once you have generated that table you cannot modify it.
You could, however, make a new get request, specifying a parameter with the row name to delete, you have to change your server php code to take in account this parameter, though.
The best, according to me, is using javascript: you assign a td id to each row and then you write a simple function in which you delete that row.
You have to submit the form and do this action....
<input type="submit" name="submit" value="Delete" />
After submit the form will redirected to some page. In that page you got all the posted values. In that you can delete the record by using the record id otherwise you use the name for appropriate record.
$query = "DELETE FROM table_name WHERE name='$_POST['name']'";
(or)
$query = "DELETE FROM table_name WHERE id='$_POST['id']'";
After this execution you have to redirect the URL to that page.
(or)
Delete
In this file you have to written like this...
$id = $_REQUEST['id'];
$query = "DELETE FROM table_name WHERE id='$id'";
//Add this form before the end of the while loop
<form action="#" method="post">
<input type="hidden" name="name" value="<?php echo $row['name']?>">
<input type="submit" name="delete" value="delete">
</form>
//Add this at the end of the coding
<?php
if(isset($_POST['delete']))
{
//database connection
$sql="DELETE FROM `table_name` WHERE `name`='{$_POST['name']}'";
$queryEXE=mysql_query($sql);
}
?>
You add a "elemID" attribute to each of your <tr>s and a new class that would be individual for each row (for example, elem+the id):
<tr elemId="12" class="elem12">...</tr>
Then, for the Delete link, you use AJAX to call the page that deletes the row from your DB, passing the elemID as an argument to this function:
function deleteRow(thisElemID) {
$.ajax({
url: yourURL,
data: {'elemID', thisElemID },
success: function() {
$('.elem'+thisElemID).remove();
}
});
}
More on $.ajax here.
Create another cell in your table and call ajax onclik of that button. Inside your ajax call delete the pecific row
Use a 'delete' form for each row.
The best way would be to add, for each row, a form with a submit button. Each form has a hidden field containing the id (or name, if you must) of the record to delete. Set the method of the form to 'post'.
Reasons why:
A delete link (a href) can be indexed and bookmarked easily. You
don't want pets to be deleted everytime Google drops by or a user is
browsing through their history.
A method='get' form also can cause
the url to be bookmarked and/or show up in the history. The method
with a form will work without Javascript altogether.
Apart from that,
Any solution (both forms and links) can easily be 'upgraded' to a solution with Ajax for a better user experience, but that's always an extra and no core functionality.
If you like, you can style the submit button to look like a link.
Use the post-redirect-get pattern if you implement this solution.
That is, assuming you want to actually remove the record from the database. If you just want to alter the HTML, a Javascript soliution would make more sense.

Categories