Reputation: 15
I have a MySQL Database setup like so:
id | username
-------------
1 | name1
2 | name2
3 | name3
But when I use this code in PHP, it only reads the first name. NOTE: I need it to read just the names. The id is there for something else.
$sql = mysql_query("SELECT `username` FROM `black_list`");
$blacklist = array();
while($row = mysql_fetch_array($sql))
{
$blacklist[] = $row;
if(!in_array($name,$blacklist))
{
//User not protected
} else {
echo "User Protected";
}
}
If anyone could help me, that would be great. Thanks :)
Upvotes: 1
Views: 141
Reputation: 2306
I think you want to compare if $name
is in the blacklist array. For that you have to first build your blacklist array and then compare $name
to it. In your code it is just comparing name to the current contents of the $blacklist
array and not the whole array.
If you are iterating 1st row it will add value of the first row of the resultset to the $blacklist
and compare $name
just with that one element. When it goes to second row it adds the value of the second row in the resultset to the array thus this time it will compare $name
to two elements in array(the first two rows in resultset). Also it will check $name
in $blacklist
for each iteration in the resultset. I don't think you want this. So we first build an array of blacklist and then just compare it once.
//building the $blacklist array
while($row = mysql_fetch_array($sql)){
$blacklist[] = $row['username'];
}
//Comparing $name with all elements of $blacklist which is now a full list
if(!in_array($name,$blacklist)){
echo "Coming Soon";
}else{
echo "User Protected";
}
Upvotes: 1
Reputation: 11467
You could do this:
if (!in_array($name, mysql_fetch_array($sql))) {
echo "Coming Soon";
} else {
echo "User Protected";
}
But you should actually be doing it at the database level. This takes advantage of database optimizations and doesn't need one to load an entire table into memory.
$query = mysql_query(sprintf(
'SELECT 1 FROM `skype_bl` WHERE `username`="%s"',
mysql_real_escape_string($name)
));
if (mysql_num_rows($query)) {
// Username not available
}
Upvotes: 1
Reputation: 30488
use this
while($row = mysql_fetch_array($sql))
{
$blacklist[] = $row['username'];
}
if(!in_array($name,$blacklist))
{
echo "Coming Soon";
} else {
echo "User Protected";
}
Upvotes: 1