简体   繁体   中英

SQL request not returning anything when replacing a string by a variable

I'm trying to setup a simple function to update the path of subfolders when the main folder is renamed.

Here is my code :

case 'rename':

$dirpath = rtrim(preg_replace('~/+~', '/', (str_replace('\\', '/', $_POST['old-dirpath']))), '/');
$new_dirpath = rtrim(preg_replace('~/+~', '/', (str_replace('\\', '/', $_POST['new-dirpath']))), '/');

$sql = "
    UPDATE privatedir SET
    dirpath = '{$new_dirpath}'
    WHERE dirpath = '{$dirpath}'
    ";

    $db->execute($sql);


$rs = $db->query("SELECT * FROM privatedir WHERE `dirpath` LIKE '%.$dirpath.%'");

$folders = $db->fetchAll($rs);
print_r ($folders); print_r($dirpath); die;
foreach ($folders as $folder){
    echo $folder['dirpath']; die;
    $folder_new_dirpath = str_replace($dirpath, $new_dirpath, $folder['dirpath']);

    $sql = "
        UPDATE privatedir SET
        dirpath = '{$new_dirpath}'
        WHERE dirpath = '{$folder['dirpath']}'
        ";

        $db->execute($sql);
}

My problem concerns the line $rs = $db->query("SELECT * FROM privatedir WHERE dirpath LIKE '%.$dirpath.%'"); even though there are matching results in my database it won't return me anything, if I print_r $folders it just prints me an empty array.

However if I replace .$dirpath. by the string directly (for example C:/wamp/www/gg/ftp/repository/folder1 ) it will return me the matching results and print_r $folders will print me the corresponding arrays.

What am I doing wrong ?

像thi这样将变量放在引号中

    $rs = $db->query("SELECT * FROM privatedir WHERE `dirpath` LIKE '%'".$dirpath."'%'");

Thing is that you don't need the dots around, because you're not concatenating the string.

This should work:

$rs = $db->query("SELECT * FROM privatedir WHERE `dirpath` LIKE '%$dirpath%'");

You can also do

$rs = $db->query("SELECT * FROM privatedir WHERE `dirpath` LIKE '%".$dirpath."%'");

if you like it better.

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