Delete automaticaly data from db..help please!!

Hi people!!
I need to understand how can i delete automaticaly a record from mysql. In this example from “http://www.tutorialspoint.com/php/mysql_delete_php.htm” we can delete it with the input tag. But i need to set a specific date from a select tag and delete the record automaticaly at term of date…what is the right way???

Here is the original code:

Delete a Record from MySQL Database <?php if(isset($_POST['delete'])) { $dbhost = 'localhost:3036'; $dbuser = 'root'; $dbpass = 'rootpassword'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } $emp_id = $_POST['emp_id']; $sql = "DELETE employee ". "WHERE emp_id = $emp_id" ; mysql_select_db('test_db'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not delete data: ' . mysql_error()); } echo "Deleted data successfully\n"; mysql_close($conn); } else { ?>
Employee ID
<?php } ?>

Do it in baby steps,

  1. First add the Select tag to your HTML
  2. Then read the value Post Value of the SELECT Tag in PHP
  3. Then use that Value to Build the proper SQL Statement to delete it by date.

If you get stuck at any of those steps, post the code that you have (After you attempted it) and I’m sure one of us will help you get going.

Thanks Topcoder…! The code is too long :(.
Do you know the tutorial “build a cms in an afternoon” from Matt Doyle??
In the edit page the user can set the publication Date of the article and a link to delete it,
My request is :
what is the right way to add a select box to set the date to delete the article automaticaly at the term of date??

Thanks to anyone can help me.

Are you trying to learn php or just fix and issue your having with an app?

Yes Topcoder i’m trying to learn php and i have a problem with a home cms.
I need to understand ,If you can help me i will post another code.

what is the right way to add a select box to set the date to delete the article automatically at the term of date??

Lets do it together, since you want to learn… Show me some PHP code with a Select Box where you can pick the date from it…

If you get stuck, post what you have and we’ll modify it together.

Thanks!!! Ok this is another code i try to do:
I need to set an expiration date to the article to delete it automaticaly on date.
I’m sorry i can’t attach any attachments because i’m write from iPhone.

display.php:

[php]

<link rel="stylesheet" type="text/css" href="style.css" />
<?php
  include_once('cms.php');
  $obj = new simpleCMS();

  /* CHANGE THESE SETTINGS FOR YOUR OWN DATABASE */
  $obj->host = 'localhost';
  $obj->username = 'root';
  $obj->password = '';
  $obj->table = 'database_name';
  $obj->connect();

  if ( $_POST )
    $obj->write($_POST);

  echo ( $_GET['admin'] == 1 ) ? $obj->display_admin() : $obj->display_public();

?>
</div>
[/php] cms.php:

[php]<?php

class simpleCMS {

var $host;
var $username;
var $password;
var $table;

public function display_public() {
$q = “SELECT * FROM testDB ORDER BY created DESC LIMIT 3”;
$r = mysql_query($q);

if ( $r !== false && mysql_num_rows($r) > 0 ) {
  while ( $a = mysql_fetch_assoc($r) ) {
    $title = stripslashes($a['title']);
    $bodytext = stripslashes($a['bodytext']);
    $created = date ("Y-m-d, H-m-s");
    $day = $_POST['day'];
    $month = $_POST['month'];
    $year = $_POST['year'];
    $entry_display .= <<<ENTRY_DISPLAY

<div class="post">
	<h2>
		$title
	</h2>
    <p>
      $bodytext
    </p>
        <p>
          $created
        </p>

         <br/>
        the expiration date you select is: $day /$month/$year

</div>

ENTRY_DISPLAY;
}
} else {
$entry_display = <<<ENTRY_DISPLAY

<h2> This Page Is Under Construction </h2>
<p>
  No entries have been made on this page. 
  Please check back soon, or click the
  link below to add an entry!
</p>

ENTRY_DISPLAY;
}
$entry_display .= <<<ADMIN_OPTION

<p class="admin_link">
  <a href="{$_SERVER['PHP_SELF']}?admin=1">Add a New Entry</a>
</p>

ADMIN_OPTION;

return $entry_display;

}

public function display_admin() {
return <<<ADMIN_FORM

<form action="{$_SERVER['PHP_SELF']}" method="post">

  <label for="title">Title:</label><br />
  <input name="title" id="title" type="text" maxlength="150" />
  <div class="clear"></div>
 
  <label for="bodytext">Body Text:</label><br />
  <textarea name="bodytext" id="bodytext"></textarea>
  <div class="clear"></div>
1 2 3 1 2 3 2004
  <input type="submit" value="Create This Entry!" />
</form>

<br />

<a href="display.php">Back to Home</a>

ADMIN_FORM;
}

public function write($p) {
if ( $_POST[‘title’] )
$title = mysql_real_escape_string($_POST[‘title’]);
if ( $_POST[‘bodytext’])
$bodytext = mysql_real_escape_string($_POST[‘bodytext’]);
if ( $title && $bodytext ) {
$created = date (“Y-m-d, H-m-s”);
$sql = “INSERT INTO testDB VALUES(’$title’,’$bodytext’,’$created’)”;
return mysql_query($sql);
} else {
return false;
}
}

public function connect() {
mysql_connect($this->host,$this->username,$this->password) or die("Could not connect. " . mysql_error());
mysql_select_db($this->table) or die("Could not select database. " . mysql_error());

return $this->buildDB();

}
/this is the function i try to do…but i need to store the select values at date/

public function delete(){
$q = “DELETE FROM testdb VALUES (’$title’,’$bodytext’,’$created’)”;
$r = mysql_query($q);

private function buildDB() {
$sql = <<<MySQL_QUERY
CREATE TABLE IF NOT EXISTS testDB (
title VARCHAR(150),
bodytext TEXT,
created VARCHAR(100)
)
MySQL_QUERY;

return mysql_query($sql);

}

}

?>[/php]

If this is your table

[php]CREATE TABLE IF NOT EXISTS testDB (
title VARCHAR(150),
bodytext TEXT,
created VARCHAR(100)
)[/php]

Then you really need a column for the expiration date in your table.

So alter the table above and create a column for the expiration date, that’s a date column (Not a Varchar) you should already consider changing the “created” column to a date field.

So if you don’t care about time use Date as your column type, if you care about time use datetime.

Once you get your database structured right, post back with the database layout.

Like this??

CREATE TABLE IF NOT EXISTS testDB (
title VARCHAR(150),
bodytext TEXT,
created DATE,
expirationdate DATE
)

Good…

Now we will add a primary key to the table.

CREATE TABLE IF NOT EXISTS testDB (
id INT NOT NULL AUTO_INCREMENT,
title VARCHAR(150),
bodytext TEXT,
created DATE,
expirationdate DATE,
PRIMARY KEY (id)
)

Now following your example in your code you posted you have this…

[php] $day = $_POST[‘day’];
$month = $_POST[‘month’];
$year = $_POST[‘year’];[/php]

Code update statement to update the table with the current expiration date…

Lets pretend you have this record with the ID of 1 in the database - Write the update statement that will update the expiration date… What do you put in place of the ?'s

[php]updatequery = “UPDATE testDB SET expirationdate = ??? WHERE ID=1;”
[/php]

:o

updatequery = “UPDATE testDB SET expirationdate = $day, $month, $year WHERE ID=1;”

??? Something like this???
:-X

Not quite,

The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.

After reading the above statement, try it again and don’t forget the single quotes…

‘YYY,MMM,DDD’

updatequery = “UPDATE testDB SET expirationdate = DATE(’$year, $month, $day’) WHERE ID=1;”

It’s right??

Nope… The way you coded it your using the DATE function in MySQL

Which does this…

[php]Extracts the date part of the date or datetime expression expr.

mysql> SELECT DATE(‘2003-12-31 01:02:03’);
-> ‘2003-12-31’[/php]

You’re missing the single quotes, you can do this…

[php]updatequery = “UPDATE testDB SET expirationdate = '” . $year . “-” . $month . “-” . $day . “’) WHERE ID=1;”
[/php]
Or you can do this…

[php]updatequery = “UPDATE testDB SET expirationdate = ‘$year-$month-$day’) WHERE ID=1;”[/php]

And there’s another dozen ways you can do it. If you do it the way above you’ll need to make your Day drop down have the leading 0… (01,02,03, … , 31) since it expects DD and same for the MM.

Now write the delete statement for the same record…

Uhmmmm…and something like this? Can work??

If (date() == $expirationdate){
mysql_query (“DELETE FROM testDB WHERE ID=1”)
}else{
}

Thanks TopCoder to help me.

A surefire way would be something like this.

[php]mysql_query (“DELETE FROM testDB WHERE expirationdate >= '” . date(‘Y-M-d’) . “’”); [/php]

Which should delete everything that has an expirationdate greater to or equal to today’s date.

This is everything i need??
We don’t need to create a function?

:o Shouldn’t that be < or = to the current date???

You are correct.

@TopCoder

This statement need to be include in the delete function??

mysql_query (“DELETE FROM testDB WHERE expirationdate >= '” . date(‘Y-M-d’) . “’”);

Sponsor our Newsletter | Privacy Policy | Terms of Service