Jump to content

Dumb question..In a URL SQL query, why do you need to "bind the conditions?"


Recommended Posts

I'm working on a project where the user inputs a URL like these:

http://localhost/project/read.php?user=user&secretkey=pass&table=customer&order=age&conditions=age%20BETWEEN%20%270%27%20AND%20%2760%27

http://localhost/project/read.php?user=user&secretkey=pass&table=customer&order=age&limit=0,3&conditions=customer_name%20LIKE%20%27J%%27%20AND%20customer_name%20IN%20(%27Joe%27,%27Bob%27)

in the browser window and JSON of the SQL query results is displayed on a .php page.

Our instructor gave us the following code "that will help binding the conditions:"

$revised_conditions = str_replace("%20"," ",$clean_conditions);
$revised_conditions = preg_replace("!'%?[a-zA-Z0-9]+%?'!","?",$revised_conditions);
$conditions_array = preg_match_all("!'(%?[a-zA-Z0-9]+%?)'!", $clean_conditions, $condition_matches, PREG_PATTERN_ORDER);

... and ...

if ($clean_conditions != False) {
    $types = ""; 
    foreach ($condition_matches[1] as $c) {
        if (preg_match("![0-9\.]+!",$c)) {
            $types .= "d";
        } else {
        $types .= "s"; 
        }   
        }   
        $stmt->bind_param($types, ...$condition_matches[1]);
}

Can someone tell me what "binding the conditions" means? I believe it means putting each condition from the URL into a variable. How does the above code do that? How would I implement this code to make it functional?

Edited by wad11656

Your instructor is an idiot. That code has no business being given to anyone learning PHP. Try not to learn too much from it.

The principle behind binding parameters is that you write the overall structure of the query without any data inside it, then tell MySQL that certain locations within it (like those marked with ?s) correspond to certain values (the bound parameters). The idea is that you can't accidentally confuse syntax with data.

Problem with this code is that it isn't so much "accidentally confusing syntax with data" as it is intentionally confusing syntax with data. Which is terrible, and why you should try to ignore it as much as possible and focus on the basic concepts of prepared statements.

  • Like 1
  • Haha 1
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.