Search code examples
phpsqlsql-like

Change (title LIKE 'A%') to B or C, etc (rewrite)


This is a rewrite of a question that was closed because it was too vague and I hadn't inserted the code correctly. Hopefully this makes more sense.

I have a large SQL database containing 'title' and 'author'. I've set up a query using PHP that will select only titles beginning with A - (title LIKE 'A%') - on one page:

$result = mysql_query("SELECT * FROM table WHERE (title LIKE 'A%') ORDER BY title ASC");

//fetch the data from the database
while ($row = mysql_fetch_array($result)) {
$DirPath = $row{'filename'};
//To get the innermost dir 'display just mp3'
$InnermostDir = basename(rtrim($DirPath, '/'));

echo "<tr><td align='justify'>";
echo $row{'title'} ;
echo "</td><td align='center'>";
echo $row{'author'} ;
echo "</td><td align='center'>";
echo $row{'publisher'} ;
echo "</td><td align='center'>";
echo $row{'pages'} ;
echo "</td><td align='center'>";
echo $row{'year'} ;
echo "</td><td align='center'>";
echo $row{'type'} ;
echo "</td><td align='center'>";
echo $row{'genre'} ;
echo "</td><td align='center'>";
echo $row{'location'} ;
echo "</td><td align='center'>";
echo $row{'id'} ;
echo "</td><td align='center'>";
echo $row{'shortauthor'} ;
echo "</td></tr>";
}
?>
</table>
<?php
//close the connection
mysql_close($dbhandle);
?>

http://sanctuary-westminster.org/library/epa.php

At the moment I've simply copied the page 25 time, where the only difference is that the letter changes (and the page title changes to reflect the letter), and then just use a simple a href="epb.php" to join them together. So on the epb.php page:

$result = mysql_query("SELECT * FROM table WHERE (title LIKE 'B%') ORDER BY title ASC");

http://sanctuary-westminster.org/library/epb.php

This is a very long winded and unattractive approach, any changes require changing all the pages. I've tried using $letter instead of the link and have LIKE 'A%' be LIKE '$letter%' instead:

$result = mysql_query("SELECT * FROM table WHERE (title LIKE 'row{'letter'}%') ORDER BY title ASC");

But that fails; it doesn't give any error messages, the query is not happening as the input value is not correct, so nothing is being returned. Hopefully that makes better sense and apologies for before.

(I've also looked at ways of using a dropdown menu where the "Submit" command stores the letter chosen from the options and then it's used in the query, but when ever I look dropdown menus and SQL the only examples seem to relate to populating a menu with a table, not creating a query using one. Not sure if that would work better)


Solution

  • Have one page, titled lib.php and pass it an argument, like lib.php?letter=A

    Change your code to:

    $result = mysql_query("SELECT * FROM table WHERE (title LIKE '" . mysql_real_escape_string($_GET['letter']) . "%') ORDER BY title ASC");
    

    Now the same file, lib.php, can generate all the pages from before.