• I’m trying to add a function that will simply track my visitors IP.

    If the IP exists then it add’s one to the table, if it doesn’t then it adds it.

    However it’s not working and i can’t figure out where i’m going wrong.

    $result = $wpdb->query("SELECT * FROM wp_hits WHERE ip = '$visitor_ip'");
    
    	if (mysql_num_rows($result)  > 0) { 
    
        	$row = mysql_fetch_row($result);
        	$count = $row[2];
    
        	$plus_one = $count + 1;
    
        	$wpdb->query("UPDATE wp_hits SET hits = '$plus_one' WHERE id = '$visitor_ip'");
    
        } else {
    
    	    $wpdb->query("INSERT INTO wp_hits (ip, hits) VALUES ('$visitor_ip', 1)");
    
    	}

    to my knowledge this is:
    – querying the databased and checking for an IP
    – if row exists it should be greater than 1, if not it should be 0?
    – does exist: grab current number and add one then updaye
    – doesn’t exist: insert into db

    however it’s returning the error:

    Warning: mysql_num_rows() expects parameter 1 to be resource, object given in…

    it proceeds to skip to the else statement and adds the ip to the db, even if it does exist.

    Why isn’t it working?

Viewing 2 replies - 1 through 2 (of 2 total)
  • You’re close, but this hsould be re-written a little bit. I wouldn’t use $wpdb->query() for your query as you want ot return the values, and that doesn’t do it, you need $wpdb->get_results() for that.

    $result = $wpdb->get_results ("SELECT id FROM wp_hits WHERE ip = '".$visitor_ip."'");
    
    if (count ($result) > 0) {
    	$row = current ($result);
    	$wpdb->query ("UPDATE wp_hits SET hits = ".($row->wp_hits + 1)." WHERE id = '".$visitor_ip."'");
    } else {
    	$wpdb->query ("INSERT INTO wp_hits (ip, hits) VALUES ('".$visitor_ip."', 1)");
    }
    Thread Starter forcerdj

    (@forcerdj)

    Its working now many thanks ??

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘[php] tracking visitors, check if row exists..’ is closed to new replies.