Trying to delete records from a table. I have looke on line and I am following the examples but I can't get prepare() and execute() to work.

function DeleteOldData()
{
	$pdo = connectDB();
	$Date = time();
	$Month = date('m' ,$Date);
	$Year = date('Y' ,$Date);
	$Month -= 1;
	if ($Month == 0)
	  {
	   $Month = 12;
	   $Year -= 1;
	  }
	$Date = $Year . "-" . $Month . "-01";
	$sqlOldData = "DELETE from `Bank_Data` Where EntryDate < ? ";
	$stmt= $pdo->prepare($sqlOldData);
	$return = $stmt->execute($Date);	
	exit;
}

    The argument to the execute() must be an array, so in this case (since using an unnamed ? place-holder):

    $return = $stmt->execute([$Date]);
    

    (Like you did in your reply, above)

      PS: If using MySQL, you might consider just letting the SQL handle it, something like

      function DeleteOldData()
      {
      	$pdo = connectDB();
      	$sqlOldData = "DELETE FROM Bank_Data WHERE EntryDate <  CURDATE() - INTERVAL 1 MONTH";
      	$return $pdo->query($sqlOldData);
      }	
      

      PPS: Just return the result, and you do not want (normally?) to exit; from a function, as that will kill your script at that point.

        "If using MySQL,"
        The problem is that my hosting provider is upgrading from PHP4.5 to PHP7. So MySQL will no longer work. I am moving to PDO and converting all database code to this.

        Will "DELETE FROM Bank_Data WHERE EntryDate < CURDATE() - INTERVAL 1 MONTH";
        Work with PDO and PHP7?

        otuatail The problem is that my hosting provider is upgrading from PHP4.5 to PHP7. So MySQL will no longer work. I am moving to PDO and converting all database code to this.

        NogDog is not talking about PHP's MySQL extension. PDO works perfectly fine with the MySQL RDBMS (as one would expect, given how many people use MySQL, and as you've already seen from all the stuff you've written already). The SQL in the query is exactly that: SQL. It runs in the database.

        "PHP4.5 to PHP7"

        Shocked on both ends of that spectrum. Php 7 is already past end of life. Time to get a new host.

          Well I would like to make my website PHP8 ready.

          Okay but I changed
          WHERE EntryDate < CURDATE() - INTERVAL 1 MONTH
          date('Y-m-d', strtotime('first day of last month'))
          as I wanted all before first of month. CURDATE() would be middle of month to middle.

          Thanks for your help. It seems to be working fine now.

            6 days later

            Looks like you could do it in the SQL with:

            where EntryDate < last_day(curdate() - interval 2 month) + interval 1 day
            

            (Not claiming that's the "best" way, but a way that could be used if you prefer.)

              Write a Reply...