Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Victor Bielski
Victor Bielski
2,325 Points

Search field - PHP & MySQL

Hello,

I'm currently working on a search field, but I'm having some troubles and I can't quite figure out, what the problem is. At the moment, users are able to upload documents like .pdf and .docx. And then the documents get stored in a table called "files" in my database.

The "files" table contains following:

ID name title forfatter (author) size downloads (for later user)

Search.php contains following:

<div class="container">
    <div class="row">
        <div class="col-12">
            <form action="" method="post">
                <input type="text" class="form-control" name="search" placeholder="Search">
                <button type="submit" name="submit-search"></button>
            </form>
        </div>
    </div>
</div>

<div class="container"> <div class="row"> <div class="col-12"> <?php if (isset($_POST['submit-search'])) { $search = $_POST['search']; $sql = "SELECT * FROM files WHERE name LIKE '%".$search."%'"; $query = mysqli_query($conn, $sql);

                if (mysqli_num_rows($query)) {
                    echo "Sorry, no results!";
                } else {
                    while ($fetch = mysqli_fetch_assoc($query)) {
                        $id = $fetch['id'];
                        $name = $fetch['name'];

                        echo $id. " - " .$name."< /br>";
                    }
                }
            }
        ?>
    </div>
</div>

</div>

If anyone knows what I'm doing wrong, help me out :)

1 Answer

Victor Bielski
Victor Bielski
2,325 Points

if (isset($_POST['submit-search'])) { $search = $_POST['search']; $sql = "SELECT * FROM files WHERE name LIKE '%".$search."%'"; $query = mysqli_query($conn, $sql);

                if (mysqli_num_rows($query)) {
                    echo "Sorry, no results!";
                } else {
                    while ($fetch = mysqli_fetch_assoc($query)) {
                        $id = $fetch['id'];
                        $name = $fetch['name'];

                        echo $id. " - " .$name."< /br>";
                    }
                }
            }