PHP/mySQL newb question

Discussion in 'PHP' started by RogerDodgr, Dec 17, 2009.

  1. #1
    I am trying to update 20 records in a mySql table. I want to use a for loop and update the 20 records by a 'key'.

    This code works. It updates *one record (I copied the PHP 'UPDATE' sytax from GoDaddy's 'Starfield' interface):
    
    mysql_connect("**.*.***.***",$username,$password) or die(mysql_error());
    mysql_select_db("*******") or die(mysql_error());
    $sql = 'UPDATE `*******`.`hot_topics` SET `phrase` = \'test45\' WHERE `hot_topics`.`key` = 2 LIMIT 1;'; 
    
    Code (markup):
    However, when I assign a value from a symbol ($i) to the variable 'key', it stops working. This is confusing me because:
    1) The key field is an int in the mySQL data base.
    2) I checked with an is_int function, and $i is in-fact an int.
    3) And, it works with the above code.

    This does not work (The only difference is changing the `key` = 1 ---> `key` = $i):
    
    mysql_connect("**.*.***.***",$username,$password) or die(mysql_error());
    mysql_select_db("*******") or die(mysql_error());
    $i = 2;
    $sql = 'UPDATE `*******`.`hot_topics` SET `phrase` = \'test45\' WHERE `hot_topics`.`key` = $i LIMIT 1;'; //changed 2 to $i
    
    Code (markup):
    Thanks.
     
    RogerDodgr, Dec 17, 2009 IP
  2. CoreyPeerFly

    CoreyPeerFly Notable Member Affiliate Manager

    Messages:
    394
    Likes Received:
    24
    Best Answers:
    5
    Trophy Points:
    240
    #2
    Try this:
    $sql = "UPDATE `*******`.`hot_topics` SET `phrase` = 'test45' WHERE `hot_topics`.`key` = '" . $i . "' LIMIT 1;";
    PHP:
     
    CoreyPeerFly, Dec 17, 2009 IP
  3. JAY6390

    JAY6390 Peon

    Messages:
    918
    Likes Received:
    31
    Best Answers:
    0
    Trophy Points:
    0
    #3
    It's because php only converts variables in strings when they're in double quotes. Use this
    $i = 2;
    $sql = "UPDATE `*******`.`hot_topics` SET `phrase` = 'test45' WHERE `hot_topics`.`key` = $i LIMIT 1";
    PHP:
     
    JAY6390, Dec 17, 2009 IP
  4. RogerDodgr

    RogerDodgr Well-Known Member

    Messages:
    267
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    105
    #4
    Thanks! Both of your solutions worked.
     
    RogerDodgr, Dec 17, 2009 IP
  5. leeann.william

    leeann.william Peon

    Messages:
    4
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    you can do this by adding the new column i.e auto increment column in the data base. This will help in selecting all the row value range for which you for loop will be work. and your job will be easy.
     
    leeann.william, Dec 17, 2009 IP