php - Right way to escape string after replacing quotes?

30

Is this the right way to escape a string just in case or I can insert string like this without additional escaping?

$filenamefordb = preg_replace('/[^A-Za-z0-9а-яА-Я_\.\-]/u', '', $filenamefordb);
$query = "INSERT INTO file SET filename='$filenamefordb";

I don't use mysqli_escape because I also need name without any quotes in another place

582

Answer

Solution:

Why don't you escape the string using PDO?

<?php
    $conn = new PDO('sqlite:/home/lynn/music.sql3');

    /* Complex string */
    $string = "Co'mpl''ex \"st'\"ring";
    print "Unquoted string: $string\n";
    print "Quoted string: " . $conn->quote($string) . "\n";
?>

This will output

Unquoted string: Co'mpl''ex "st'"ring
Quoted string: 'Co''mpl''''ex "st''"ring'

Reference: http://php.net/manual/it/pdo.quote.php

633

Answer

Solution:

you can escape it with a generic php function:

$filenamefordb = mysql_escape_string ($filenamefordb);
$query = "INSERT INTO file SET filename='$filenamefordb";

People are also looking for solutions to the problem: php - Unable to retrieve json data on server side via ajax call

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.