Jump to content

MYSQLi - Filtering results


merkont

Recommended Posts

Hey,

 

Wrote I quick script to filter results from database.

It kinda works but not sure if this is best or even secure way to do it.

I know mysqli has function 'bind_params', but failed to make it work.

<form action="" method="get">
<input type="checkbox" name="data" value="3" />
<input type="submit" />

<?php
if( empty($_GET['data']) ) {
die("GET empty"); }

$mysqli = new mysqli('localhost', 'user', 'password', 'database');
$statement = "SELECT * FROM table1 WHERE id=" . $_GET['data'];

$result = $mysqli->query($statement);
while( $row = $result->fetch_assoc() ) {
        echo $row['id'];
        echo "<br/>";
        echo $row['text'];
        if ($row['img'] !=  NULL)
        echo "<img src=" . $row['img'] . " > ";
}

?>

So just basic checkbox interface, when selected one of checkboxes and submitted, script queries database with matching ID from GET, returns results and loops through them.

Inside loop checks for associated image src, if not present ignores field.

 

I want to use this fucntions logic in my project but not sure if secure nor best/easiest way to do this.

Obviously will improve interface, naming of variables etc.

Link to comment
Share on other sites

EDIT:

 

NEVER put user entered data into a query (unless you are using prepared statements). In this case you can use intval() on the value

$id = intval($_GET['data']);
$statement = "SELECT * FROM table1 WHERE id={$id}";

As to your issue, MySQL does not return NULL for a NULL field. Just check if the value is not empty. Plus, there are no quotes around the value

 

 

if (!empty($row['img']))
{
    echo "<img src=\"{$row['img']}\">";
}
Edited by Psycho
Link to comment
Share on other sites

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.