1

I have just changed a script to use

$query=$database->query (INSERT...)

but I also have several if statements that add to the query if the number of input fields generated from the previous page is higher than expected.

The original query is as follows...

$query=$database->query("INSERT INTO pool_" . $pool_name . " (team_name) VALUES('$team_one'),     ('$team_two'), ('$team_three'), ('$team_four'), ('$team_five'),
('$team_six'), ('$team_seven'), ('$team_eight')");

I understand the error I am getting, I just don't know how to avoid it.

The error is Catchable fatal error: Object of class PDOStatement could not be converted to string in D:\newXamp\htdocs\real_do_create_pool.php on line 32

the line of code is...

$query.=", ('$team_nine'), ('$team_ten'), ('$team_eleven')";

How can I add to the query whilst using $database->query

Thanks

3
  • Shouldn't it be VALUES('$team_one', '$team_two', '$team_three') and so on? Commented Jan 15, 2014 at 0:17
  • well when i was using mysql_query, mysql_result etc, the deprecated methods, I just added to $query like I have shown above, however, since changing to $query=$database->query, it won't work. I could type them all in again but hoped there was a shortcut Commented Jan 15, 2014 at 0:20
  • Wait, I took a stab at the answer, but now I'm not sure; what is your table structure? Commented Jan 15, 2014 at 0:21

1 Answer 1

2

Don't call $database->query until it's all baked:

$queryString = "INSERT INTO pool_" . $pool_name . " (team_name) VALUES('$team_one'),     ('$team_two'), ('$team_three'), ('$team_four'), ('$team_five'),
('$team_six'), ('$team_seven'), ('$team_eight')";

Then as necessary you can:

$queryString .=", ('$team_nine'), ('$team_ten'), ('$team_eleven')";

and then finally

$query=$database->query($queryString);

Edit: Or even better, use the magic that is PDO prepared statements

$stmt = $dbh->prepare("INSERT INTO pool_" . $pool_name . " (team_name) VALUES (:team_name)");
$stmt->bindParam(':team_name', $team_name);
$stmt->execute();

Got some more to insert?

$team_name = $team_nine;
$stmt->execute();
$team_name = $team_ten;
$stmt->execute();

etc

Sign up to request clarification or add additional context in comments.

2 Comments

Now with bonus PDO option!
Just want to mention, that you should always use prepared statements when dealing with user input. Otherwise you might have SQL Injection on your hands.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.