简体   繁体   中英

How can I throw an error with PDO/MySQL when a string is not valid or found in the database?

Apologies for the apparent simplicity of what I'm trying to do here, I'm a little bit new when it comes to PDO/PHP... I'm currently having a slight issue with my site that could potentially pose a bit of a security risk.

I have a 'video' page that is passed a variable ( video.php?id=VALUE ) by the URL -

At the moment I have my page set-up like this:

<?php 
    $video = $_GET['video'];
    $videodata = $pdo->prepare("SELECT * FROM video WHERE siteurl = ? LIMIT 1");
    $videodata->execute([$video]);
    ?>

    <head>
     <meta charset="utf-8">
     <meta http-equiv="x-ua-compatible" content="ie=edge">

     <title>   
     <?php
     foreach ($videodata as $videodatas) {
     echo "{$videodatas['title']}</title>";

     echo "<meta property=\"og:title\" content=\"{$videodatas['title']}\"/>"; }?>
     <meta name="description" content="Description lives here">

     <meta name="viewport" content="width=device-width, initial-scale=1">
     <meta name="apple-mobile-web-app-capable" content="yes">

     <meta property="og:url" content="<?php echo "http://" . $_SERVER['HTTP_HOST']  . $_SERVER['REQUEST_URI'];?>" />


     <link rel="apple-touch-icon" href="apple-touch-icon.png">

     <link rel="stylesheet" href="scripts/style.css">


    </head>

When this successfully matches it generates the page, showing the correct video and listing the correct video title in the <title> tags and throughout the rest of the page.

However, when I'm testing an incorrect variable in the URL or something that is not in my database, the page is spitting out a completely blank page (no errors) that is including all of the raw HTML in the <title> tag.

How can I prevent this and instead throw a redirect to my 404 page?

Just put a condition before your sql :

if (isset($_GET['video']) && $_GET['video'] !="") {
    $video = $_GET['video'];
    $videodata = $pdo->prepare("SELECT * FROM video WHERE siteurl = ? LIMIT 1");
    $videodata->execute([$video]); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM