开发者

PHP Mysql multiple insert with foreach not working

Here is my code - I'm attempting to attach a bunch of user_id 's to a piece of content.

if (empty($errors)) // If everything's OK.
{ 
    foreach($_POST['userId'] as $row)
    {
        $query = " ('".$row[learner_id]."', '".$postId."', '".$id."' ),";
    }

    $query = substr_replace($query,"",-1);
    $mysql_return = m开发者_如何学JAVAysqli_query("INSERT INTO subs (userId, postId, account_id ) VALUES ".$query) or die(mysql_error());
}

Would love any help you could give - it's not working...


And how's it not working? Syntax error? Silently puking? You're not escaping your POST data, so if any of those contain at least one single quote, that'll cause a syntax error right there, plus leaving you wide open for sql injection attacks.

Or maybe a foreign key check is failing... many possibilities, but you haven't given us nearly enough info to tell. What error message(s) are you getting?


Ok, I see several issues:

  1. You are not using parameters or escaping, opening yourself up WIDE to sql injection attacks. See mysqli_real_escape_string.

  2. What are you possibly sending to $_POST['userId'] that would make itself an array?

  3. Unless learner_id is a constant, then this is a syntax error. If it is an array key, put it in quotes.

  4. Where are $postId and $id coming from ?


The first parameter to mysqli_query is the identifier returned by mysqli_connect, whereas you're just giving it the query directly.

It should be like this,

$link = mysqli_connect("host", "user", "pass", "db");
$mysql_return = mysqli_query($link, "INSERT INTO subs (userId, postId, ac...
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜