- This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
Viewing 4 posts - 1 through 4 (of 4 total)
- The forum ‘Back End’ is closed to new topics and replies.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
How can i prepare this PHP code to make it more secure and reliable?
`
<?php
// Include database connection file
require_once("php/db-connect.php");
// get database data
try {
$sql = "SELECT ID, TITLE, COVER_URL FROM movies ORDER BY id DESC";
$q = $connect -> query($sql);
$q -> setFetchMode(PDO::FETCH_ASSOC);
} catch( PDOException $e ) {
echo "Could not retrieve data from the database";
die();
}
?>
`
By defining $connect
in another file and then importing it into scope using require_once
, you might eventually find yourself in a situation where it doesn’t actually become available. It’s better to pass the connection explicitly where you need it… but if you’re sticking to a procedural programming style, what you’re doing will usually work just fine. You might want to do something like:
require_once 'php/db-connect.php';
if( ! $connect instanceof PDO ){
/* something didn't work */
}
I’d also prefer to show the user an actual error page, rather than just dropping dead with a brief notice.
Other than that, are you trying to address any specific problem(s)?
No. There are no problems at all with it now but i’m being very cautious when learning PHP. So i guess ill leave it like that if theres no issue
It’ll work fine for most (probably the majority of typical) projects. It’s not a bad pattern, but it will become more fragile as your app becomes more complex. It also won’t work well if you adopt a more functional or object-oriented programming style — so, basically, it depends on what you want to do.