VB Coder VB Coder - 1 year ago 65
MySQL Question

No slashes stored in mysql table

this is a simplified version of my code. What I'm trying to achive is that I want to insert the image path into a DB table. I used the constant DIRECTORY_SEPERATOR and I am also using PDO.

$tmp = $_FILES['file1']['tmp_name'];
$name = $_FILES['file1']['name'];
$path = getcwd() . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $name;

$success = move_uploaded_file($tmp, $path);

$query = "INSERT INTO phptbl (Name, Photo) VALUES ('name', '$path')";
echo 'Something went wrong!';

Data will be inserted into the table without directory separation.

Please advise

Answer Source

If the DIRECTORY_SEPERATOR is \ on your system, you're creating a string with backslashes. Backslashes are an escape character in many languages, including SQL. The database will interpret \ as a meta character. To correctly store any and all arbitrary values, you need to either escape the value correctly (to \\) or, better, prepare and bind the query:

$stmt = $db->prepare("INSERT INTO phptbl (Name, Photo) VALUES ('name', ?)";

This will correctly preserve special characters as is without them getting interpreted.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download