0

I am trying to select data from mySQL database,
I execute the following code:

 <?php $_SESSION["dog_park"] = $_GET['keyword'] ?>              

                <div class="review"> <!-- Creating a div with the class 'review -->


                <!-- but POST varibale in here for dog park name -->
                    <h1><?php echo $_SESSION["dog_park"]; ?></h1>




<table border="1" cellspacing="5" cellpadding="5" width="100%">
    <thead>
        <tr>
            <th>Park Name</th>
            <th>Street</th>
            <th>Suburb</th>
            <th>Dog Park Area (m2)</th>
        </tr>
    </thead>
    <tbody>
    <?php

        $result = $conn->prepare("SELECT * FROM dog_parks.items where suburb = '$_SESSION[dog_park]'");
        $result->execute();
        for($i=0; $row = $result->fetch(); $i++){
    ?>
        <tr>
            <td><label><?php echo $row['Park_Name']; ?></label></td>
            <td><label><?php echo $row['Street']; ?></label></td>
            <td><label><?php echo $row['Suburb']; ?></label></td>
            <td><label><?php echo $row['Dog_Park_Area_(m2)']; ?></label></td>

        </tr>
        <?php } ?>
    </tbody>
</table>

When that script executes it displays the following error:
Error Message

It has something to do with the session variable, if i enter a static value for the mySQL query it will display table data correctly, but fail when the $_SESSION variable is present.

chris85
  • 23,846
  • 7
  • 34
  • 51

1 Answers1

0

That string contains quotes, that breaks your SQL string encapsulation. Use the prepared statements as they are meant to be, parameterized, and the issue will be gone.

$result = $conn->prepare("SELECT * FROM dog_parks.items where suburb = ?");
$result->execute(array($_SESSION[dog_park]));

You can read more:

http://php.net/manual/en/pdo.prepared-statements.php
How can I prevent SQL injection in PHP?

As is your query was running as:

SELECT * FROM dog_parks.items where suburb = ''Tramway''

(roughly, if you'd included text of error message, not image I could supply real query)

Which is invalid because '' is what you are comparing. The Tramway'' it doesn't know what to do with. This coincidentally is how SQL injections occur.

Community
  • 1
  • 1
chris85
  • 23,846
  • 7
  • 34
  • 51
  • Error message was fixed, thanks. Had to add quotes around $_SESSION['dog_park'] No table data being displayed, any ideas?? –  May 12 '16 at 14:55
  • You read my whole answer? The `'dog_park'` wasn't the main point of my answer.. If `suburb` doesn't equal your exact string you will get no records, does your record have quotes in it? – chris85 May 12 '16 at 14:56
  • @deluxenathan so the issue is resolved? – chris85 May 12 '16 at 15:07
  • Not quite i'm having other issues with sessions, but not related to the post. All good. –  May 12 '16 at 15:35
  • Okay, if this resolved the issue please mark answer as such. – chris85 May 12 '16 at 15:37