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

How to query certain values from a column in a database?

I am trying to do a query on a database. One of the columns on the database is 'category'. I would like to query every message from the database except a certain category. How would I go about this?

Antonio De Rose
Antonio De Rose
20,885 Points
/*say for example if you have categories - car, van, plane, train, trucks
and if you do not want trucks*/

select *
from category
where category != "trucks"

How would that look on the PHP side?

1 Answer

Antonio De Rose
Antonio De Rose
20,885 Points
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT id, type, vehicle FROM Categories where category != 'trucks'"
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - Type: " . $row["type"]. " " . $row["vehicle"]. "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();
?>