0

I hate PHP, but I have to do this. I have spent the last 2 days searching for a simple way to write a SQL Select with a LIKE clause where the parameter is passed from the lname input text on the form. Now, it has to be SQL Server, NOT MYSQL

So here is what I've done so far.

    function getActorDetailsLnameOnly($lname) {
    // the SQL query to be executed on the database

    $query = "select NameFirst, NameLast, Age, Gender from actor where NameLast like '%$lname%'";

    return executeQuery($query);
}

on the index.php, I wrote the following:

if ((!empty($_REQUEST['lname'])) and ( empty($_REQUEST['age']) and ( empty($_REQUEST['gender'])))) {

        $lname = (string) $_GET['lname'];

        $sql = getActorDetailsLnameOnly($lname);
        foreach ($sql as ...) {
            extract(...);
           ...

The code returns a value, but it's nowhere near correct. It's like requesting A in the select statement and it's returning Z. I can't figure it out.

urfusion
  • 5,528
  • 5
  • 50
  • 87
RazorSharp
  • 179
  • 1
  • 3
  • 15
  • 1
    Post your test cases. – Samir Selia Mar 01 '16 at 05:14
  • Did you write `executeQuery`? Mysql and sqlserver in this instance will have the same syntax; depending on the driver you are using. We also need to know what you are querying and what is being returned. – chris85 Mar 01 '16 at 05:21
  • I'm querying a SQL Server using PDO and I'm trying to return every value in the table where the last name like %whatever% I enter into the Last Name: – RazorSharp Mar 01 '16 at 05:37
  • Also, yes, I am calling the executeQuery in the dbconn php file. – RazorSharp Mar 01 '16 at 05:43

1 Answers1

2

You check form input values through $_REQUEST['lname'] and then assign a variable $lname = (string) $_GET['lname'];. If form method is POST then $_REQUEST['lname'] would have the value and $_GET['lname'] would be empty. As the result like pattern would be '%%', which is effectively everything but NULL.

Basically, $_GET is for GET, $_POST is for POST and $_REQUEST is for any.

Try using $lname = (string) $_REQUEST['lname'];.

Y.B.
  • 3,526
  • 14
  • 24
  • Using your reply gave me a good idea. When I applied your suggestion, I also changed my SQL query. Now, it works like a charm! The New Query is:: $query = "SELECT NameFirst, NameLast, Age, Gender FROM Actor WHERE NameLast like '%{$_POST['lname']}%'"; – RazorSharp Mar 01 '16 at 17:14
  • @dot3tech Glad that helped. Please do sanitize input though [How to escape strings in SQL Server using PHP?](http://stackoverflow.com/questions/574805/how-to-escape-strings-in-sql-server-using-php) – Y.B. Mar 01 '16 at 17:21