I haven't had to do Php in about 5years and I'm having some trouble doing the simplest task.

I use Javascript to send some parameters from a querystring to my page and so some may be 'undefined'

I want to build a mySQL query based on these parameters, therefore need to skip those that are 'undefined'

I can't seem to get this to work properly..any help would be appreciated.

    $WhereClause = "";  

     if (isset($_REQUEST['lname']) && $_REQUEST['lname'] === 'undefined')        
        {
            $WhereClause .= " surname like \"%$lname%\"";
        }           


    $query = "SELECT * from foo

            " . $WhereClause . "

            LIMIT $start, $pagesize";

Dani AI

Generated

A few practical points to add to the thread: the literal string "undefined" usually comes from the client side (as observed), the SQL builder must include a WHERE only when there are conditions (as noted), and the immediate symptom here was a missing assignment (as later found). Beyond those fixes, follow a small set of robust practices so the same problem does not reappear.

Normalize and classify input as soon as it arrives. Treat missing, empty or the literal string "undefined" as “no value” and convert to a single canonical form (null). For example, use server-side filtering and trimming, then test case-insensitively for the undesired literal before deciding to add a condition.

$lname = trim((string) filter_input(INPUT_GET, 'lname'));
if ($lname === '' || strcasecmp($lname, 'undefined') === 0) {
    $lname = null; // treat as not provided
}

Build SQL with parameter binding for any user text, and validate numeric paging values before inserting them into the query. Keep text parameters in prepared placeholders and cast/clamp start/pagesize to integers so the LIMIT clause remains safe.

$start = max(0, (int) ($_GET['start'] ?? 0));
$pagesize = max(1, min(200, (int) ($_GET['pagesize'] ?? 25)));
$sql = 'SELECT ... FROM MAIN /* joins omitted here */';
$params = [];
if ($lname !== null) {
    $sql .= ' WHERE surname LIKE :lname';
    $params[':lname'] = "%$lname%";
}
$sql .= " LIMIT $start, $pagesize";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);

On the client side, avoid sending literal "undefined" by only appending parameters that actually exist and by encoding values. Quick checklist: (1) prevent sending undefined from JS; (2) normalize input server-side; (3) use prepared statements for text and validate numeric inputs; (4) log raw incoming params when debugging. These steps address the immediate bug and remove common security and correctness issues.

Recommended Answers

All 4 Replies

undefined is Javascript, not PHP. You maybe thinking of null but isset takes care of that check. What you could do is combine trim and empty.

Two main problems stand out to me right away:

  1. Your if statement is only true if lname contains the value undefined (curious why you'd store "undefined" in a variable?).
  2. You're missing the actual "WHERE" keyword.

If $_REQUEST['lname'] contains undefined, your SQL query will look like this:

SELECT * from foo surname like \"%$lname%\ LIMIT $start, $pagesize

To fix, A) change line 1 to:

$WhereClause = "WHERE";

B), change line 3 to:

if (isset($_REQUEST['lname']) && $_REQUEST['lname'] !== 'undefined')

Please allow me to be much more specific...i'm using a Jquery Datagrid (jqGrid) to display my data. Its loaded via json and so i'm using Javascript to receive the querystring paramenters from my form and pass them onto my data.php

This might not be the most elegant way to do this, I've just started working on it last night.

index.php

        $(document).ready(function () {

        var qs = getQueryStrings();
        var lname = '?lname=' + qs["lname"]; 
        var myURL = 'data.php' + lname

         });


        function getQueryStrings() { 
          var assoc  = {};
          var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
          var queryString = location.search.substring(1); 
          var keyValues = queryString.split('&'); 

          for(var i in keyValues) { 
            var key = keyValues[i].split('=');
            if (key.length > 1) {
              assoc[decode(key[0])] = decode(key[1]);
            }
          } 

          return assoc; 
        } 

data.php

    $WhereClause = " WHERE ";   

    if (isset($_REQUEST['lname']) && $_REQUEST['lname'] !== 'undefined')
        {
            $WhereClause .= " surname like \"%$lname%\"";
        }   

    $query = "SELECT MAIN.*, Regiment.*, UnitText1.* , Country.* , Cemetary.*

                        FROM MAIN

                            INNER JOIN Regiment ON MAIN.regiment_ID = Regiment.ID

                            INNER JOIN Cemetary ON MAIN.Cemetary_ID = Cemetary.ID

                            INNER JOIN Country ON MAIN.Country_ID = Country.ID

                            INNER JOIN UnitText1 ON MAIN.UnitText1_ID = UnitText1.ID 

                            " . $WhereClause . "

                            LIMIT $start, $pagesize";       

Well, like i said it's beena while, but I managed to sort my issue

i was forgetting to SET to variable

duh!

$lname = $_GET['lname'];
$WhereClause = " WHERE ";   

    if (isset($_REQUEST['lname']) && $_REQUEST['lname'] !== 'undefined')
        {
            $WhereClause .= " surname like \"%$lname%\"";
        }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.