how to retreive and change data (noob)

Discussion in 'MySQL' started by ycc, Mar 31, 2010.

  1. #1
    I want to make a simple visit-counter for my site. The plan is this:

    Make a simple mysql database table containing two variables:
    1. IP number
    2. number of vists (for each IP)

    The program would quite simply use the current users ip (IP) to do this:

    if (IP is not in database)
    make a new entry with IP number and number of visits = 1
    else (IP is already in database)
    bump corresponding number of visits by one;

    Simple enough!

    I just want to verify that I have understood mysql.
    Are these the simplest and most suited commands to obtain the following:
    
    // Check if IP is in database:
    $query = mysql_query("SELECT * FROM my_table WHERE ip=$_SERVER['REMOTE_ADDR']");
    $number=mysql_num_rows($query);
    if ($number == 0) echo "IP not in database";
    
    
    // Bump corresponding IP
    $query = mysql_query("SELECT * FROM my_table WHERE ip=$_SERVER['REMOTE_ADDR']");
    $row = mysql_fetch_array($query);
    $visits = $row['visits'];
    $visits++;
    $query = mysql_query("UPDATE my_table SET visits='$visits' WHERE ip=$_SERVER['REMOTE_ADDR']");
    
    Code (markup):
    I am just an old Cobolsaur (who didn't even know Cobol, but mostly assembler and C). ;) Just let me know if I got the hang of how to use mysql.

    I have a feeling I sometimes have used completely unnecessary iterating procedures to scan the database, using mysql-commands in this way is maybe better?

    ycc
     
    Last edited: Mar 31, 2010
    ycc, Mar 31, 2010 IP
  2. koko5

    koko5 Active Member

    Messages:
    394
    Likes Received:
    14
    Best Answers:
    1
    Trophy Points:
    70
    #2
    Hi,

    Please check this link!
    p.p.: and this also. Hope it's clear now and you can do it yourself via single line of code.

    Regards :)
     
    koko5, Mar 31, 2010 IP
  3. ycc

    ycc Peon

    Messages:
    99
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks a million koko5. You hit dead center.

    UPDATE my_table SET visits=visits+1 WHERE ip=$ip;
    Code (markup):
    seems to work directly. (without adding "unique") It reduces what I want to do from five lines to one

    The conversion between IP-numbers and integer in your second link is exactly what I should have done from the start. (I was just puzzling together some sorting routine for IP-number-strings - not efficient)

    I feel highly motivated for rewriting it all. (I just did it yesterday afternoon.)

    Blagadaryo vam. (My Russian of childhood (grandma came from there) is lost, but at least I go to Ukraine on holiday next week.) :)

    Thanks a lot, very helpful.
     
    ycc, Apr 2, 2010 IP