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, '$firstName', '$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 :
is transforming your
$likesarray to a$likesstring, 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 :
If your
$likesis an array, you’ll get some trouble, asmysql_escape_stringworks on a string.Instead of trying to escape the whole array at once, you should use
mysql_escape_stringon each item, while looping over the array — a bit like that :As a sidenote : you should use [**`var_dump()`**][1] on your variables, while developing, to see what they contain 😉 It’ll help you understand what your code is doing.