Dynamically creating buttons that remove a row from a table - php

I'm trying to create a button for each row in my database that, when pressed, will delete this particular row. I should also mention that the data from the database is displayed correctly and the table I'm using is also completely fine.The buttons appear at the side of each row, when the button is clicked, the row dissapears but the data is not deleted from the database, when the page is reloaded the rows that were previously "deleted", reappear. After pressing the button i also get this "Fatal error: Uncaught Error: Call to undefined function mysql_query() in C:\xampp\htdocs\INDUSTRIALPROJECT\records.php:56 Stack trace: #0 {main} thrown in C:\xampp\htdocs\INDUSTRIALPROJECT\records.php on line 56".
line 56 is : $del = mysql_query("DELETE FROM records WHERE id=" . $row['id']);. The same query works fine when placed directly into phpMyAdmin.
<?php
// Check connection
include_once 'config.php';
if ($link->connect_error) {
die("Connection failed: " . $link->connect_error);
}
$sql = "SELECT * FROM records";
$result = $link->query($sql);
function post($key){ return(isset($_POST[$key]) ? htmlspecialchars($_POST[$key]) : ""); }
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if(post('rowButton'.$row['id']) =="Delete"){
$del = mysql_query("DELETE FROM records WHERE id=" . $row['id']);
$deleted = '<p>Entry ' . $row['id'] . ' was succesfully deleted</p>';
}
else {
echo '<form action ="' . $_SERVER['PHP_SELF'] . '" method="post">';
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row["visitingdate"]. "</td>";
echo "<td>" . $row["department"] . "</td>";
echo "<td>" . $row["visitingreason"]. "</td>";
echo "<td>" . $row["importance"]. "</td>";
echo "<td>" . $row["visitorname"]. "</td>";
echo "<td>" . $row["company"]. "</td>";
echo "<td>". $row["internalrecipientname"]. "</td>";
echo "<td>". $row["visitinglocation"]. "</td>";
echo "<td>". $row["ETA"]. "</td>";
echo "<td>". $row["ETD"]. "</td>";
echo "<td>". $row["HRverification"]. "</td>";
echo "<td>". $row["visitcompleted"]. "</td>";
echo '<td><input type="submit" name="rowButton'. $row['id'] .'" value="Delete"/> </td>';
echo "</tr>";
echo "</form>";
}
}
echo "</table>";
echo $deleted;
}
else { echo "0 results"; }
$link->close();
?>

First, this appears to be rather vulnerable to SQL injection attacks. StackOverflow is quite font of pointing this out up front, because it's really a solved problem that you should account for in the early stages of development. You're taking untrusted data (that was submitted by the user, without sanitizing it) and putting it directly in an SQL query. Bad things can happen when that occurs. Now with that aside, on to your actual question.
"Nothing happens" means the page doesn't change at all, right? So the browser doesn't know what to do when the button is clicked.
I think you haven't put any <form...> declaration here, which would be required for <input type="submit"> to do anything useful. You could use JavaScript with the stand alone submit button, but I don't see that in your code, either. You'll need something to tell the browser what to do when the submit button is pressed.
I haven't really tested the rest of your code, but based on what you've got already you might add the following:
else {
+ echo '<form action ="' . $_SERVER['PHP_SELF'] . '" method="post">';
echo "<tr>";
and
echo "</tr>";
+ echo "</form>";
}
(don't add the plus sign, that's just to show which line is added). I should add that I don't usually use submit buttons like this, so there's a chance I missed some additional details about how you're calling this, but putting the form in a <form> tag is at least a good start.
Edit
The mysql_query() function was removed in PHP 7; if you're using an older PHP you need to add support for the MySQL functions or if you're on PHP 7, you should use the MySQLi or PDO_MySQL functions instead. The warning box on the PHP manual page for mysql_query has some links for alternatives, how to select an alternative, and other supporting documentation that may help you. This StackOverflow answer may help, as well.

Related

PHP array initialized inside if($_POST) block can't be used outside of it

I have been looking all over to find out why this is happening, but to no avail. I have a 2-step process to update specific rows (to approve timesheets) in a mySQL database based off what checkboxes are checked. In the first screen, the user checks whichever checkboxes associated with the timesheet she or he wants to update. On the next screen, I display the rows associated with those checkboxes, a confirmation page - if you will. On this confirmation page, I successfully set and echo out an array that is simply a copy of the $_POST checkbox array, called 'approvebox'. Despite this, I seemingly cannot use this array anywhere outside of the "if($_POST)" block that it is created in.
Here is the code associated with creating the first page, where the user must check the checkboxes for each timesheet she/he wishes to approve:
if($_POST['submit']){
...
...
while ($row = mysqli_fetch_assoc($tblresults)){
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['timesheetsid'] . "</td>";
echo "<td>" . $row['unixstamp'] . "</td>";
echo "<td>" . $row['total_hours'] . "</td>";
echo "<td>" . $row['coordinatorid'] . "</td>";
echo "<td>" . $row['status'] . "</td>";
echo "<td>(<a href='./currenttimesheets.php?timesheetsid=" . $row['timesheetsid'] . "'>View</a>)</td>";
echo "<td> &nbsp &nbsp &nbsp <input type='checkbox' name='approvebox[{$row['timesheetsid']}]' value='{$row['timesheetsid']}' /></td>";
echo "</tr>";
}
Here is the code in which I successfully set and echo the array that is a copy of the $_POST approvebox array. Also worth noting that I actually use the approvebox array from the if($_POST['submit']) block in a foreach loop to populate the resulting rows the user selected from the prior screen:
if($_POST['appove']){
...
...
foreach ($_POST['approvebox'] as $approvebox){
...
...
while($row = mysqli_fetch_assoc($tblresults)){
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['timesheetsid'] . "</td>";
echo "<td>" . $row['unixstamp'] . "</td>";
echo "<td>" . $row['total_hours'] . "</td>";
echo "<td>" . $row['coordinatorid'] . "</td>";
echo "<td>" . $row['status'] . "</td>";
echo "<td>(<a href='./currenttimesheets.php?timesheetsid=" . $row['timesheetsid'] . "'>View</a>)</td>";
echo "</tr>";
}
}
echo "</table>";
print_r($_POST);
$selectedtimesheets = array();
$selectedtimesheets2 = array_merge($selectedtimesheets, $_POST['approvebox']);
//$selectedtimesheets2 is successfully set to the $_POST array here
print_r($selectedtimesheets2);
Finally, here is the second if($_POST) block, in which I try to use the $selectedtimesheets2 array in, but to no success, it doesn't echo out anything:
if($_POST['accept']){
print_r($_POST);
//$selectedtimesheets2 does not get echoed out, despite being successfully set and echoed previously..
print_r($selectedtimesheets2);
echo $selectedtimesheets2;
It sounds like you are doing two requests. Whatever was in the superglobal _POST after the first request won't be in the next request.
To preserve data between requests, you can use PHP sessions.
You could do something like this: on first request, save that array into the session:
session_start();
$_SESSION["selectedtimesheets2"] = array_merge($selectedtimesheets,
$_POST['approvebox']);
Then in your next request, you can retrieve it:
$selectedtimesheets2 = $_SESSION["selectedtimesheets2"]
Does that make sense? This is very crude, I would suggest maybe using a framework like Symfony, Laravel or Lumen, depending on size of your project. HTTP requests have been abstracted and are much easier/safer to manipulate. Also have a look at the HTTP foundation package from Symfony.
shouldn't print_r($_POST); be print_r($_POST['approve']);

How to put user input into a SQL Query

I have a database and I want the user to be able to have an input into what comes out. i.e
Select from Table where example = user input from box **(input by the user)**
Im guessing what I need is a variable to hold the value that then goes into the statement. I know how to get the value from the input box with script but can I use it like:
select * From handover WHERE hdate = variable. However I am guessing someone is going to talk to me about security if its even possible.
<html><body>
<input>User input</input> //That needs to go into statement
<?php
include 'config.php';
$result = mysqli_query($con,"SELECT * FROM handover WHERE hdate = **user input**;");
echo "<table border='1'>
<tr>
<th>hdate</th>
<th>Delay</th>
<th>Health and Safety</th>
<th>Non Vsa</th>
<th>VSA</th>
<th>Dar</th>
<th>Other</th>
<th>Hour</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['hdate'] . "</td>";
echo "<td>" . $row['hdelay'] . "</td>";
echo "<td>" . $row['hs'] . "</td>";
echo "<td>" . $row['nv'] . "</td>";
echo "<td>" . $row['vsa'] . "</td>";
echo "<td>" . $row['dar'] . "</td>";
echo "<td>" . $row['other'] . "</td>";
echo "<td>" . $row['hour'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Any help is welcome and advice on the best language to use for this.
Kind Regards
Fintan
first of all, this question has nothing to do with javascript & ajax. so you can delete those tags.
you want to show/search data from mysql.
$result = mysqli_query($con,"SELECT * FROM handover WHERE hdate = '".$_POST['abc']."' ");
this is when you want to check if hdate column have exact data as user input ( $_POST['abc'] ).
and also don't forget to use mysqli_real_escape_string
you can learn common mysql pattern queries from here: http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html

Sending MySQL data to page through link in a table

We are currently working on a game shop website and have hit a roadblock regarding the purchase link.
The link displays within a mysql table and each link sends the user to the same page.
This is necessary as we will be adding new games to the database and want to do using only a mysql command to make the site as efficient as possible.
This is the code of the table (ignore the fact that the purchase link displays the 'gameCodes'.
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['gameName'] . "</td>";
echo "<td>" . $row['pointsValue'] . "</td>";
echo "<td>" . ''. $row['gameCodes'] .'' . "</td>";
echo "</tr>";
}
echo "</table>";
What I am wanting to do is send the game code of the game that corresponds with the row the link is on to the Purchase.php page to then process the purchase.
Any help is appreciated greatly.
my answer deals with not only passing variables from url to your page....but passing it in clean way
First, make sure that url URL properly encode using "PHP urlencode"
echo "<td>" .
'<a href="Purchase.php?gameCodes='.urlencode($row['gameCodes']) .'">'.
$row['gameCodes'] .
'</a>' .
"</td>";
Then to fetch the data strip_tags from the url variable if any:
echo (strip_tags($_GET['item']));
why is this needed??
Since you are fetching the values from URL, assume i manually change the url to :
Purchase.php?gameCodes=<script>alert("hello")</script>
then without proper handling, gameCodes variable value will be fetched and it would alert "hello" on the page
Have you thought about sending it through the URL like follow:
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['gameName'] . "</td>";
echo "<td>" . $row['pointsValue'] . "</td>";
echo "<td>" . ''. $row['gameCodes'] .'' . "</td>";
echo "</tr>";
}
echo "</table>";
and then process to the purchase using the code sent in the URL
let me know if it corresponds to what you need.
I think you can put the gameCodes id directly in the link
echo "<td>" .
'<a href="Purchase.php?gameCodes='. $row['gameCodes'] .'">'.
$row['gameCodes'] .
'</a>' .
"</td>";
Now you can process the code from the purchase page and retrieve it with $_GET
$_GET['gameCodes'];

mysqli dynamic generated table with link that opens form with all values from row

I have this table:(megaoverzicht.php) (I left out the part where it connects to the db)
echo "<table border='1'><tr><th>Formulier Id</th><th>Domeinnaam</th><th>Bedrijfsnaam</th><th>Datum</th><th>Periode</th><th>Subtotaal</th><th>Dealernaam</th><th>Offerte Maken</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['formuliernummer'] . "</td>";
echo "<td>" . $row['domeinnaam'] . "</td>";
echo "<td>" . $row['bedrijfsnaam'] . "</td>";
echo "<td>" . $row['datum'] . "</td>";
echo "<td>" . $row['periode'] . "</td>";
echo "<td> € " . $row['subtotaal'] . "</td>";
echo "<td>" . $row['dealercontactpersoon'] . "</td>";
echo "<td><a href='offertemaken.php?id=" . $row->id . "'>Offerte Maken </a></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
I want to open offertemaken.php when the user clicks on Offerte Maken. It needs to open the form with the data from that row(id).
This is the code from (offertemaken.php)(I left out the part where it connects to the db)
<?php
$id=$_POST['id'];
$data = 'SELECT * FROM cypg8_overzicht WHERE id="$id"';
$query = mysqli_query($con,$data) or die("Couldn't execute query. ". mysqli_error());
$data2 = mysqli_fetch_array($query);
?>
<form>
<div class="formcontainer" onmousemove="">
<input type="text" name="datum" id="datum" value="<?php echo $data2[datum]?>">
<input type="text" name="formuliernummer" id="formuliernummer" value="<?php echo $data2[formuliernummer]?>">
<input type="text" name="periode" id="periode" value="<?php echo $data2[periode]?>">
<input type="text" name="domeinnaam" id="domeinnaam" value="<?php echo $data2[domeinnaam]?>">
<input type="text" name="bedrijfsnaam" id="bedrijfsnaam" value="<?php echo $data2[bedrijfsnaam]?>">
<input type="text" name="dealercontactpersoon" id="dealercontactpersoon" value="<?php echo $data2[dealercontactpersoon]?>">
</div><!--/.formcontainer-->
</form>
I cant get it to work. I am missing something I think! I make an error in the codes below:
echo "<td><a href='offertemaken.php?id=" . $row->id . "'>Offerte Maken </a></td>";
$id=$_POST['id'];
$data = 'SELECT * FROM cypg8_overzicht WHERE id="$id"';
I have been looking at a lot of tutorials but cant understand what i am doing wrong. Here a list to show that i am not just asking but actually have been looking for a solution by myself.
http://www.daniweb.com/web-development/php/threads/341921/-php-mysqli-update-database-using-id-syntax-help-requested-
http://www.codeofaninja.com/2012/01/phpmysqli-update-record.html
I have looked at many more but i don’t want to bother all of you with an extreme long list of links. And i am not allowed because my rep is not big enough! Dont downvote me please!
Question
I want to open offertemaken.php when the user clicks on Offerte Maken. It needs to open the form with the data from that row(id)?
Edit 1 Getting closer to the endresult
I found out(thanks to Cuba32) that the link in megaoverzicht.php was doing nothing so i changed the following
<a href='offertemaken.php?id=" . $row->id . "'>
to
<a href='offertemaken.php?id=" . $row['id'] . "'>
Now it is creating these kind of links:
something/formulieren/overzichten/offertemaken.php?id=24
This is a good thing(i think) but the form that opens is blank so offertemaken.php is doing nothing with the id???
Edit 2 (Thanks to Cube32)
Since yesterday the code has changed quite a bit. I belive that megaoverzicht.php is finished it sends the link as described in edit 1. The only problem is know in offertemaken.php. Below i will put in the code.
$con = mysqli_connect($server,$username,$password,$database);
if (!$con){
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,$database);
$id=$_GET['id'];
if($data = mysqli_prepare($con, 'SELECT * FROM cypg8_overzicht WHERE id="?"'))
{
/* bind parameters for markers */
mysqli_stmt_bind_param($data, "s", $id);
/* execute query */
mysqli_stmt_execute($data);
$data2 = mysqli_stmt_fetch($data);
But this code gives me the following error.
Warning: mysqli_stmt_bind_param(): Number of variables doesn't match number of parameters in prepared statement in line 31. Line 31:
mysqli_stmt_bind_param($data, "s", $id);
I dont know how to solve this part. I will offcourse be looking on the internet to try and find a solution but if anyone knows it please post it. Thanks in advance.
Edit 3<= No more error (Thanks to Your Common Sense)
by changing WHERE id="?"' into WHERE id=?' i no longer have the error. But still it is not showing anything in the input fields
Edit 4<= Getting to confused and going back to original code.
Thanks for everyone who got me so far. But I can't see the forest anymore through the trees. I am going back to the original code and try to solve that. So the code is now as follows:
$id=$_GET['id'];
$data = 'SELECT * FROM cypg8_overzicht WHERE id="$id"';
$query = mysqli_query($con,$data) or die("Couldn't execute query. ". mysqli_error());
$data2 = mysqli_fetch_array($query);
error_reporting(E_ALL);
But this gives the following errors inside the input fields:
Notice: Use of undefined constant formuliernummer - assumed 'formuliernummer' in offertemaken.php on line 37
This error goes for all the input fields.
Edit 5
Fixed this by changing <?php echo $data2[formuliernummer]?> to <?php echo $data2['formuliernummer']?> but it is still not showing the information.
Edit 6 THE SOLUTION
I added the answer to the question below. Just look for answer written by HennySmafter.
Thanks to:
Cube32, SITDGNymall, Your Common Sense. Thanks all of you for helping me find the solution.
It took me a while but i found the answer.
megaoverzicht.php
echo "<td><a href='offertemaken.php?id=" . $row['id'] . "'>Offerte Maken </a></td>";
offertemaken.php
// Check whether the value for id is transmitted
if (isset($_GET['id'])) {
// Put the value in a separate variable
$id = $_GET['id'];
// Query the database for the details of the chosen id
$result = mysqli_query($con,"SELECT * FROM cypg8_overzicht WHERE id = $id");
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = "Invalid query: " . mysqli_error($result) . "\n";
$message .= "Whole query: " . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(),etc.
while ($row = mysqli_fetch_assoc($result)) {
echo $row['formuliernummer'] . "\n";
echo $row['domeinnaam'] . "\n";
echo $row['bedrijfsnaam'] . "\n";
echo $row['datum'] . "\n";
echo $row['periode'] . "\n";
}
} else {
die("No valid id specified!");
}
It is not showing the values in the input boxes because there are no input boxes into the echo but those can be easily added I imagine.
In reference to the edit 1:
You are referencing the variables by association, but are outputing the mysql as a default array. instead of
$data2 = mysqli_fetch_array($query);
Try this:
$data2 = mysqli_fetch_assoc($query);
Or:
$data2 = mysqli_fetch_array($query, MYSQLI_ASSOC);
Also, do you have error reporting turned on? If so, then if the array contains no data you should be getting warnings of some kind. If not, a good test is:
error_reporting(E_ALL);
This will warn you about any places where a variable is unset or a array is empty. Another good test is to simply echo out your query, which will tell you if there's any errors in the query itself(which can save some time). If you're not going to go the Prepared Statements route(which is highly encouraged), you can simply echo out $data into your script.

Mysql DELETE query strange behaviour

I have populated an html form with MySQL data from a table.
I have included in that table a form, which if submitted, should delete that row of data from the MySQL table.
This is the code that creates populates the table with the MySQL data from my table.(missed out db connection code and other code I have deemed irrelevant).
while($row_data=mysql_fetch_array($table_data)){
echo "<tr>";
echo "<td>" . $row_data['ID'] . "</td>";
echo "<td>" . $row_data['Site'] . "</td>";
echo "<td>" . $row_data['Date'] . "</td>";
echo "<td>" . $row_data['Target_Site'] . "</td>";
echo "<td>" . $row_data['Target_Contact_Email'] . "</td>";
echo "<td>" . $row_data['Target_Contact_Name'] . "</td>";
echo "<td>" . $row_data['Link_Type'] . "</td>";
echo "<td>" . $row_data['Link_Acquired'] . "</td>";
echo "<td>" . $row_data['Notes'] . "</td>";
echo "<td>" . $row_data['Link_URL'] . "</td>";
echo "<td></td>";
echo "<td><form action='delete.php' method='post'><input type='hidden' name='delete_id' value=" . $row_data['ID'] . "><input type='submit' value='✓' name='delete' style='background:none;' /></form></td>";
echo "</tr>";
}
As you can see in that code, there is a table data on the end, which is a form, and if clicked it is meant to delete that given row. As you can see from the form, the action is delete.php.
This is the code for delete.php (missed out db connection code)
$ID = $_POST['delete_id'];
$Delete = $_POST['delete'];
if(isset($Delete)){
mysql_query("DELETE FROM link_building WHERE 'ID'=" . $ID);
header("location:link_building.php?success2=1");
}else{
header("location:link_building.php?fail2=1");
}
Now, it sort of works, but only deletes rows of data that have an ID of 0. Whenever I try to delete a row of data with an ID of 2 for example, it says it succesfully deleted the data, but doesnt actually delete it. But when I click delete on a row with an id of 0 it deletes all the data instead of just that row.
Your issue is that you have quoted 'ID' with single quotes. An integer 0 compared to an any string equates to TRUE in MySQL, and the quoted 'ID' is a string literal rather than a column name, hence your deletion occurs when you pass in the ID=0, but fails in every other circumstance.
Remove the quotes from ID:
mysql_query("DELETE FROM link_building WHERE ID=" . $ID);
//------------------------------------------^^^^
Also, your code is vulnerable to SQL injection. Be sure to properly filter the value of $ID.
if (isset($_POST['delete_id']) && !ctype_digit($_POST['delete_id'])) {
// Non-integer value! error! bail out!
}
else {
$ID = $_POST['delete_id'];
// Do your query...
}
Note that the above code differs from your original in that it checks for the presence of $_POST['delete_id'] and its validity before proceeding with the rest of the operation. In your original, you set the values of $ID and $Delete without checking if they exist. It isn't really necessary to check for $Delete since you only have the one other form input.
A final note: We don't see any authentication code in this post, but be sure that if you are accepting SQL deletions from a form input that you check any permissions on the row being deleted before you delete it. Otherwise, any user could modify the form to delete any other user's rows (if this applies to your situation).

Categories