emiel popelier
emiel popelier

Reputation: 5

ajax & PDO variable as condition for WHERE

So i wanted to make a little "search engine" for my database. my javascript is:

 $(document).ready(function () {
     $("#display").click(function () {
         var zoeknaam = $("#zoeknaam").val();
         var zoektype = $("#zoektype").text();
         $.ajax({    //create an ajax request to load_page.php
             type: "POST",
             url: "display.php",
             data: { name: zoeknaam, zoekt: "name" },
             dataType: "html",   //expect html to be returned                
             success: function (response) {
                 $("#responsecontainer").html(response);
                 //alert(response);
             }

         });
     });
 });

my html is the following:

<input type="text" name="inputtext" id="zoeknaam" />
<select name="searchtype" id="zoektype"><option value="name">name</option><option value="age">age</option></select>
<input type="button" id="display" value="Display All Data" />

and now i have my php

include("connection.php");
$dataget = $_POST["name"];
$datawaar = $_POST["zoekt"];
$stmt = $conn->prepare("SELECT * FROM student WHERE :waar=:postname");
$stmt->bindParam(':waar', $datawaar, PDO::PARAM_STR);
$stmt->bindParam(':postname', $dataget, PDO::PARAM_STR);
$stmt->execute();
echo "<table>";
while($data = $stmt->fetch(PDO::FETCH_ASSOC))
{   
    echo "<tr>";
    echo "<td align=center>$data[name]</td>";
    echo "<td align=center>$data[address]</td>";
    echo "<td align=center>$data[age]</td>";
    echo "</tr>";
}
echo "</table>";

When i remove the where condition and set the condition to name it works. Now when i retrieve it with the post and param it doesn't work. The connection.php is correct since it works with the condition.

Upvotes: 0

Views: 39

Answers (1)

jeroen
jeroen

Reputation: 91762

This is wrong:

... WHERE :waar=:postname

You can only bind values using placeholders in a prepared statement, not column- or table names.

If you want to accept and use client-provided column- or table names, the only way to secure that, is to check them against a white-list and then inject them directly in the query string.

Upvotes: 2

Related Questions