PHP - Delete Older Mysql Rows
I have a table with several fields, one of which is an amount of days after which the row will be deleted. Every time the script is run, I want to check for old entries and delete them. How would I do this?
Similar TutorialsI just have a general question about when other programmers remove rows older than say a year old.... Do most of you: 1) set up a CRON job to run daily at 3:00am 2) Add a routine at login for each user 3) Add a routine when a user moves into a certain portion of the application 4) A maintenance routine that an administrator manually has to envoke Or is there another way...I have done some research but most of the things google has showed me is the how not when to do this... <body> <?php include 'sql.php'; $query = "SELECT * FROM validation"; $result = mysqli_query($con , $query); $rows = mysqli_fetch_assoc($result) ; $totals = mysqli_num_rows($result) ; ?> <div id="css"> <form > <table width="80%" border="0" cellpadding="2" cellspacing="2" > <caption><h2>Personal Details of Customers</h2></caption> <tr class="white"> <td bgcolor="#330033"> </td> <td bgcolor="#330033"> Id Number </td> <td bgcolor="#330033"> Full Name </td> <td bgcolor="#330033"> Email Address </td> <td bgcolor="#330033"> Website </td> <td bgcolor="#330033"> Comment </td> <td bgcolor="#330033"> Time </td> </tr> <?php while($rows=mysqli_fetch_assoc($result) { <tr> <input type="raido" name="ID" value="<?php echo $rows['ID']; ?>" /> <td bgcolor="#FFFFCC"><?php echo $rows['ID'];?></td> <td bgcolor="#FFFFCC"><?php echo $rows['Name'];?> </td> <td bgcolor="#FFFFCC"><?php echo $rows['Email'];?></td> <td bgcolor="#FFFFCC"><?php echo $rows['Website'];?></td> <td bgcolor="#FFFFCC"><?php echo $rows['Comment'];?></td> <td bgcolor="#FFFFCC"><?php echo $rows['Time'];?></td> <td> </td> <td> <a href="delete.php? ID= "$rows[ID]" /"> <input type="submit" name="del" value="Delete" /> </a> <input type="button" name= "edit" value="Edit" /> </td> </tr> }?> </table> </form> </div> </body> Can I use php to delete multiple rows that have a checkbox selected. I'm not sure how to go about doing this. Any suggestions? in my code i have $query = "DELETE " . $DBPrefix . "bids WHERE auction = " . $Auction['id']; $system->check_mysql(mysql_query($query), $query, __LINE__, __FILE__); but if WHERE auction = " . $Auction['id'] doesnt match anything i returns the error Quote You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE auction = 8' at line 1 I really dont understand why its returning an error is this just a case of having to add some code to check if theres anything that actualy needs deleting first? Hi, I have created a table named multipath with database name "mydatabase".. I have created a table to store the data in the tables. Check boxes are created to select one row each to delete. But I am unable to delete the rows. Why?? Here's my PHP code <?php $host="localhost"; // Host name $username="root"; // Mysql username $password=""; // Mysql password $db_name="mydatabase"; // Database name $tbl_name="multipath"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $sql="SELECT * FROM $tbl_name"; $result=mysql_query($sql); $count=mysql_num_rows($result); ?> <table width="400" border="0" cellspacing="1" cellpadding="0"> <tr> <td><form name="form1" method="post" action=""> <table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC"> <tr> <td bgcolor="#FFFFFF"> </td> <td colspan="4" bgcolor="#FFFFFF"><strong>Delete multiple rows in mysql</strong> </td> </tr> <tr> <td align="center" bgcolor="#FFFFFF">#</td> <td align="center" bgcolor="#FFFFFF"><strong>Path ID</strong></td> <td align="center" bgcolor="#FFFFFF"><strong>Path</strong></td> </tr> <?php while($rows=mysql_fetch_array($result)){ ?> <tr> <td align="center" bgcolor="#FFFFFF"><input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $rows['id']; ?>"></td> <td bgcolor="#FFFFFF"><?php echo $rows['path_id']; ?></td> <td bgcolor="#FFFFFF"><?php echo $rows['path']; ?></td> </tr> <?php } ?> <tr> <td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete"></td> </tr> <? // Check if delete button active, start this if($delete){ for($i=0;$i<$count;$i++){ $del_id = $checkbox[$i]; $sql = "DELETE FROM $tbl_name WHERE id='$del_id'"; $result = mysql_query($sql); } // if successful redirect to delete.php if($result){ echo "<meta http-equiv=\"refresh\" content=\"0;URL=delete.php\">"; } } mysql_close(); ?> </table> </form> </td> </tr> </table> Please u can reply me at sawyerford007ATgmail DOTcom Hey everyone i having some trouble updating records in my databse using checkbox from a form. I can update the records, but i can't figure out how to remove records at the same time. I've posted the code that i'm using to update below foreach($_POST['tag'] as $k=>$l){ $tag = mysql_real_escape_string($_POST['tag'][$k]); $check_tags = mysql_query("SELECT * FROM file_cats WHERE category='$tag'") or die(mysql_error()); $num_tags = mysql_num_rows($check_tags); if($num_tags==0){ $add_tag = mysql_query("INSERT into file_cats (fileID, category) VALUES('$fileID', '$tag')") or die(mysql_error()); } } This code inserts new records based on what the user checked. If it exist it won't add a new row, if it doesn't exist then it will add a new row. but like i said how can remove a row if the box is no longer checked? I've tried using foreach(empty($_POST['tag'] as $k => $l){ $tag = empty($_POST['tag']['$k']; } But that didn't work basically nothing was deleted. Has anyone done something like this before? if so i would appreciate any help you could give Hey Guys. I have tried looking this up on Google but the only answers I am finding is using there where clause. I wanted to know if I can update or delete a range of rows like from id 100-200. Is there a way to do that? Thanks!
Hello all, im new to this forum, im a noobie, just started coding about 3 weeks ago, don't be too hard on me.
My question is I wan't to check for challenges a user's team posted that have not been excepted after 1 day, then auto refund the user's team back there credits, and then also delete all the challenges. So far here is my code.
//Delete all matches not accepted after 1 day $arrayin = array(); $autorefund = mysql_query("SELECT * FROM `challenges` WHERE `a` = " . $team['id'] . " " . "AND `accepted` = 0 AND `completed` = 0 AND `chtype` = 1 AND (`expires` < " . ((int) time()) . ")"); if (mysql_num_rows($autorefund) > 0) { while ($autorefund = mysql_fetch_assoc($autorefund)) { $arrayin[] = $autorefund['id']; mysql_query("UPDATE `teams` SET `balance` = `balance` + " . $autorefund['credits'] . " " . "WHERE `id` IN (" . mysql_real_escape_string(implode(',', $arrayin)) . ")"); mysql_query("DELETE FROM `challenges` WHERE `a` IN " . "(" . mysql_real_escape_string(implode(',', $arrayin)) . ") " . "AND `accepted` = 0 AND `completed` = 0 AND `chtype` = 1 " . "AND (`expires` < " . ((int) time()) . ")"); } }FYI here is the code i had, it works fine, however it will only delete 1 challenge per team, not all of there challenges. $autorefund = mysql_query("SELECT * FROM `challenges` WHERE `a` = " . $team['id'] . " AND `accepted` = 0 AND `completed` = 0 AND `chtype` = 1 AND (`expires` < ".((int)time()).")"); if (mysql_num_rows($autorefund) > 0) { while ($autorefund = mysql_fetch_assoc($autorefund)) { if ($autorefund['accepted'] == 0 and $autorefund['expires'] < time()) { mysql_query("UPDATE `teams` SET `balance` = `balance` + " . $autorefund['credits'] . " WHERE `id` = " . $team['id'] . ""); mysql_query("DELETE FROM `challenges` WHERE `a` = " . $team['id'] . " AND `accepted` = 0 AND `completed` = 0 AND `chtype` = 1 AND (`expires` < ".((int)time()).")); } } }I inherited this script, its using deprecated statements, i know im not skilled to rewrite the entire site to use prepared statements. I'm trying to set it so that it will delete an entire populated directory based upon a value in the database then after finishing that to go back and delete that row in the database. my current code is Code: [Select] <?php $page_title = "Central Valley LLC | Photo Addition" ?> <?php include("header.php"); ?> <?php include("nav.html"); ?> <div id="content"> <form action="delprod.php" method="post" enctype="multipart/form-data"> <label for="which">Choose A Product To Remove:</label> <?php $con = mysql_connect("localhost","phoenixi_cv","centraladmin"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("phoenixi_cvproducts", $con); $result = mysql_query("SELECT * FROM Products"); echo "<select name=\"which\">"; while($row = mysql_fetch_array($result)) { echo "<option "; echo "value=\"" . $row['id'] . "\">"; echo $row['Name'] . "</option>"; } echo "</select>"; mysql_close($con); ?> <br /> <input type="submit" name="submit" value="Submit" /> </form> </div><!--#content--> <?php include("footer.html") ?> and the delete script Code: [Select] <?php $con = mysql_connect("localhost","phoenixi_cv","centraladmin"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("phoenixi_cvproducts", $con); $result = mysql_query("SELECT id FROM Products WHERE id=$_POST['which']"); $row = mysql_fetch_array($result) chdir('assets'); chdir('images'); $mydir = $row . '/'; $d = dir($mydir); while($entry = $d->read()) { if($entry!="." && $entry!="..") { unlink($_POST['which'] . '/' . $entry); } } rmdir($mydir); $result = mysql_query("DELETE * FROM Producs WHERE id=$_POST['which']"); ?> Thank you in advance for all your help. any easier ways of approaching this will be welcome as well Hi there, I currently have this code that is supposed to delete a message according to their id. The ID is sent through a hidden input field, but it's still somehow not parsing correctly. Here it is.... Code: [Select] $query = mysql_query("SELECT * FROM messages WHERE to_user='$username' ORDER BY message_id DESC") or trigger_error('Error: '.mysql_error()); $numrows = mysql_num_rows($query); if ($numrows > 0){ while ($row = mysql_fetch_assoc($query)){ $id = $row['message_id']; $from = $row['from_user']; $to = $row['to_user']; $title = $row['message_title']; $content = nl2br($row['message_contents']); $date = $row['date']; $read = $row['message_read']; echo" <center> <table border='0' width='100%' style='text-align:center;'> <tr>"; if($read == 0){ echo"<td width='25%'><font color='white'><a href='inbox.php?action=view&mid=$id'><b>$title</b></a><b><i>NEW!</i></b></font></td>"; } else{ echo"<td width='25%'><font color='black'><a href='inbox.php?action=view&mid=$id'>$title</a></font></td>"; } echo"<td width='25%'><font color='black'>$from</font></td> <td width='25%'><font color='black'>$date</font></td> <td width='25%'><font color='black'> <form action='inbox.php' method='post'> <input type='submit' name='delete' value='Delete' class='button'> <input type='hidden' name='id' value='$id'> </form></td> </tr> </table></center> <br>"; if(isset($_POST['delete'])){ $message_id = $_POST['id']; mysql_query("DELETE * FROM messages WHERE message_id='$message_id'"); echo"<script type='text/javascript'> alert('Message deleted!') </script>"; } } } Hello there, I have this bit of code: Code: [Select] <?php $host="localhost"; // Host name $un="**"; // Mysql username $password="**"; // Mysql password $db_name="**"; // Database name $tbl_name="weddingpics"; // Table name // Connect to server and select database. mysql_connect("$host", "$un", "$password")or die("cannot connect"); $id = intval($_POST['id']); $sql="DELETE id='$id' FROM $tbl_name WHERE id=$id"; $result=mysql_query($sql); if($result){ echo "Successful"; echo "<BR>"; echo "<a href='weddingcakes.php'>View result</a>"; } else { echo "Error"; } ?> I've tried to reword the delete query but still no avail. If you are wondering where it pulls the `id` variable, it is on the previous page as a hidden attribute. I have made a simple form where users who have been subscribed and unsubscribe by inserting their email address. In my database using PHPMyAdmin, my database to store the emails is 'Links', the table is 'email' and the fields are the 'id' and 'emailaddress'. What I have tried is making a text input field, where the user ill insert his or her email address, to unsubscribe on the website. As a result the user's field for his or her email address will be delete in the database which is saving the emails for all users who have subscribed. My HTML codes a Code: [Select] <p>Subscribe for newsletters:</p> <img src="images/k-newsletter-icon.png" width="96" height="96" alt="subscri"/> <form action="index.php" method="post"> <input type="text" size="25" placeholder="Your email address..." name="enter"/> <input class="submit" type="submit" value="Subscribe" name="subscribe"/> </form> My PHP codes a Code: [Select] <?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { $email = $_POST['enter']; @mysql_connect ('localhost', 'root', '') or die ('Error'); @mysql_select_db ('links') or die ('Error'); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { echo "Not an email"; return false; } else { mysql_query("DELETE FROM email WHERE emailaddress ='$email'"); echo "deleted"; } } ?> When I test it,it is not working, as I see the email which was saved, is still in the database! Help! im wondering how to get php to read the latest row (instead of show them all) and when another one comes it replaces it once the page refreshes I am trying to delete child nodes using the parent_id, id. like the following...
id | parent_id
1 | 0
2 | 1
3 | 2
deleting id 2 should also delete id 3. How to get the follow code to work?
i am using mysql 5.1. this code gives a query syntax error on line number... but no error message.
"CREATE TABLE test( `id` INT(20) NOT NULL AUTO_INCREMENT, `parent_id` INT(8) NOT NULL, `title` TEXT NOT NULL, FOREIGN KEY (parent_id) REFERENCES test (id) ON DELETE CASCADE, PRIMARY KEY (`id`) ) ENGINE=INNODB DEFAULT CHARSET=utf8 ";when i use the following code, there is no errors. "CREATE TABLE test( `id` INT(20) NOT NULL AUTO_INCREMENT, `parent_id` INT(8) NOT NULL, `title` TEXT NOT NULL, PRIMARY KEY (`id`) ) ENGINE=myisam DEFAULT CHARSET=utf8 ";notice in the above code that i have changed the word INNODB to MYISAM for the ENGINE and removed the FOREIGN KEY. this code works but no "on delete cascade". The code is posted he http://codepad.org/Fck5s2zz The attached file (delete_user.php) is the same as the code in the link above. The same code is also posted below. [text] What I am trying to do is create a function that will allow me to delete a user from my mysql database. I have an HTML select that outputs the username(s) using the function get_admin_username() (The function is posted below) There is also a HTML form I am using to make this happen. (Also posted below) In other words I would select the user I would like to delete, and click submit which will then delete the user from the database. The problem I am having is I do not know how to pass values from the HTML select, or the form, or even use the submit button value. I am not sure If I need to create a function to achieve this. Basically I don't know what to do this at all for that matter. I thought I might have gotten close but I thought wrong, and failed. I was told (in the php irc) that my method was way off and wrong but was given no help after that. I do have an example to show you of how I tried to accomplish this, but being told that I was wrong I did not feel that it was even worth posting it. I am lost and have been at this for two days now. I am a noobe but I do understand allot (I think). Someone, anyone, please help. Thank You, Ryan [/text] Code: Code: [Select] <?php // Session's Functions require_once("../includes/sessions/session.php"); // Establish A Connection To The Database require_once("../includes/connection/connection.php"); // User Defined Admin Functions require_once("includes/functions/admin_functions.php"); // New User Functions //require_once("includes/users/delete_user.php"); // Confirms If The User Is Logged In confirm_logged_in(); // Document Header include("includes/templates/default/header.php"); ?> <?php // Gets The Admin Username function get_admin_username() { global $connection; $query = "SELECT * FROM administration_users "; $query .= "ORDER BY username"; $admin_user_set = mysql_query($query, $connection); confirm_query($admin_user_set); while ($admin_users = mysql_fetch_array($admin_user_set)) { echo "<option value=\"username" . "\">" . $admin_users['username'] ."\n "; } } ?> <table id="structure"> <tr> <td id="navigation"> <a href="../staff.php">Return To Staff Menu</a> <a href="admin_content.php">Return To Admin Menu</a> <br /> <br /> <ul class="menu"> <li class="pages"><a id="page_menu" href="new_user.php">Add New User</a></li> <li class="pages"><a href="edit_user.php">Edit User</a></li> <li class="pages"><a href="list_users.php">List Users</a></li> <li class="pages"><a href="delete_user.php">Delete User</a></li> </ul> </td> <td id="page"> <h2>Remove User</h2> <br /> <form action="delete_user.php" name="delete_user" method="post"> <table> <tr> <th class="field_name field_padding_user_name">User Name: </th> <td> <select id="select_username" name="username_select"> <?php echo get_admin_username();?> </select> </td> </tr> <tr> <td class="delete_user_submit" colspan="2"><input type="submit" name="submit" value="Delete User" onclick="return confirm('Are You Sure You Want To Delete This User?');"/></td> </tr> </table> </form> </td> </tr> </table> <?php // Document Footer include("includes/templates/default/footer.php"); ?> MOD EDIT: [code] . . . [/code] tags added. basically could somebody help me with information on having a php script that deletes mysql rows which are older than 3 hours old. I know MYSQL table will need a date/time column but how can I only target ones which are 3 hours old+. Thanks I have a MySQL query that returns rows containing date_add column like below:
DATE(date_add) 2014-01-07 2014-01-07 2014-01-07 2014-01-07 2014-01-08 2014-01-15 2014-01-20 2014-01-20 2014-01-20 2014-01-26 2014-01-28 2014-02-16 2014-02-16 2014-02-16 2014-02-16 2014-02-16 2014-02-16 2014-02-16 2014-02-18 2014-02-18 2014-03-08 2014-03-08How can I have pagination based on dates and show rows with the same date in a page and not just based on predefined limit number? I have a HTML dropdown list which is populated from a MySQL table. I use an auto-incremend ID field. I have also got a sort_order field. I would like to be able to specify the exact order that entries should appear in the dropdown list. Specifically I need some functionality that does the following two things: 1) If I change the sort order of a record to for example "4" then the existing record with sort_order 4 becomes 5, sort_order 5 becomes 6 and so on. 2) If I change the sort order of a record to for example "4" and there is currently no record with sort_order 4, then no other records will be updated. I'm trying to pull user referral data from my database. This is what I have so far. <table cellpadding="0" cellspacing="0" style="border:1px #000000 solid;" width="68%"> <tr> <td bgcolor="#eeeeee" style="padding:2px;border-right:1px #000 solid;border-bottom:1px #000 solid;"><font size="2" face="verdana"><b> User </b></font></td> <td bgcolor="#eeeeee" style="padding:2px;border-right:1px #000 solid;border-bottom:1px #000 solid;"><font size="2" face="verdana"><b> </b></font></td> <td bgcolor="#eeeeee" style="padding:2px;border-right:1px #000 solid;border-bottom:1px #000 solid;"><font size="2" face="verdana"><b> Date </b></font></td> <td bgcolor="#eeeeee" style="padding:2px;border-bottom:1px #000 solid;"><font size="2" face="verdana"><b> Visits </b></font></td> </tr> <? $lole=$_COOKIE["usNick"]; $tabla = mysql_query("SELECT * FROM tb_users where username='$lole' ORDER BY id ASC"); while ($row = mysql_fetch_array($tabla)) { echo "<tr><td><font size=\"2\" face=\"verdana\">"; echo $row["username"]; echo "</font></td><td><font size=\"2\" face=\"verdana\">"; echo $row["email"]; echo "</font></td><td><font size=\"2\" face=\"verdana\">"; echo $row["joindate"]; echo "</font></td><td><font size=\"2\" face=\"verdana\">"; echo $row["visits"]; echo "</font></td></tr>"; } echo "</table>"; ?> <script type="text/javascript"> initSortTable('myTable',Array('S','N','S','N','S')); </script> I just found out my user ID is missing from database.. Ok I am trying to delete some rows from a database. I have done this before with success so I thought I could use the same method just modify it a little and it would work. Man was I wrong. Any help on this is much appreciated below is my code. Code for the Query to get the data from the database and for displaying the results in a table: Code: [Select] //GET DATA $sql = "SELECT * FROM `".$tblname."` ORDER BY $orderby $sort LIMIT $startrow,$limit"; $result = mysql_query($sql) or die(mysql_error()); $result2 = mysql_query($sql); //START TABLE AND TABLE HEADER echo "<form name='form1' method='post' action=''><table style='font-size:9.5px;'>\n<tr><th>Delete</th>"; $array = mysql_fetch_assoc($result); foreach ($array as $key=>$value) { if($config['nicefields']){ $field = str_replace("_"," ",$key); $field = ucwords($field); } $field = columnSortArrows($key,$field,$orderby,$sort); echo "<th>" . $field . "</th>\n"; } echo "</tr>\n"; //reset result pointer mysql_data_seek($result,0); //start first row style $tr_class = "class='odd'"; //LOOP TABLE ROWS while($row = mysql_fetch_assoc($result)){ echo "<tr ".$tr_class.">\n<td><a href='remove_rec.php?id=". $rows['ID'] . "'><p>Delete</p></a>"; echo "</td>"; foreach ($row as $field=>$value) { echo "<td>" . $value . "</td>\n"; } echo "</tr>\n"; //switch row style if($tr_class == "class='odd'"){ $tr_class = "class='even'"; }else{ $tr_class = "class='odd'"; } } //END TABLE echo "</table>\n</form>"; Here is the code that should delete the row: Code: [Select] $tblname = 'tablename'; // get value of id that sent from address bar $id=$_GET['ID']; // Delete data in mysql from row that has this id $sql="DELETE FROM $tblname WHERE ID='$id'"; $result=mysql_query($sql); // if successfully deleted if($result){ echo "Deleted Successfully"; echo "<BR>"; echo "<a href='leads3.php'>Back to Results</a>"; } else { echo "ERROR"; } When I click on the link to delete a record it redirects me to the appropriate page with the "Deleted Successfully" message but when I go to view the results the row was not deleted. Any help on this would, again, be greatly appreciated. |