?
Solved

How do I delete row when prompted?

Posted on 2011-10-28
18
Medium Priority
?
358 Views
Last Modified: 2012-05-12
Hello all,

I am trying to use PHP to pull information from a mySQL database, as well as offer an "Add More" button through the use of JavaScript.  I'm able to put the new information into the database and I am able to pull the information out of the database to show.    However, I am unable to figure out how to delete the information that's pulled from the database when I hit the delete button beside it (Line 137 below).  Any thoughts or ideas?

Thank you in advance!
Paula


<?php
include ("dbinfo.php");
?>
<HTML>
<head>
<title>Add test</title>
<php
$rnumber="0";
?>
<script language="javascript">
rnumber=0;
function addRow(tbl,row){

<?php
//row count
$rnumber++;
 
if ($rnumber<20){
 ?>
 
var textbox = '<center><input type="file" size="10" name=upload[]></center>';

var textbox2 ='<center><select name=toy[]><option 

value="select">Select</option><option value="doll">Doll</option><option 

value="truck">Truck</option><option value="train">Train</option><option 

value="ball">Ball</option></select></center>';

var textbox3 = '<center><select name=color[]><option 

value="select">Select</option><option value="blue">Blue</option><option 

value="red">Red</option><option value="yellow">Yellow</option><option 

value="Green">Green</option></select></center>';

var textbox4 = '<center><input type="text" size = "5" maxlength= "10" name=weight[]

></center>';
var textbox5 = '<center><input type="text" size = "5" maxlength= "10" name=price[]

></center>';
var textbox6 = '<center><input type="checkbox" name=accept[]></center>';

var stop = '<input type="button" value="delete" onclick="deleteRow(this)" >';
 
var tbl = document.getElementById(tbl);
var rowIndex = document.getElementById(row).value;
var newRow = tbl.insertRow(rnumber);
var newCell = newRow.insertCell(0);
newCell.innerHTML = textbox;
var newCell = newRow.insertCell(1);
newCell.innerHTML = textbox2;
var newCell = newRow.insertCell(2);
newCell.innerHTML = textbox3;
var newCell = newRow.insertCell(3);
newCell.innerHTML = textbox4;
var newCell = newRow.insertCell(4);
newCell.innerHTML = textbox5;
var newCell = newRow.insertCell(5);
newCell.innerHTML = textbox6;
var newCell = newRow.insertCell(6);
newCell.innerHTML = stop;
 <?php
}
?>
 
}
    function deleteRow(r)
    {
    var i=r.parentNode.parentNode.rowIndex;
    document.getElementById('TableMain').deleteRow(i);
     
<?php
    $rnumber--;
?>
    }
 
</script>
</head>
<body>

<table width="75%" >
<tr>
<td width = 100%>

<form name="toyentry" method="post"> 
<table width="100%" border="0" cellspacing="0" cellpadding="2" id="TableMain">
<th>Upload Picture</th>
<th><center>Toy</th>
<th>Color</th>
<th>Weight</th>
<th>Price</th>
<th>Accept</th>

$id=$_SESSION['id'];
$id=htmlspecialchars($id);
$id_sq=mysql_real_escape_string($id);

<?php
$sql="SELECT * FROM table WHERE id='$id_sq'";
$result = mysql_query($sql);

while ($row = mysql_fetch_assoc($result))
{
$toydb=$row["toy"];
$colordb=$row["color"];
$weightdb=$row["Weight"];
$picdb=$row["ImagePath"];
$pricedb=$row["Price"];

echo "<tr><td>";
echo "<center><img src=\"$picdb_sq\" height=\"75\" width=\"100\"></center>";
echo "</td><td>";
echo "<center>";
echo $toydb_sq;
echo "</center>";
echo "</td><td>";
echo "<center>";
echo $colordb_sq;
echo "</center>";
echo "</td><td>";
echo "<center>";
echo $weightdb_sq;
echo "</center>";
echo "</td><td>";
echo "<center>$";
echo $pricedb_sq;
echo "</center>";
echo "</td><td>";
echo "<center><input type=\"checkbox\"></center>";
echo "</td><td>";
echo "<center><input type=\"checkbox\"></center>";
echo "</td><td>";
echo "<input type=\"button\" value=\"Delete\" onclick=\"deleteRow(this)\" >";
echo "</td></tr>";
}
?>

<tr id="row1">
</tr>
</table>
</td>
<td valign="top" width = 20%>
<input type="button" name="Button" value="Add more" onClick="addRow

('TableMain','row1')"></td>
</tr>
</table>
<table>
<tbody>
<tr><td>
<input type="submit" class="button" name="submit" value="Submit">
</td></tr>
</tbody>
</table>
</form>
</body>
</html>

Open in new window

0
Comment
Question by:happysunny
  • 8
  • 8
  • 2
18 Comments
 
LVL 3

Expert Comment

by:re-searcher
ID: 37046904
It's work as well on firefox, but if you test it on IE (Internet Explorer) you should change line 74 to following code:
document.all.getElementById('myTable').deleteRow(i);

Open in new window

0
 
LVL 3

Expert Comment

by:re-searcher
ID: 37046926
if you want to remove this row from database,too.
you should post delete command to another php page (or current page with specified variables) with ajax.
0
 
LVL 4

Author Comment

by:happysunny
ID: 37046960
Thank you for the IE tip!

Yes, I am trying to use the delete command, but I'm unsure how to do it correctly in this case.  This is the code I have for when they press submit.

<?php

if(isset($_POST['submit']))
{

include ("dbinfo.php");

$weight = $_POST["weight"];

$cnt=count($weight);

for ($counter=0; $counter < $cnt; $counter++)
{
$weight = $_POST["weight"][$counter];
$file = $_POST["upload"][$counter];
$price = $_POST["price"][$counter];
$toy = $_POST["toy"][$counter];
$color = $_POST["color"][$counter];

mysql_query("INSERT INTO table (Weight, File, Price, Toy, Color) VALUES('$weight', '$file', '$price', '$toy', '$color')") or die(mysql_error());  
}

}
?>

Open in new window

0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 111

Expert Comment

by:Ray Paseur
ID: 37047070
Generally a delete-from-database concept would work something like this.  You need to be sure that you do not do a delete (or any other change to the data model) on the basis of the URL parameters alone.  HTH, ~Ray
<?php // RAY_delete_example.php
error_reporting(E_ALL);


// DEMONSTRATE HOW TO HAVE A SAFE DELETE SCRIPT
// IF THE GET AND POST KEYS MATCH, IT IS OK TO DELETE


// CONNECTION AND SELECTION VARIABLES FOR THE DATABASE
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "??";        // GET THESE FROM YOUR HOSTING COMPANY
$db_user = "??";
$db_word = "??";

// OPEN A CONNECTION TO THE DATA BASE SERVER
// MAN PAGE: http://php.net/manual/en/function.mysql-connect.php
if (!$db_connection = mysql_connect("$db_host", "$db_user", "$db_word"))
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB CONNECTION: ";
    echo "<br/> $errmsg <br/>";
}

// SELECT THE MYSQL DATA BASE
// MAN PAGE: http://php.net/manual/en/function.mysql-select-db.php
if (!$db_sel = mysql_select_db($db_name, $db_connection))
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB SELECTION: ";
    echo "<br/> $errmsg <br/>";
    die('NO DATA BASE');
}
// IF WE GOT THIS FAR WE CAN DO QUERIES



// GET THE KEYS FROM GET AND POST ARRAYS
$pk = (!empty($_POST["key"])) ? (int)$_POST["key"] : 0;
$gk = (!empty($_GET["key"]))  ? (int)$_GET["key"]  : 0;

// IF BOTH KEYS ARE PRESENT, DELETE THE ROW (NOTE THERE ARE NO ROWS WITH KEY=0)
if ($pk == $gk)
{
    $sql = "DELETE FROM mytable WHERE mykey = $pk LIMIT 1";
    $res = mysql_query($sql) or die( mysl_error() );
    die("KEY $pk HAS BEEN DELETED");
}



// IF ONLY THE GET KEY IS PRESENT, PUT UP A MESSAGE AND A FORM
if ( (empty($pk)) && ($gk) )
{
	$sql = "SELECT myname FROM mytable WHERE mykey = $gk LIMIT 1";
	$res = mysql_query($sql) or die( mysql_error() );
	$num = mysql_num_rows($res);
	if ($num)
	{
	    // THE ROW EXISTS, GENERATE THE FORM FOR POST-METHOD SIGNAL TO DELETE
	    $row = mysql_fetch_assoc($res);
	    $nom = $row["myname"];
	    $uri = $_SERVER["REQUEST_URI"];

	    // CREATE THE FORM USING HEREDOC SYNTAX
	    $form = <<<ENDFORM

<form method="post" action="$uri">
CONFIRM REQUEST TO DELETE THE ROW WITH MYNAME=$nom
<input type="hidden" name="key" value="$gk" />
<input type="submit" value="DELETE RECORD NUMBER $gk" />
</form>
ENDFORM;

        echo $form;
        die();
    }

    // NO RECORD WAS FOUND
    else
    {
        die("NO RECORD FOUND FOR KEY=$gk");
    }
}

Open in new window

0
 
LVL 3

Expert Comment

by:re-searcher
ID: 37047073
you want delete a row in database, right?
0
 
LVL 3

Assisted Solution

by:re-searcher
re-searcher earned 800 total points
ID: 37047174
If you want delete row in database with deleting it on html table following code is best solution for you.

1

create new php file or add following code on each page which you like (we will call it in future time..)
i.e: smth.php
// ID IS CONTAIN PRIMARY KEY FIELD IN MYSQL TABLE
if( isset($_POST['id']) ){
    // RUN MYSQL COMMAND TO DELETE SPECIFIED ROW
  if( mysql_query('SELECT * FROM [table name] WHERE [field name] = "'.$_POST['id'].'" ') ){
         echo 'yes';
  }else{
         echo 'no';
  }
  die();
}

Open in new window


2

create js function and add add it with your previous code (deleteRow)
$.post("smth.php", { id: "21" },
   function(data) {
     alert("Row, Deleting Status: " + data);
   });

Open in new window


3

add jQuery .js file before </header> tag
Note: you can try this with another ways. but best solution for you is using ajax or jquery and XMLHTTPRequest() function, because it will not redirect you/visitor to another page.

-
Enjoy with Coding ;)
0
 
LVL 4

Author Comment

by:happysunny
ID: 37047241
re-searcher...what does the 'id: "21"' stand for?
0
 
LVL 4

Author Comment

by:happysunny
ID: 37047280
Ray_Paseur...I see that the value of the submit button isn't onClick.  I'd like for it to both take it away with JavaScript, and delete it out of the database with PHP.  I know it's possible, but I'm still not seeing how it will all work.
0
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 1200 total points
ID: 37047531
Hi, Paula.  I found this question because I watch the PHP zone from time to time, so naturally my thinking about these things is made in PHP terms.  On this, I think you might want to consider a jQuery solution.  I am not any kind of expert on the client-side matters, but I am fairly sure that jQuery has something like this baked in.  Best of luck with it, ~Ray
0
 
LVL 4

Author Comment

by:happysunny
ID: 37047574
I've never used jQuery before, so this will be a wonderful learning experience :)  Thanks, Ray!

re-searcher, will you help with this?
0
 
LVL 4

Author Closing Comment

by:happysunny
ID: 37048322
I will look into both ajax and jQuery for this.  Either that, or try to use something like http://www.phpmyedit.org/   Thank you both very much :)
0
 
LVL 3

Expert Comment

by:re-searcher
ID: 37048975
@happysunny
you should change you primary key field name with "id".

please, let me know if you need any more helps.
0
 
LVL 4

Author Comment

by:happysunny
ID: 37050839
@re-searcher...sorry, I thought you gave up on me!  Yes, I don't understand where the 21 came from in the js function.
0
 
LVL 3

Expert Comment

by:re-searcher
ID: 37050847
# happysunny
Would you mind tell me what's the table's primary key name?
0
 
LVL 4

Author Comment

by:happysunny
ID: 37050860
It is toyid.  Is this something that should be added and pulled out of the database along with the other information?
0
 
LVL 3

Expert Comment

by:re-searcher
ID: 37050873
so you should change to following code:
$.post("smth.php", { toyid: "21" },
   function(data) {
     alert("Row, Deleting Status: " + data);
   });

Open in new window


replace toyid value with 21. so each time you post it will send correct toyid for deletion.
for example:
$.post("smth.php", { toyid: "<?php echo $row['toyid']; ?>" },
   function(data) {
     alert("Row, Deleting Status: " + data);
   });

Open in new window

0
 
LVL 4

Author Comment

by:happysunny
ID: 37051110
Oh wow!  You are a genius!  It works :)  Sorry about the points, I would have given you much more!
0
 
LVL 3

Expert Comment

by:re-searcher
ID: 37051120
# happysunny
No problem.

Enjoy ;)
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When the s#!t hits the fan, you don’t have time to look up who’s on call, draft emails, call collaborators, or send text messages. An instant chat window is definitely the way to go, especially one like HipChat. HipChat is a true business app. An…
Strategic internal linking is often considered an SEO power technique, especially for content marketing. Do you need to hire an SEO agency to optimize you internal linking? No, this article will help you understand the basics of internal linking and…
This tutorial walks through the best practices in adding a local business to Google Maps including how to properly search for duplicates, marker placement, and inputing business details. Login to your Google Account, then search for "Google Mapmaker…
Any person in technology especially those working for big companies should at least know about the basics of web accessibility. Believe it or not there are even laws in place that require businesses to provide such means for the disabled and aging p…
Suggested Courses
Course of the Month16 days, 10 hours left to enroll

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question