How do I delete row when prompted?

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

LVL 4
happysunnyAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

re-searcherCommented:
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
re-searcherCommented:
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
happysunnyAuthor Commented:
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
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Ray PaseurCommented:
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
re-searcherCommented:
you want delete a row in database, right?
0
re-searcherCommented:
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
happysunnyAuthor Commented:
re-searcher...what does the 'id: "21"' stand for?
0
happysunnyAuthor Commented:
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
Ray PaseurCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
happysunnyAuthor Commented:
I've never used jQuery before, so this will be a wonderful learning experience :)  Thanks, Ray!

re-searcher, will you help with this?
0
happysunnyAuthor Commented:
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
re-searcherCommented:
@happysunny
you should change you primary key field name with "id".

please, let me know if you need any more helps.
0
happysunnyAuthor Commented:
@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
re-searcherCommented:
# happysunny
Would you mind tell me what's the table's primary key name?
0
happysunnyAuthor Commented:
It is toyid.  Is this something that should be added and pulled out of the database along with the other information?
0
re-searcherCommented:
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
happysunnyAuthor Commented:
Oh wow!  You are a genius!  It works :)  Sorry about the points, I would have given you much more!
0
re-searcherCommented:
# happysunny
No problem.

Enjoy ;)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.