PHP – Writing to an Access .MDB database using a DSN-less connection.

Hot on the heels of the last article on READing data from an MS Access .MDB database file comes the eagerly anticipated sequel: “Writing to an MS Access .MDB database using a DSN-less connection.”

What a snappy title! 🙂

Here goes then. You will of course remember from the last lesson how to make the DSN-less connection to the database. No? Well here is a refresher:

//Set up the connection
if (!$conn = new COM(“ADODB.Connection”))
exit(“Unable to create an ADODB connection”);
$strConn = “DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=” . realpath(“mydatabase.mdb”);
$conn->open($strConn);

Next we read in the data that we wish to save to the database. Here I’m reading something posted from another page. You know the method “mypage.php?ids=1-2-3&tops=1-2-3&lefts=1-2-3” etc etc. Hint: We use $_GET[‘ids’] to do this:

$iconids = trim(strip_tags($_GET[‘ids’]));
$icontops = trim(strip_tags($_GET[‘tops’]));
$iconlefts = trim(strip_tags($_GET[‘lefts’]));

// Because multiple values are passed we need to EXPLODE them (in VBScript its called Split).
$DB_IDs = explode(“-“, $iconids);
$Coord_Tops = explode(“-“, $icontops);
$Coord_Lefts = explode(“-“, $iconlefts);

$counter = 0;

Now we just need to iterate through each value and commit it to the database using a small bit of SQL.

foreach ($DB_IDs as $value) {

$strUpdateSQL = “UPDATE tblLocation SET Location_Coords_Top=” . $Coord_Tops[$counter] .”, Location_Coords_Left=” . $Coord_Lefts[$counter] . ” WHERE Location_ID=” . $value;
$rs = $conn->execute($strUpdateSQL);

$counter = $counter + 1;

}

echo “Saved!”;

Don’t forget to tidy up after yourself! Remember to close those objects!

$conn->Close();
$rs = null;
$conn = null;

Well, that wasn’t particularly difficult was it?

Comments are closed.