1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Help on a db query please.

Discussion in 'Databases' started by JEET, Jul 10, 2006.

  1. #1
    Hi,
    I am getting a value submitted from a form.

    $val= $_POST['field'];
    Then putting it in an array.
    $arr= explode("/", $val);

    Now I have to open a db and check if this value in that field already exists or not. if not, insert it.
    This is what I am not getting.

    mysql_connect(localhost,username,password);
    @mysql_select_db($database) or die( "Unable to select database");
    $query="SELECT * FROM $tablename WHERE field='$cat'";
    $result=mysql_query($query);
    $num=mysql_numrows($result);
    mysql_close();

    I know that I need to run a foreach loop to automatically check for each item in $arr but I am completely confused by the number of records in $num now.

    My question:
    What code needs to be put in FOREACH loop now.
    It has to check all records selected for the previous query with the current value in $arr.
    If a record with $arr value is found, do nothing or else insert a record.

    foreach ($arr as $value)
    {

    }

    Thank you for any help here.
     
    JEET, Jul 10, 2006 IP
  2. T0PS3O

    T0PS3O Feel Good PLC

    Messages:
    13,219
    Likes Received:
    777
    Best Answers:
    0
    Trophy Points:
    0
    #2
    
    foreach ($arr as $value)
    {
    $query="SELECT * FROM $tablename WHERE field='" . $value . "'";
    $result=mysql_query($query);
    $num=mysql_numrows($result);
    if ($num == 0) {
    //Insert
    }
    }
    
    PHP:
     
    T0PS3O, Jul 10, 2006 IP
  3. JEET

    JEET Notable Member

    Messages:
    3,825
    Likes Received:
    502
    Best Answers:
    19
    Trophy Points:
    265
    #3
    Hi,
    Thanks so much.
    It was easy just had to let go the pressure.
    Thanks again.
    Here's what I came up with. ( a little longer than what you gave but doesn't involve querying the db over and over)
    ----------------
    Code in first post here.

    foreach ($arr as $value)
    {

    $i=0;
    $c= "1";
    while ($i < $num) {
    $f = mysql_result($result,$i,"field");
    if ($f == $value)
    $c= "2";

    ++$i;
    }

    if ($c== "1")
    {
    INSERT here
    }
    }
    -----------------
    Bye
     
    JEET, Jul 10, 2006 IP