-1

I've a search page in php and I've already stored many terms in database. Suppose i input

Helloworld

on the search form. I want to find the last

2 characters (Ld)  in the database table.

I've already tried mb_functions and other alternatives too but nothing worked. I'm badly stuck with this.

Mehreen
  • 85
  • 7
  • See http://php.net/manual/en/function.substr.php. Specifically `If start is negative, the returned string will start at the start'th character from the end of string.` – chris85 Dec 28 '15 at 20:28
  • You could grab the last 2 characters using JavaScript, and pass those characters to your SELECT query. – durbnpoisn Dec 28 '15 at 20:28
  • 3
    Possible duplicate of [Getting last 5 char of string with mysql query](http://stackoverflow.com/questions/10134609/getting-last-5-char-of-string-with-mysql-query) or http://stackoverflow.com/questions/10542310/how-can-i-get-the-last-7-characters-of-a-php-string – chris85 Dec 28 '15 at 20:31

1 Answers1

0

I dont know exactly what you need, but this will search for last 2 characters of a string and find a column value in your table that matches it, and then echo it. Also make a check to see if string is longer than 2.

$string = 'helloworld';
$newstring = substr($string, -2);

// Connect to database
try {
    $db = new PDO('mysql:host=localhost;dbname=DATABASE_NAME', 'root', 'password123');
} catch (PDOException $e) {
    echo $e->getMessage()."<br>";
    die();
}

// Search for the $newstring in a table
$sql = $db->prepare("SELECT * FROM table_name WHERE column = :newstring");
$query = $sql->execute(array(
    ":newstring" => $newstring
    )
);

foreach ($sql as $row) {
    $dbstring = $row['column_name'];
    echo $dbstring . '<br>';
}