How can I delete the echo of an HTML table? - php

I have the following code for the echo of an HTML table. In the table is a delete button. I want to delete the user's input from the database when the user hits the delete button. In the database there are more rows from the same user with different values and these are also shown with this code. How do I delete the specific input from one output (the one where the user hits delete)? I've been at it all day and tried a lot of things but can't find a way to do it. I'm just a beginner..
$sql = "SELECT publicaties.pub_Id,publicaties.userid,publicaties.titel,publicaties.type,publicaties.linkwerk,publicaties.linkuitgever,publicaties.beschikbaar,publicaties.hierbewerkt, users.username,users.userid FROM publicaties, users WHERE publicaties.userid=users.userid AND publicaties.userid='$user' ORDER BY pub_Id DESC LIMIT $offset, $rec_limit";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
if ($row["hierbwerkt"] ==1)
echo $row["hierbewerkt"];
else
{
echo" ";
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "
<table width='415' border='0' class='tablepublicaties'>
<tr>
<td rowspan='2' bgcolor='#1E1E1E'> </td>
<td rowspan='2' bgcolor='#1E1E1E'><span class='user-imagelarge'><img src='Images/nopicture.png' alt='nopicture' width='273' height='381' class='user-imagelarge'></span></td>
<td valign='middle' nowrap bgcolor='#1E1E1E'><span class='linkkleur'>".$row["hierbewerkt"]."</td>
<td valign='middle' bgcolor='#1E1E1E'>".$row["username"]."</td>
</tr>
<tr>
<td valign='bottom' bgcolor='#1E1E1E'>Titel</td>
<td valign='middle' bgcolor='#1E1E1E'><span class='sterrenkleur'>".$row["titel"]."</span></td>
</tr>
<tr>
<td bgcolor='#1E1E1E'> </td>
<td nowrap bgcolor='#1e1e1e'> </td>
<td bgcolor='#1E1E1E'>Type</td>
<td bgcolor='#1E1E1E'>".$row["type"]."</td>
</tr>
<tr>
<td bgcolor='#1E1E1E'> </td>
<td bgcolor='#1E1E1E'> </td>
<td bgcolor='#1E1E1E'>Publicatie</td>
<td bgcolor='#1E1E1E'><a href='$row[linkwerk]'> ".$row["linkwerk"]."</a></td>
</tr>
<tr>
<td bgcolor='#1E1E1E'> </td>
<td bgcolor='#1E1E1E'> </td>
<td bgcolor='#1E1E1E'>Uitgever</td>
<td bgcolor='#1E1E1E'><a href='$row[linkuitgever]'> ".$row["linkuitgever"]."</a></td>
</tr>
<tr>
<td bgcolor='#1E1E1E'> </td>
<td nowrap bgcolor='#1E1E1E'> </td>
<td bgcolor='#1E1E1E'>Beschikbaar</td>
<td bgcolor='#1E1E1E'>".$row["beschikbaar"]."</td>
</tr>
<tr>
<td bgcolor='#1E1E1E'> </td>
<td bgcolor='#1E1E1E'><input type='image' class='backgroundgreyfotoos' src='Images/Icons/crossorangebutton.png' alt='Submit Form' width='15' height='15' border='0'/ ></td>
<td bgcolor='#1E1E1E'><img src='Images/lijntransparant.png' width='70' height='1' alt='lijn'></td>
<td bgcolor='#1E1E1E'><img src='Images/lijntransparant.png' width='224' height='1' alt='lijn'></td>
</tr>
</table>
<br>";
}
}
mysql_close($conn);

Your PHP-Script has to handle this deletion. For example you can define a GET-Parameter called action which defines what should be done:
$action = ( isset( $_GET['do'] ? $_GET['do'] : 'index' );
if( $action == 'index') {
// Print your Table
}elseif( $action == 'delete' ) {
// Send a SQL-Query to the database-server like 'DELETE FROM TABLE WHERE
// DELETE FROM publicaties WHERE publicaties.pub_Id = $pub_id [...]
}
For the deletion, you can link to yourscript.php?do=delete&pubId=123 so that the entry you've passed by pubId (accessable by $_GET['pubId']) gets deleted. The advanced version would be using ajax. Its more user-friendly and you can safe ressources because it's not necessary to reload the entire page. You keep on the table-page, make a ajax-request to yourscript.php?do=delete&pubId=123 in the background. When it was successfull, you can delete the table-row by manipulating the DOM. A library like jQuery would make those thinks much easier.
But as beginner it will be a good idea to skip the ajax-part initially and do it like the simple way I explained first. This is easier and you don't need any Javascript which is necessary for ajax.
As a second tip you should get information about SQL-Injections. Building dynamic SQL-Querys like
$query = 'DELETE FROM table WHERE id = ' . $_GET['id'];
is very insecure because every visitor can manipulate the Query by passing valid SQL as the parameter. HTTP-POST is not even better, it's only a bit more difficult because POST-Data is send in the HTTP-Body. You should at least filter input from outside by escaping it. Numeric values can also be casted like (int)$_GET['id']. But the best way is to use prepared statements because by manual escaping you may forget to escape correctly which can result in a security risk. By using prepared statements, you're not inserting variable data like from GET or POST directly in the query-string. Instead you're using placeholders, which gets replaced later. The replacing with these values is done by php automatically, so that you can't forget the escaping.

<?php
// is the page requested in the post method?
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
// if we have received an x coordinate from the delete-button then it is pressed.
if(isset($_POST['delete_x']))
{
// make your delete query here
echo 'Now its time to delete record with id=' . $_POST['id'];
// if everything is working i recommand that you reload the page in the normal GET method.
// Then you need to uncomment the two following lines
//header('Location: ' . $_SERVER['SCRIPT_NAME']);
//exit;
}
// dump the $_POST array. Just for learning or debugging
echo '<pre>';
print_r($_POST);
echo '</pre>';
}
// dummy variabele, comes normal from your database
$row['id'] = 12;
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
<input type="image" src="cross.png" name="delete">
</form>
The entire HTML form (last 4 lines) needs to be rendered for each row in the table!

Related

Can we make results of MySQL select query editable and sortable?

I have a select query which pulls up data from a table and displays it accordingly
$display_query= "select * from customer WHERE abc_mailing_list = '$abc' AND def_mailing_list ='$def' AND ghi_mailing_list = '$ghi' AND position_category IN($var) AND country_code='$country_cat' ORDER BY state";
$display_result=mysqli_query($dbc2,$display_query);
<table width = "100%"border="1" style="border-collapse: collapse;">
<tr style="background-color: #51626F; color: #FFFFFF;">
<th> S.No</th>
<th> First Name</th>
<th>Last Name</th>
<th>Position Category</th>
<th>State</th>
<th>Country</th>
<th>Title</th>
<th>Agency</th>
<th>Department</th>
</tr>
<?php
$colour2 = "transparent";
$colour1 = "#B1B0A7";
$count = 0;
$row_count = 0;
while($row=mysqli_fetch_assoc($display_result)){
$rowcolor = ($row_count % 2) ? $colour1 : $colour2;
$count++;
?>
<tr style="background: <? echo $rowcolor; ?>;">
<td width="10%" height="20"><? echo $count; ?></td>
<td width="10%" height="20"><? echo $row['first_name']; ?></td>
<td width="10%" height="20"><? echo $row['last_name']; ?></td>
<td width="10%" height="20"><? echo $row['position_category']; ?></td>
<td width="10%" height="20"><? echo $row['state']; ?></td>
<td width="10%" height="20"><? echo $row['country_code']; ?></td>
<td width="10%" height="20"><? echo $row['title']; ?></td>
<td width="10%" height="20"><? echo $row['agency']; ?></td>
<td width="10%" height="20"><? echo $row['department']; ?></td>
</tr>
<?
$row_count++;
}
?>
My question is I want to make everything editable so that if the user finds some mistake in the returned results, he should have the option to edit then and there and save it, so that it can be saved in the database. Is there any plugin for this? I'm sorry if this is a trivial question, I'm new to PHP. Thanks
The edit part would take some work, but you could use DataTables (a JQuery plugin) to handle the sorting, searching etc..
DataTables (table plug-in for jQuery)
www.datatables.net
You are missing some understanding about how this works. What you do now is show the data in a web page. You need to implement a mechanism to update the database back, this is not going to happen instantly, you need to show the data in an editable format like a textbox and than let the user change it and click an update button for example when he is done. then you need to respond to a click on that button, take the edited data from the textbox and update the right location in the database. that is simply put and can be done in many different ways. start doing something and post some code so we could help :)
instead of
'<td width="10%" height="20"><? echo $count; ?></td>'
you should have this column be a unique auto-incrementing number from the database, so each row can be identified. from there, you can use forms(either checkboxes to select which colums need to be edited, or text inputs that can be edited on each column). if you choose to use checkboxes and a 'edit' button, have a hidden input with the unique id attached. Then check if
(isset($_POST['id']) && isset($_POST['firstName']))
{
$firstName = sanitizeStrin($_POST['firstName']);
$id = sanitizeString($_POST['id']);
mysql_query( "UPDATE table SET first_name = '$firstName' WHERE uniqueID='$id'" );
}
.. ect to see which column in which row needs to be updated. A lot of code is needed to check every column, but you get the idea. Hope this helps.

Delete record from table using Checkbox [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Deleing Multiple Rows Using Checkboxes, PHP and MySQL
I wonder whether someone may be able to help me please.
I'm trying to put together a script which creates a form which gives the user the ability to delete a record via the selection of a checkbox and then pressing a 'submit' button.
From reading through many articles, I've put together the following script which is the section of code that builds the table, checkboxes and submit button.
<?php
$query = "SELECT l.*, COUNT(f.locationid) totalfinds FROM detectinglocations l LEFT JOIN finds f ON f.locationid = l.locationid WHERE l.userid = '$idnum' GROUP BY l.locationname";
$result=mysql_query($query);
$count=mysql_num_rows($result);
?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td><form name="del" id="del" action="deletelocation.php" method="post">
<table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td bgcolor="#FFFFFF"> </td>
<td colspan="4" bgcolor="#FFFFFF"><strong>Delete multiple rows in mysql</strong> </td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">#</td>
<td align="center" bgcolor="#FFFFFF"><strong>Id</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Name</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Lastname</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Email</strong></td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td align="center" bgcolor="#FFFFFF"><input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $rows['locationid']; ?>"></td>
<td bgcolor="#FFFFFF"><? echo $rows['locationid']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['locationname']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['returnedaddress']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['totalfinds']; ?></td>
</tr>
<?php
}
?>
<tr>
<td colspan="5" align="center" bgcolor="#FFFFFF"><input type="submit" value="Delete" /></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
The code below, then deals with the deletion of the record.
<?php
$del_id = $_POST['checkbox'];
for($i=0;$i<$count;$i++){
$del_id = $checkbox[$i];
$sql = "DELETE FROM $detectinglocations WHERE locationid='$del_id'";
$result = mysql_query($sql);
}
?>
The correct information is retrieved and shown in the form table, but the problem I'm having is that I'm unable to get the deletion of the record to work. I've run this through JavaScript Console, but unfortunately I don't receive an error message which may help me to solve the problem.
I just wondered whether someone could possibly take a look at this please and let me know where I'm going wrong.
Change your PHP code as below
$del_id = $_POST['checkbox'];
$detectinglocations = 'your database table name';
foreach($del_id as $value){
$sql = "DELETE FROM ".$detectinglocations." WHERE id='".$value."'";
$result = mysql_query($sql);
}

PHP mySQL - How do i print only different attributes of two things that share a common name?

I'm trying to print out a list of products on a page. This is cake so far..
However Some of my items share names but have different attributes.
Example would be like...:
product:
keyboard
keyboard
size:
25 inches
23 inches
color:
red
blue
My table looks something like this:
id, product, size, color, so on...
So my .php I'm doing my query and print from looks something like this
<div id="accordion">
<?php
$letter = $_GET['letter'];
//echo "$id";
include("database.php");
$result = mysql_query("SELECT UPPER(product) AS upperName, PRODUCTS.* FROM PRODUCTS WHERE product LIKE '$letter%' ORDER BY UPPER(product) ");
$prodName = "";
while($row = mysql_fetch_array($result))
{
if ($row['upperName'] != $prodName)
{
print('<div style="background-color:#666; padding-bottom:25px; margin-bottom:25px;">');
print ("<h1>" . "$row[product]" . "</h1>");
}
print ("$row[ndc]" . "<br />");
print ("$row[size]" . "<br />");
print ("$row[strength]" . "<br />");
print ("$row[imprint]" . "<br />");
print ("$row[form]" . "<br />");
print ("$row[color]" . "<br />");
print('</div>');
$prodName = $row['upperName'];
}
mysql_close($linkID);
?>
</div>
My problem comes from trying to style the attributes..
Do you see that /div tag?
I want to style that stuff within an accordion however that stuff repeats for each product that shares the same name in that accordion. So if i include the div there, it prints out for 3 times with the same name 3 end div tags (hence breaking all my html nooo!!)
Is there a way to maybe loop? or use some kind of conditional logic to print that top stuff, once for the product name that all the products share, then the loop and print all the different attributes, then when each attribute is finished, to then include my closing html?
So if i have 6 products and half are named "keyboard", and the other half are named "shoes"
could i get it to print out
TABLE
product name: KEYBOARD
table for all my attributes
end table for all my attributes
end TABLE
TABLE
product name: SHOES
table for all my attributes
end table for all my attributes
end TABLE
That way i can style all my attributes.
I'm really sorry if this isn't correctly explained I'm still learning.
Any help is appreciated!
Extra stuff that you may not need to figure out my problem just an example of a table i'm printing to and why the way the attributes print is a problem. the 1-2-3-4-5-6-7-8-9 are data for the attributes.
<table cellspacing="0" cellpadding="0" border="0" width="649">
<tr>
<td width="180" height="10" valign="top"></td><td width="36" height="10" valign="top"></td><td width="433" height="10" valign="top"></td>
</tr>
<tr>
<td width="180" valign="top"><img src="images/slide1.gif" width="180" height="200" border="0" /></td>
<td width="36" valign="top"></td>
<td width="433" valign="top"><table cellspacing="0" cellpadding="0" border="0" width="433">
<tr>
<td valign="top"><span class="in-table-head">Name:</span></td>
<td valign="top"><span class="in-table-name">$row[name]</span></td>
</tr>
<tr>
<td valign="top"><span class="in-table-head">Therapeutic Category:</span></td>
<td valign="top"><span class="in-table-name">$row[therapeutic]</span></td>
</tr>
<tr>
<td colspan="2" valign="top"><span class="in-table-providers">Information for Providers</span></td>
</tr>
</table></td>
</tr></table>
<table cellspacing="0" cellpadding="0" border="0" width="649">
<tr>
<td><span class="in-table-att">NDC#:</span></td>
<td><span class="in-table-att">Strength:</span></td>
<td><span class="in-table-att">Size:</span></td>
<td><span class="in-table-att">Imprint:</span></td>
<td><span class="in-table-att">Form:</span></td>
<td><span class="in-table-att">Color:</span></td>
<td><span class="in-table-att">Shape:</span></td>
<td><span class="in-table-att">Pack Size:</span></td>
<td><span class="in-table-att">Rating:</span></td>
</tr>
</table>
<table cellspacing="0" cellpadding="0" border="0" width="649">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</table>
Thank you again to anyone who looks at this problem!
stop matching by name but start using sku’s as a selector. that way you’re always spot on, no matter how many keyboards you have.
set up your pages to pass the sku instead of generic name.
otherwise you need to add more criteria to your where statement like dimensions, weight, color, price etc... to get ta reliable result.
-- Update --
An example.
page.php?product_type=keyboard
<?php
// set up database
$db = mysqli_connect("localhost", "user", "pass", "database_name");
// Just using mysql escape string, you should consider adding more securty checking to prevent injection
$producttype = mysql_real_escape_string($_GET['product_type']);
$result = $db->query("SELECT * FROM `products` WHERE `products`.`type`='$producttype'");
$features["width"][]
$features["height"][]
$features["color"][]
$features["whatever"][]
while ($row = $result->fetch_assoc())
{
$features["width"][] = $row["width"];
$features["height"][] = $row["height"];
$features["color"][] = $row["color"];
$features["whatever"][] = $row["whatever"];
}
// printing the features
echo "You have selected $producttype<BR>";
echo "The following widths can be selected<BR><UL>";
foreach($features["width"] as $width)
echo "<LI>$width</lI>";
echo "</UL><P>The following heights can be selected<BR><UL>";
foreach($features["heights"] as $height)
echo "<LI>$height</lI>";
echo "</UL><P>The following colors can be selected<BR><UL>";
foreach($features["colors"] as $color)
echo "<LI>$color</lI>";
echo "</UL><P>The following whatevers can be selected<BR><UL>";
foreach($features["whatevers"] as $whatevers)
echo "<LI>$whatevers</lI>";
echo "</UL>";
echo "have a nice day";
?>

PHP Dynamically returning multidimensional arrays

I have been doing a lot of work in learning how to return multidimensional arrays dynamically- but what I can't seem to figure out is how to nest them.
I have two tables, each has the identical format: ID, name.
Table one: SSC
- sscid
- sscname
Table two: SRV
- srvid
- srvname
What I am trying to do is print all of the items in table two under EACH item in the table one list.
The table one items are the headers, the table two items are returned as a checkbox (with the srvid as the value) and label(srvname).
I can get it to all print together, but it is a. one giant list of results and it's in a
| checkbox | table 1: name | table 2: name | format.
Not pretty at all (although it is progress for me to get this far).
After I run my query and get the result, my code looks like this:
Now, I've had a few additional thoughts about the design of the concept re:the database tables go, but everything I read indicates that they really need to be on their own tables, and they should be able to be referenced by the key from one table and the key from the other (eventually ended up in a joint table with user ID references) Because they are numerically indexed, I don't know why this would be an issue for me; however I simply can't seem to get this to work properly.
I should mention that when I alter the code to try to make the ssc_name span 2 cols and make it more like a header, it returns a header row for each checkbox/srv row, instead of for all of the checkbox/srv rows.
if($result) {
echo '<table border="1" align="center" cellspacing="3" cellpadding="3" width="300">
<tr><th colspan="2"><h3>Options</h3></th></tr>
<tr><td></td><td align="left"><b>Services</b></td></tr>';
$numfields = mysql_num_fields($result);
$data = array();
$flist = array();
for($i=0;$i<$numfields;$i++)$flist[] = mysql_field_name($result,$i);
$data[0] = $flist;
while($row = mysql_fetch_assoc($result)) {
$data[] = $row;
echo '<tr><td colspan="2" align="center"><b>' . $row['ssc_name'] .'</b><td></tr>
<tr><td align="center"><input type="checkbox" value="'. $row['ssv_id'] .'" / </td>
<td align="left">' . $row['ssvname'] . '</td>
</tr>';
}
echo '</table>';
}
Can anyone help me figure this out, please?
You are missing a > on this line
<tr><td align="center"><input type="checkbox" value="'. $row['ssv_id'] .'" / </td>
Should be
<tr><td align="center"><input type="checkbox" value="'. $row['ssv_id'] .'" /></td>
Something you might be able to pick up on with better formatting...
<?php
if ($result) {
echo <<<EOD
<table border="1" align="center" cellspacing="3" cellpadding="3" width="300">
<tr>
<th colspan="2"><h3>Options</h3></th>
</tr>
<tr>
<td></td>
<td align="left"><b>Services</b></td>
</tr>
EOD;
while ($row = mysql_fetch_assoc($result)) {
echo <<<EOD
<tr>
<td colspan="2" align="center"><b>{$row['ssc_name']}</b><td>
</tr>
<tr>
<td align="center"><input type="checkbox" value="{$row['ssv_id']}" /></td>
<td align="left">{$row['ssvname']}</td>
</tr>
EOD;
}
echo '</table>';
}
?>
And I'm not really sure what business any of those arrays have being in there.

SELECTING in two tables...

I have two tables that I want to use for viewing my reports which I can get after inputting a date.
Here are my tables: for customers - customer_date, lastname, firstname
for services - room_number, date_in, date_out
Here is my code now : it seems that it can't get any rows from my table
<?php
$conn = mysql_connect("localhost","root","");
mysql_select_db('irm',$conn);
if(isset($_GET['Submit'])){
$customer_date = $_GET['customer_date'];
}
?>
<form method="get">
<table width="252" border="0">
<tr>
<td width="98">Choose Date:</td>
<td width="144"><label>
<input onclick="ds_sh(this);" name="customer_date" id="customer_date" readonly="readonly" style="cursor: text" />
</label></td>
</tr>
<tr>
<td align="right"><input type="submit" value="Submit" /></a></td>
<td></td>
</tr>
</table>
</form>
<form>
<?php
$tryshow = "SELECT * FROM customers,services WHERE customer_date = '$customer_date' ";
$result = #mysql_query($tryshow,$conn)
or die("cannot view error query");
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print...";
}
while($row=mysql_fetch_assoc($result)){
?>
<table width="700" border="0">
<tr>
<td width="100">Customer Date:</td>
<td width="100">Last Name</td>
<td width="100">First Name</td>
<td width="100">Room Number</td>
<td width="100">Date In</td>
<td width="100">Date Out</td>
</tr>
<tr>
<td><?php echo $row["customer_date"]; ?></td>
<td><?php echo $row['lastname']; ?></td>
<td><?php echo $row['firstname']; ?></td>
<td><?php echo $row['room_number']; ?></td>
<td><?php echo $row['date_in']; ?></td>
<td><?php echo $row['date_out']; ?></td>
</tr>
</table>
<?php }?>
</form>
With this I can get a report of any customer who checks in on that date.
I need some advice. Hope you can answer me soon.
You don't appear to have any fields in common between the two tables. How do you store fact that customer A was in room B on date C? To do an SQL join, the tables being joined have to have at least one field in common.
As well, instead of just saying die("cannot view error query"), which is utterly useless for debugging purposes, try doing die(mysql_error(), which will give you the exact reason the query failed.
As well, if the query DOES work, then you're outputting an entire HTML table for each row found. You should have the table headers and footers data OUTSIDE of the fetch loop.
You need to relate the two tables with a JOIN. Based on the information given, customers.customer_date to services.date_in seems to be the most likely candidate. This assumes that the date columns hold only a date and not a date/time.
Also notice that I'm not using select * in my query and neither should you. ;-)
SELECT c.customer_date, c.lastname, c.firstname,
s.room_number, s.date_in, s.date_out
FROM customers c
INNER JOIN services s
ON c.customer_date = s.date_in
WHERE c.customer_date = '$customer_date'
When your making query to database make sure your date format is yyyy-mm-dd
Mysql understand date in this format only so that you have to compare the date format in this format only.
your $customer_date should be in the yyyy-mm-dd format
As an aside, I'd change customer_date to something more meaningful such as "date_in." (It's a good thing when the names are predictable!) You don't need to specify that it's the customer since it's in the customer table already.

Categories