开发者

array issues with php and SQL querys

Hey guys, I'm using smarty and php I am trying to make this function work

                {foreach $rows as $row}
            <input type="checkbox" name="likes[]" value="{$row.ID}">{$row.Interests}<br>
            {/foreach}

That there is the html/template for checkboxes, it grabs data from a table in my database

Now I am trying to store data into my database

     // $likes = mysql_escape_string($likes);

      $connection = mysql_open();
      $insert = "insert into Users " . 
          "values (null, '$fi开发者_Go百科rstName', '$lastName', '$UserName', '$email', from_unixtime('$DOB'), '$join', '$gender')";


      $result = @ mysql_query ($insert, $connection)
            or showerror();
        $id = mysql_insert_id();
        //echo $id; testing what it gets.
          mysql_close($connection);

      $connection = mysql_open();
      foreach($likes as $like)
      {

      $insert3 = "insert into ProfileInterests " .
        "values ('$id', '$like', null)";
      $result3 = @ mysql_query ($insert3, $connection)
        or showerror();

      }
      mysql_close($connection)
        or showerror();
    }

That there is the script I am using to enter data into my database...there is more above which is just cleaning the user input really. mysql_open() is my own function, so don't worry too much about that.

    $likes = @$_POST['likes'];

that is what I am using to get the likes....I feel that this is wrong. I am not sure what to do....

I get this error at the moment. Invalid argument supplied for foreach() I think this is completely to do with the variable $likes, I think it's not being treated like an array...any idea on what I should do.. I am quite a newbie.


The following line :

$likes = join(",",$likes);

is transforming your $likes array to a $likes string, containing the values and separating them by commas.

So, later, when you try to loop over $likes, its no longer an array : it's a string -- which explains the Invalid argument supplied for foreach().


Edit after the comment : when calling the following line :

$likes = mysql_escape_string($likes);

If your $likes is an array, you'll get some trouble, as mysql_escape_string works on a string.

Instead of trying to escape the whole array at once, you should use mysql_escape_string on each item, while looping over the array -- a bit like that :

foreach($likes as $like)
{
    // escape the current item :
    $escaped_like = mysql_real_escape_string($like);

    $insert3 = "insert into ProfileInterests values ('$id', '$escaped_like', null)";
    $result3 = @ mysql_query ($insert3, $connection) or showerror();
}


As a sidenote : you should use var_dump() on your variables, while developing, to see what they contain ;-) It'll help you understand what your code is doing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜