I need to add a check box on the end of each value in my html table that will be checked if the user would like to remove that value from the mysql database, my current cod elooks like this:

<?php
$con = mysqli_connect("localhost", "root", "", "numbers") or die(mysqli_error($con));
// Check connection

$result = mysqli_query($con,"SELECT * FROM usernumdata");

echo "<table border='1'>
<tr>
<th>First name</th>
<th>Last name</th>
<th>Phone Number</th>
<th>Date Added</th>
<th>Time Added</th>
</tr>";

while($row = mysqli_fetch_array($result)) {
  echo "<tr>";
  echo "<td>" . $row['firstname'] . "</td>";
  echo "<td>" . $row['lastname'] . "</td>";
  echo "<td>" . $row['numb'] . "</td>";
  echo "<td>" . $row['date'] . "</td>";
  echo "<td>" . $row['time'] . "</td>";
  echo "</tr>";
}

echo "</table>";

mysqli_close($con);
?>

Obviously from my setup i would like if the user could click multiple checkboxes from the table and delete them all at once. Ive attached an image of what the table looks like now.

While im at it i would like to know if there is a way to check to see if multiples of the same number in the table already exist, that way i could keep the user from submitting multiples of the same thing, how would i go about checking this?

Recommended Answers

All 13 Replies

There are TONS AND TONS of these examples all over about this bud. Here's the first one I found after a quick google search:

Delete multiple rows from mysql with checkbox

Make an attempt at that and if you still have any questions, I would love to help.

Member Avatar for diafol

As dj states there are many examples out there. You have to

1) include a checkbox for each record in your php loop
2) make sure that the checkbox name includes the right id or you can just give the value attribute the id.

$output .= "<td><input type='checkbox' name='delete[{$row['id']}]' /></td>";

or

$output .= "<td><input type='checkbox' name='delete[]' value='{$row['id']}' /></td>";

You'll notice I concatenated this in a string ($output) - echoing every single little thing, one at a time, wastes a lot of time. Concatenate an output string and echo/print ONCE only.

3) Remember to use POST not GET with anything that changes data in files, dbs etc.

4) You can pick up the post data thus:

$delete = (array) $_POST['delete'];

5) Check that the current user is logged in and has sufficient priviledges to delete data from the db. Do not allow blind delete routines.

6) Run an array function, such as array_filter or array_map to validate the item data (integer datatype, greater than 0 etc). Possibly use php's built-in validation or sanitize functions.

7) Run a SINGLE query to delete valid ids. E.g.

DELETE FROM table WHERE some_id IN ($arrayList)

Where $arrayList is just an imploded string with "comma glue" from the sanitized id array, e.g.

$arrayList = implode(',', $cleanArray);

You can do this via "full-fat form submission" or you can do it via ajax. If you decide on the latter, you will need some feedback at to which records have been successfully removed. Too many ajax routines remove displayed records in html tables before they receive confirmation in the callback telling them whether the deletion has been succeessful or not. If your html table uses "pagination", then you may need to make a second mysql query to update the displayed html table - i.e. move records up to fill spaces left by successfully deleted rows.

Well so far i have my table the way i like which is wonderful but now my delete portion o fmy code isnt working, and im sure i have made a programming logic mistake so bear with me

here is my code, i know its wrong but keep in mind im still pretty new to php so please go easy on me lol

$delete = (array) $_POST['delete'];

if($delete){
    for($i=0;$i<$count;$i++){
    $del_id = $checkbox[$i];
    $arrayList = implode(',', $cleanArray);
    $sql = "DELETE FROM usernumdata WHERE $del_id IN ($arrayList)";
    $result = mysqli_query($con, $sql);
    }
    if($result){
    echo "<meta http-equiv='refresh' content='0;URL=table.php'>";
    }
}

thank you both for all the assistence i have recieved, this has been some of the best guided self learning i have ever had and i greatly thank you both especially you diafol, i truly do appreciate it :)

also i forgot to post what my table form looks like, this is it

while($row = mysqli_fetch_array($result)) {
  echo "<tr>";
  $output = "<td><input type='checkbox' name='delete[{$row['id']}]' /></td>";
  echo $output;
  echo "<td>" . $row['id'] . "</td>";
  echo "<td>" . $row['firstname'] . "</td>";
  echo "<td>" . $row['lastname'] . "</td>";
  echo "<td>" . $row['numb'] . "</td>";
  echo "<td>" . $row['date'] . "</td>";
  echo "<td>" . $row['time'] . "</td>";
  echo "</tr>";
}

this seems to work so i think its right, i just wanted a second opinion lol

Member Avatar for diafol

A few issues...

echo "<meta http-equiv='refresh' content='0;URL=table.php'>";

Do this instead...

header("Location:table.php");exit;

Also you need to check wheether the current user (you?) has sufficient privileges to delete the data... e.g.

if(isset($_SESSION['rights']) && $_SESSION['rights'] == 'admin')
{
    //your delete code
}

//your redirect header code

Don't forget to filter your input data and you're running a for loop - no need:

$rawdelete = (array) $_POST['delete'];
$delete = array_map("intval", $rawdelete); //forces all items to integer
if($delete && isset($_SESSION['rights']) && $_SESSION['rights'] == 'admin')
{
    $arrayList = implode(',', $delete);
    $sql = "DELETE FROM usernumdata WHERE $del_id IN ($arrayList)";
    $result = mysqli_query($con, $sql);
}
header("Location:table.php");exit;

You could check the number of rows deleted as flash a messeage before redirecting to table.php:

header('Refresh: 3; url=table.php');

This could be used thus...

$affected = "No rows were deleted";
$rawdelete = (array) $_POST['delete'];
$delete = array_map("intval", $rawdelete); //forces all items to integer
if($delete && isset($_SESSION['rights']) && $_SESSION['rights'] == 'admin')
{
    $arrayList = implode(',', $delete);
    $sql = "DELETE FROM usernumdata WHERE $del_id IN ($arrayList)";
    $result = mysqli_query($con, $sql);
    $affected = "You deleted " . mysqli_affected_rows($con) . " rows";
}
echo $affected;
header('Refresh: 3; url=table.php');exit; //3 second delay before refresh

I fixed my code but im still not getting any results :( Its not doing anything and unfortunatly the line:

header('Refresh: 3; url=table.php');exit; //3 second delay before refresh

gave me this error:

Warning: Cannot modify header information - headers already sent by (output started at C:\AppServ\www\newsearch\table.php:9) in C:\AppServ\www\newsearch\table.php on line 56

not sure at all what to do :(

Member Avatar for diafol

Sorry, place the echo after the header().

It'll only work if you have $_SESSION['rights'] set and it holds a value of 'admin'. You need to place a

session_start();

right at the top of the file.

Before the

if($delete && isset($_SESSION['rights']) && $_SESSION['rights'] == 'admin')

line, do this:

$_SESSION['rights'] = 'admin';

just to hard-code the session value for now. Obviously this should be set during your user login procedure.

i changed it but it did nothing, its strange cause i found another solution to my problem somewhere that i literally pulled the whole project file and it worked marvoulously, but what confuses me is that its the exact same set up we have here but without the admin rights, literally the only difference is the delete portion of this setup is its own file. heres the link to the file, i hope its ok to use this cause id rather not steal anyones work if i can help it.

http://www.sourcecodester.com/php/5270/delete-multiple-rows-checkbox-mysql.html

Please inform me if its illegal to use this code because ill be using this in a professional workplace environment :/

also i chose to use this because the table that red data is beautiful and looks gorgous with mutiple functions built right in making it extremely useful

Member Avatar for diafol

The site states in its ToC:

By submitting your source code, article, and tutorial you agree that you grant all users permission, including sourcecodester.com, to view, copy, edit or modify (for source code only) any content you have submitted.

So I take it that means you can use it for your own needs. Do not take my word for it though. You should read all policies and ToCs and any accompanying licences.

I have a pretty liberal view towards any source code that I post to forums and my own demo sites - "use it however you want, I don't care - but I won't be held responsible for my code cacking up your system". Other people/sites are a bit more conservative. As the site itself encourages you to download the source code and deosn't seem to have any licences attaches, I think it's pretty safe to use. Especially as the code is nothing special - it's just routine stuff that has been independently created hundreds or thousands of times before. Similar to code that I posted here, it would be a bit ridiculous to apply any sort of restriction on it.

Most if not all of code is developed over years by looking at other people's code in books, tutorials and manuals. But that's not to say that the original author does not deserve an attribution (or whatever he/she requires as part of the ToC).

I agree, i read the apache license and it plainly states that as long as you do not try to come after them with lawsuits and that u do not hold them responsible then u can use he code freely in free or personally derived products. Also thank you for the help, i still needed to sue this code because i needed to print basic tables that could be modified and thats what i have accomplished.

for the record the sites licensure is here and there codes are as well, for any people who come across this post.

http://www.apache.org/licenses/LICENSE-2.0

http://getbootstrap.com/2.3.2/#transitions

Thanks so much and happy coding!

There is something more i need help with lol, i need to know how i can print data from the table based on a double search query, like from _______ to _______ print this to a csv file, i have the printing figured out but im not sure how to use the double query? here is what i have so far.

if(isset($_GET['submit']))
{
    $e = $_GET['e'];
    $b = $_GET['b'];
}

//or die("Database Connection Failed");
$selectdb=mysql_select_db($database) or 
die("Database could not be selected"); 
$result=mysql_select_db($database)
or die("database cannot be selected <br>");

// Fetch Record from Database

$output = "";
$table = "usernumdata"; // Enter Your Table Name 
$sql = mysql_query("SELECT * FROM $table WHERE date= '".$e."'");
$columns_total = mysql_num_fields($sql);

// only print the values from the table that align with search query


if($results = mysql_fetch_array($sql))
{
    // Get The Field Name

    for ($i = 0; $i < $columns_total; $i++) {
        $heading = mysql_field_name($sql, $i);
        $output .= '"'.$heading.'",';
    }
    $output .="\n";

    // Get Records from the table

    while ($row = mysql_fetch_array($sql)) {
        for ($i = 0; $i < $columns_total; $i++) {
            $output .='"'.$row["$i"].'",';
        }
        $output .="\n";
    }
}


// Download the file

$filename = "usernumdataexported.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);

im pretty sure all information needed is there so if anything else is needed please let me know.

I agree, i read the apache license and it plainly states that as long as you do not try to come after them with lawsuits and that u do not hold them responsible then u can use he code freely in free or personally derived products. Also thank you for the help, i still needed to sue this code because i needed to print basic tables that could be modified and thats what i have accomplished.

nvm i got all that i needed :D thank you all for all this help cause i could not have done it without u

Member Avatar for diafol

Sorry didn't get back to you sooner, hectic personal life at the moment. Glad you sorted it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.