Greanny Santos
Greanny Santos

Reputation: 9

MySQL SUBSTR() function

I want to compare $images, $uploads but the outputs have different names:

$images = '/fiscalapplications/uploads/Image_00314_20200122.pdf';  
$uploads = 'Image_00314_20200122.pdf';

How do I do SUBSTR for the $images to = Image_00314_20200122.pdf

<?php
//pulling images from mysql colum1
require_once 'database_connection.php';
$result = mysqli_query($conn,"SELECT check_pic_path FROM checklog");


$images = []; // store a list of images from the database

while ($row = mysqli_fetch_array($result)) {
    $images[] = $row['check_pic_path'] . "<br>";
}

//pulling pictures from specific path
$dir = "fiscalapplications/uploads";

$uploads = []; // store a list of files on disk

if(is_dir($dir)) {
    while (($file = readdir($dh)) !== false) {
        $uploads[] = $file . "<br>";
    }
}
}

//attempting to compare $image to $upload
$compare = array_diff($images, $uploads);
print_r($compare);

Upvotes: 0

Views: 67

Answers (4)

OO7
OO7

Reputation: 690

In PHP:

$images = $images ?: '';
$uploads = substr($images, ($pos = strrpos($images, '/')) ? $pos : 0);

In MySQL:

if( ifnull( locate( '/', check_pic_path ), 0 ) > 0, substring_index( check_pic_path, '/', -1 ), check_pic_path )

Upvotes: 0

Jin Thakur
Jin Thakur

Reputation: 2773

$uploadsnew = substr($images , strrpos($images , '/') + 1); strrpos gets the position of the last occurrence of the slash; substr returns everything after that position.

if there is no slash this doesn't work correctly since strrpos returns false. Here's a more robust version:

$pos = strrpos($url, '/'); $uploadsnew = $pos === false ? $url : substr($images , $pos + 1);

Upvotes: 0

Akina
Akina

Reputation: 42622

In MySQL it may be

SUBSTRINT_INDEX(tablename.imagefield, '/', -1)

Upvotes: 0

Barmar
Barmar

Reputation: 780889

Use basename() to remove the directory from a pathname:

$images[] = basename($row['check_pic_path']) . "<br>";

Upvotes: 2

Related Questions