I have the following lines of code to retrieve records from a database:
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname; charset=utf8;", $username, $password);
$sql = $dbh->prepare("SELECT * FROM usa WHERE code = :code AND window1 = :oldrepeat AND spare <> :americinn AND url IS NOT NULL ORDER BY user ASC");
$sql->execute(array(':code' => $code, ':oldrepeat' => $oldrepeat, ':americinn' =>$americinn));
/*** fetch the results ***/
$result = $sql->fetch();
Amongst other criteria, this query is supposed to return records that only have some content in the field called url
, but this is not happening. It is returning records that also have an empty url
field.
I assume that I am doing something fundamentally wrong but cannot see what it is.
Can anyone shed some light please?
Best wishes
Well, write your query in following way:
SELECT * FROM usa WHERE code = :code AND window1 = :oldrepeat AND spare <> :americinn AND !ISNULL(url) ORDER BY user ASC
ISNULL
is an inbuilt MySQL function that checks if value of a column is null. By using !
(negation), you will get only required rows.
In case if a column has blank value, you can try url!=''
.