Saghir A. Khatri
Saghir A. Khatri

Reputation: 3128

Get HTML Table Data in php Array

I am new to PHP. So i first apologize if i am using dumb strategy. I am working on PHP site. my page queries data from MySql and shows in html table along with me checkboxes. User can Delete any data using check boxes and button. this all is done using javascript. Here is my code to delete data from html table

<script type="text/javascript">
function deleteRow() {
        try {
            var table = document.getElementById("Categories");
        var rowCount = table.rows.length;



        for(var i=0; i<rowCount; i++) {
            var row = table.rows[i];
            var chkbox = row.cells[0].childNodes[0];
            if(null != chkbox && true == chkbox.checked) {
                table.deleteRow(i);
                rowCount--;
                i--;
            }


        }
        }catch(e) {
            alert(e);
        }
    }

</script>

on clicking Save button MySql update query should run to save all changes made to page. I know this can be done by PHP. but problem here is how i can get data from html in php to run the query?? if any one can point me to right direction, i will be thankful to you.

Thanks.

Upvotes: 1

Views: 1087

Answers (1)

Leri
Leri

Reputation: 12535

You can make a form where you'll have checkboxes like: <input type="checkbox" name="m_Name[]" value="id_of_element">. When you submit this form on server-side you can do:

foreach ($_POST['m_Name'] as $id){
    $query = 'DELETE FROM table WHERE id='.$id;
    //execute query with mysqli_*, PDO or mysql_*; NOTE: if you are not doing educational project don't use last one.
}

But better approach will be:

$query = 'DELETE FROM table WHERE id IN (';
$in = '';

foreach ($_POST['m_Name'] as $id)
    $in .= $id.',';

$in = substr($in, 0, strlen($in)-1).')'; // removes extra "," at the end.
$query .= $in;
//run the query.

The last one wil execute only one query to delete notes so it's better for performance. But the way I've created query seems ugly to me but I am very tired to thing about improvements. :)

Upvotes: 2

Related Questions