0

I am in need of a little help. I am trying to update a SQL database using php. Here I have a form button

echo '<td><center>  <form action="completebooking.php?id=' . $row['contentid'] . '" method="post"><input type="submit"  class="btn btn-info"  name="Complete" value="Complete"></form></center> </td>';

This then calls completebooking.php file where the PDO Update code is as below. This completebooking file only needs to update 3 fields, and uses the ID (called contentid) to update the relevant table.

try {
  $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $sql = "UPDATE completebooking SET `BookOn` = 'Off', `TimeOff` = '$mytime', `BookOff` = '$user' WHERE `contentid` = '$contentid'  ";


  $q = $conn->query($sql);
  $q->setFetchMode(PDO::FETCH_ASSOC);

} catch (PDOException $pe) {
  die("Could not connect to the database $dbname :" . $pe->getMessage());
}

header("Location: completbooking.php");

I want to be able to change the above to PDO statements but I am not getting there.

The three fields to fill in will be:

  • BookOn will always = off
  • TimeOff will be the time the button was clicked
  • BookOff will be the logged in user who clicked the button.

Those variables I will be defining as:

$mytime = date("H:i:sa");
$user = $user->data()->username;
$contentid = $_GET['contentid'];

Could someone help me with changing this to PDO the sql update bit? I have tried this:

$fields = [
  "Bookon"=>"Off",
  "TimeOff"=>$mytime,
  "BookOff"=>$user->data()->username
   ]; 

And then using:

$sql->update("completebooking",$contentid,$fields);

But this doesnt work, also would the redirect work properly back to the original page if all is successful? I am trying to convert the database to PDO from MySQL to prevent any SQL Injection.

ADyson
  • 57,178
  • 14
  • 51
  • 63
Azzieman
  • 1
  • 1
  • You need to use parameters and prepared statements to prevent SQL injection and to increase the overall reliability of your code. Right now this would break if any of your values even includes a simple `'`, never mind an injection attack. You'll solve both with prepared statements and parameters. See [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – ADyson Mar 18 '22 at 15:37
  • There is no update() method in PDO, least in the PHP strings (which your $sql is). You are either confusing PDO with something else or just didn't find a correct example – Your Common Sense Mar 18 '22 at 15:38

0 Answers0