duddosai duddosai - 5 months ago 11
PHP Question

Attachment is not working when the file name has ' in it in mysql

I'm creating a page where I have the option for attaching files. When the files have single quotes in their names is attached, I get an error. This is how I tried:

$id = intval(mysqli_real_escape_string($mysqli, $_REQUEST["id"]));
$upload_directory = "uploads/attachments/";
$result = file_upload("attachment", "../".$upload_directory);
if($result[status] == true) {
$query = "insert into `attachments`
(
`id`,
`file_name`,
`file_extension`,
`file_size`,
`uploaded_file_name`,
`uploaded_file_path`
)
values
(
'$id',
'".$result[file_name]."',
'".$result[file_extension]."',
'".$result[file_size]."',
'".$result[uploaded_file_name]."',
'".$upload_directory.$result[uploaded_file_name]."'
)";


This is the error I got:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '2016.xlsx'
'xlsx',
'7988',
'1466056157029.xlsx',
'upload' at line 15


I know this is the place where the problem is: '".$result[file_name]."'. The problem is because of the single quote I've used. What is the change I should do? What should I add?

Answer

Add single quotes. You are using ' in filename so use addslashes() and when fetching use stripslashes(). OR remove ' from filename. See below code

$query = "insert into `attachments` 
        (
            `id`, 
            `file_name`, 
            `file_extension`, 
            `file_size`, 
            `uploaded_file_name`, 
            `uploaded_file_path`
        ) 
        values 
        (
            '$id', 
            '".addslashes($result['file_name'])."', 
            '".$result['file_extension']."', 
            '".$result['file_size']."', 
            '".$result['uploaded_file_name']."', 
            '".$upload_directory.$result['uploaded_file_name']."'
        )";