Jump to content

[SOLVED] Php SQL IF help..


E3pO

Recommended Posts

Hello! Thanks for the fast reply on my last question.. Very helpful!

 

What I need help on now is how to add an if statement to my insert code so that it only inserts if the ip is nowhere in the database..

 

For instance, in a super omfg easy form.. if ip is != anything in database then insert, otherwise do nothing at all.

<?php
   function newview($ip){
      $q = "INSERT INTO iplist (ip) VALUES ('$ip')";
  $result = mysql_query($q, $this->connection);
      return $result;
   }
?>

Link to comment
https://forums.phpfreaks.com/topic/157765-solved-php-sql-if-help/
Share on other sites

You can try to select that ip and if the query returns and results (> 0) then it exists and return false, if not, proceed with the insertion:

 

function newview($ip){
   $q2 = "SELECT ip FROM iplist WHERE ip = '$ip'";
   $result = mysql_query($q2);
   if(mysql_num_rows($result) > 0)
   {
      return false;
   }
   else
   {
      $q = "INSERT INTO iplist (ip) VALUES ('$ip')";
      $result = mysql_query($q, $this->connection);
      return $result;
   }
}
?>

 

BYW, what datatype are you storing IP's in the database as?

BYW, what datatype are you storing IP's in the database as?

 

char(15)

utf8_bin

 

Also, not sure if it made a difference but i added the , $this->connection to the end of the query.

<?php
$q2 = "SELECT ip FROM iplist WHERE ip = '$ip'";
$result = mysql_query($q2, $this->connection);
?>

 

Final working code, thank you very much :)

 

<?php
function newview($ip){
//Code help from PHPFreaks.com
//Special Thanks to Maq for super fast help and reply!
   $q2 = "SELECT ip FROM iplist WHERE ip = '$ip'";
   $result = mysql_query($q2, $this->connection);
   if(mysql_num_rows($result) > 0)
   {
      return false;
   }
   else
   {
      $q = "INSERT INTO iplist (ip) VALUES ('$ip')";
      $result = mysql_query($q, $this->connection);
      return $result;
   }
}
      function views(){
      if($this->views3 < 0){
         $q = "SELECT id FROM iplist";
         $result = mysql_query($q, $this->connection);
         $this->views3 = mysql_numrows($result);
      }
      return($this->views3);
   }
?>

 

SQL CODE:

 

CREATE TABLE IF NOT EXISTS `iplist` (
  `id` int(11) NOT NULL auto_increment,
  `ip` char(15) character set utf8 collate utf8_bin NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.