Passing a <td> value to a php script - php

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

Related

Multiple actions for a single form

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.

Using a option to hold a value in php

Using php I have manage to search and display the data i need. Now I wish for the user to be able to select a option from a drop down menu and click update. Now when I try this it doesn't update the data for some reason. Are you able to notice any errors in the code below? I have included small bits of relevant code from the php file. I'm using the 'value=1' so that when I click update the query updates using the number rather than the text as i want to update a different field than the output field. Any ideas?
if (isset($_POST['update'])) { //once the update is click this updates the gametable with the adjusted information
$updatequery = "
UPDATE
GameTable
SET
GameID='$_POST[gameid]',
GameName='$_POST[gamename]',
PubID='$_POST[Publisher]',
TimePeriodID='$_POST[TimePeriod]',
SettingID='$_POST[Setting]', //the field i want to update using the value of the named select option
MoodID='$_POST[Mood]',
GameWeaponID='$_POST[Weapon]',
GameCameraAngleID='$_POST[CameraAngle]',
GamePlayerTypeID='$_POST[PlayerType]',
GameDescription='$_POST[Description]'
WHERE
GameID='$_POST[gameid]'";
mysqli_query($dbcon, $updatequery);
echo "Record successfully updated";
};
//query that fetches data from a database and outputs.
while ($row5 = mysqli_fetch_array($result5)) {
echo "<tr> <th> Setting ID</th> </tr>";
echo "<td><select class='text-black input-button-rounded' name='Setting'>";
//the output is a different field to the one I want to update so that's why I want to use the value.
echo "<option disabled selected>" . $row5['SettingName'] . "</option>";
echo "<option class='text-black' type='text' value=1>Western</option> ";
echo "<option class='text-black' type='text' value=2>Space</option>";
echo "<option class='text-black' type='text' value=3>City</option>";
echo "<option class='text-black' type='text' value=4>Sea</option>";
echo "<option class='text-black' type='text' value=5>Apocalypse</option>";
echo "</select></td><br>";
//update button
echo "<td>" . "<input class=text-black input-button-rounded type=submit name=update value=Update" . " </td>";
I think your problem is that your select and submit button need to be wrapped in a <form> element, so that when the "Update" button is clicked, it POSTs the Setting data as well.
A few other things to note:
All the quotes for the values of the HTML attributes are missing from the line which has your button code. Also the quotes for the array keys of $_POST in your SQL statement e.g. you wrote$_POST[Mood] rather than $_POST['Mood'] Why is that?
You don't need type="text" for the option tags.
If you really want to build a secure website/app you shouldn't be using raw SQL statements. Rather, make use of either PDO or MySQLi prepared statements.

Accessing a variable from another file in PHP, SQL

<?php
$paseoLocationTo=$_POST['locationTo'];
$paseoLocationFrom=$_POST['locationFrom'];
$PTime=$_POST['time'];
echo"The value of Location to is $paseoLocationTo </br>";
echo"The value of Location from is $paseoLocationFrom </br>";
echo"The value of time is $PTime </br>";
mysql_connect('localhost', 'root', '')
or die(mysql_error());
mysql_select_db('shuttle_service_system')
or die(mysql_error());
$TripID =mysql_query("
SELECT DISTINCT Trip_ID as 'TripID'
FROM trip
WHERE Timeslot LIKE '$PTime' AND Location_From Like '$paseoLocationFrom' AND Location_To LIKE '$paseoLocationTo'
");
echo "<form action='LastPage.php' method='post'>";
while($check = mysql_fetch_array($TripID))
**echo "<name='TripID' id='TripID'>" . $check['TripID'] . " ";**
echo "<p class='sure'> Are you sure with your reservation? </p>";
echo"<input type='submit' value='Submit' class='Log'>";
echo"</form";
?>
From another php file, this the LastPage.php
<?php
**$TripID=$_POST['TripID'];
echo"The value of trip ID is $TripID </br>";**
?>
Hi guys I was wondering why I can't access the "TripID" variable in the other php file? I was accessing it before but now there seems to be a problem, am I doing it right? I'm sorry a php and SQL newbie.
You need to add
<input type="text" name="TripID" value="'.$check['TripID'].'" ... />
in your form in order to retrieve values with $_POST['TripID'].
There is no such thing as
**echo "<name='TripID' id='TripID'>" . $check['TripID'] . " ";**
which was found in your code.
**echo "<name='TripID' id='TripID'>" . $check['TripID'] . " ";**
Looks like that should be:
echo "<input type='text' name='TripID' id='TripID' value='" . $check['TripID'] . "' />";
If you don't want it to be editable, display it then add a hidden field:
echo $check['TripID'];
echo "<input type='hidden' name='TripID' id='TripID' value='" . $check['TripID'] . "' />";
Basically, you're not putting your trip id into an actual form tag, so it's not getting posted over to your LastPage.php.
Edit: fixed the first input to wrap the tripID in the value attribute.
Replace following lines
**echo "<name='TripID' id='TripID'>" . $check['TripID'] . " ";**
with
echo "<input type="hidden" name="TripID" value="'.$check['TripID'].'" />";
So it will not be visible to user on current page but when you will post the Form, it will be available in $_POST['TripID'] variable.
One more thing your tag is not properly closed.
Use MySQLi and prepared statements to prevent SQL injection.
PS: accept the answer if its work for you.
Your form tag is not closed properly. It is now as echo </form";
It should be echo"</form>";
Also you didnt added name in input tag.
It should be
echo"<input type='submit' value="$check['TripID']" name="TripID" class='Log'>";
There is no name tag <name> but you used how?

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.

Save several checked values to MySQL database

I have a PHP form, which in the end is going to write all the filled in data to a MySQL database. That's all fairly doable, but here is something tricky that I don't know how to handle:
I have a DIV which requests all the rows of one table. Every row represents a category and the user can choose several categories to add to their post. This is the code I use to retrieve the rows + checkbox in front of them:
<?php
$sql = "SELECT merknaam FROM merken";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo " <input type=\"checkbox\" name=\"merken\" value='" . $row['merknaam'] . "'> " . $row['merknaam'] . " <Br /> ";
}
?>
The user can choose multiple categories, and I would like to save them all and write them to my database. All the categories should be written to 'one' column called 'categories', but the seperate categories should still be distinguishable.
Might be a tricky one? Hope someone can help!
Change the code for the checkboxes to:
echo " <input type=\"checkbox\" name=\"merken[]\" value='" . $row['merknaam'] . "'> " . $row['merknaam'] . " <br /> ";
Adding the [] after the name will allow PHP to treat the checkboxes as an array, which you can serialize and store in your database.

Categories