Grow your CSS skills. Land your dream job.

Deleting multiple rows in MySQL database using ajax and php

  • # March 9, 2013 at 12:08 pm

    Hello there, I am working on a small CRM for a Racing Team. I am creating a page where they can write a post and delete the posts at their liking. I am using ajax to do all the data transmission in the background to prevent page refresh. The whole posting is done, working and easy. But I can’t get my head around deleting a single or multiple posts.

    Here is the context:

    When the client sings in the admin.php page, I am generating a

    which contain a
    per post title.



    < ?php
    $query = “SELECT * FROM news ORDER BY post_date DESC”;
    $test = mysqli_query( $dbc, $query )
    or die (‘Could not query the information to News table.’);

    while ( $row = mysqli_fetch_array($test) ) {
    $id = $row;
    $postDate = $row;
    $postMonth = date(M, strtotime($postDate));
    $postDay = date(j, strtotime($postDate));
    $title = $row;

    echo ‘

    ‘;
    echo ‘‘;
    echo ‘‘;
    echo ‘‘;
    echo ‘

    ‘;
    echo ‘

    ‘;
    }
    mysqli_close( $dbc );
    ?>

    At the top of the code you can see I have a delete post button to trigger the ajax code to delete the single or multiple posts. How would I go about using JQuery AJAX to do a simple PHP:

    foreach ( $_POST as $postID )
    {
    $query = “DELETE FROM news WHERE id = $postID”;
    mysqli_query( $dbc, $query )
    or die ( ‘Could not delete the post.’ );
    }

    Will doing this work? Is my data: { select_post : postID } automatically an array?

    $(‘#post_list’).submit( function () {
    var postID = $(‘.select_post’).val();
    $.ajax({
    type: ‘POST’,
    url: ‘delete_post.php’,
    data: { select_post : postID }
    }).success( function () {
    alert(‘deleted’);
    });
    });

    # March 9, 2013 at 12:22 pm

    NEVERMIND!!! I just had to create an array and pass it to my delete.php file.

    $(‘#post_list’).submit( function (e) {
    e.preventDefault();

    var postID = [];
    $(“.select_post[name=’select_post[]’]:checked”).each(function () {
    postID.push(parseInt($(this).val()));
    });
    alert(postID);

    $.ajax({
    type: ‘POST’,
    url: ‘delete_post.php’,
    data: { select_post : postID }
    }).success( function () {
    alert(‘deleted’);
    });
    });

    Thanks to myself :P

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".