single quotes in SQL Query

后端 未结 5 2195
半阙折子戏
半阙折子戏 2020-12-20 10:26

Im writing a php script that is used to update a database but it is giving errors when i tries to run the query it returns an error along the lines of

You h         


        
5条回答
  •  鱼传尺愫
    2020-12-20 10:53

    You need to escape the variables properly and surround them by single quotes:

    mysql_query("UPDATE
                    Videos
                SET
                    Title = '".mysql_real_escape_string($_POST['Title'])."',
                    Preacher = '".mysql_real_escape_string($_POST['Preacher'])."', 
                    Date = '".mysql_real_escape_string($_POST['Date'])."',
                    Service = '".mysql_real_escape_string($_POST['Service'])."',
                    File = '".mysql_real_escape_string($_POST['File'])."',
                    Description = '".mysql_real_escape_string($_POST['Description'])."'
                WHERE
                    id = '".mysql_real_escape_string($_GET['vid_id'])."'")
    or die(mysql_error());
    

    Without escaping your variables properly, you are making yourself vulnerable to SQL injection attacks.

    EDIT

    To simplify the above, you can do a few tricks:

    // Apply mysql_escape_string to every item in $_POST
    array_map('mysql_real_escape_string', $_POST);
    // Get rid of $_POST, $_POST['Title'] becomes $p_Title
    extract($_POST, EXTR_PREFIX_ALL, 'p_');
    
    // Use sprintf to build your query
    $query = sprintf("UPDATE
                    Videos
                SET
                    Title = '%s',
                    Preacher = '%s', 
                    Date = '%s',
                    Service = '%s',
                    File = '%s',
                    Description = '%s'
                WHERE
                    id = '%s'",
                $p_Title,
                $p_Preacher,
                $p_Service,
                $p_File,
                $p_Description,
                mysql_real_escape_string($_GET['vid_id']));
    
    mysql_query($query) or die(mysql_error());
    

    Note that mixing $_POST and $_GET variables is not encouraged. You should supply the update ID through an hidden input field in the form.

提交回复
热议问题