Hi, I'm stuck trying to get data from Mysql to a php array(). I'm trying to do a script that bans IPs. At first my array was like this.. $ips = array('127.0.0.1', '127.0.0.2', '127.0.0.3'); //etc. PHP: and then the script will check it like this... $user_ip = $_SERVER['REMOTE_ADDR']; if(in_array($user_ip, $ips)) { die("Banned!"); } PHP: But now I have everything on a mysql table, so how do I check them? I had.. $sql_ban = "SELECT * FROM banned_users WHERE ip"; $result_ban = mysql_query($sql_ban) or die(mysql_error()); $row_ban = mysql_fetch_array($result_ban); $ban_ip = $row_ban["ip"]; $ban_username = $row_ban["username"]; PHP: and then I will just do.. $ips = array($ban_ip); PHP: But that only works with the first IP. I trying adding a while() but that only works with the last IP .. any help will be useful thank you in advance.
Why don't you use database for it's real purpose? $user_ip = $_SERVER['REMOTE_ADDR']; $sql_ban = "SELECT * FROM banned_users WHERE ip = '".$user_ip."'"; $result_ban = mysql_query($sql_ban) or die(mysql_error()); if($row_ban = mysql_fetch_array($result_ban)){ // this ip is banned die("your ip is banned"); } PHP:
Why don't you use PHP for it's real purpose? Also changed query to narrow returned data... $user_ip = $_SERVER['REMOTE_ADDR']; $sql_ban = "SELECT ip FROM banned_users WHERE ip = '".$user_ip."' LIMIT 1"; $result_ban = mysql_query($sql_ban) or die(mysql_error()); if(mysql_num_rows($result_ban)){ // this ip is banned die("your ip is banned"); } PHP:
I see this common mistake all the time and thought i should offer a correction. IP addresses saved in db's should ALWAYS be saved as numeric values reasons for this include but are not limited to better and more efficient indexing and faster operand comparisons. With that said assuming you have all your ip columns as integers, the below code is what you need. the INET_ATON() mysql function converts ip to numeric value and the INET_NTOA function allows you to go from numeric to ip address. $user_ip = $_SERVER['REMOTE_ADDR']; $sql_ban = "SELECT * FROM banned_users WHERE ip = INET_ATON('".$user_ip."')"; $result_ban = mysql_query($sql_ban) or die(mysql_error()); if(mysql_num_rows($result_ban) > 0){ // this ip is banned die("your ip is banned"); } Code (markup):