r/PHPhelp • • Oct 13 '19

INSERT INTO sql table not working.

Am I inserting rows into my table correctly? This doesn't work for some reason.

$conn->exec("INSERT INTO Questions_Table (ID, Question, Votes) VALUES ($num_rows, $submitted_question, 1)");
9 Upvotes

9 comments sorted by

2

u/PopeInnocentXIV Oct 13 '19

Are $num_rows and $submitted_question properly quoted and escaped?

1

u/[deleted] Oct 13 '19

$num_rows is an int and $submitted_question is a string, so I think they would be properly quoted

4

u/greg8872 Oct 13 '19

so if you do echo $submitted_question;

does it give back some value or does it give back "some value"?

To be honest, if it is something submitted, just use prepared statements to protect you for bad values being directly places in the query.

If I submitted a question that said (assuming you fix your quote issue) what color is the sky?",9999),(100,"Another Question? I may have now just submitted a two questions, and the first one I set the Votes to 999 for it.

1

u/PopeInnocentXIV Oct 13 '19

Echo out the statement and see if it looks correct.

Also get the error message from the database connection.

6

u/akas84 Oct 13 '19

You are missing quotes in the string and you should check how to bind params or you will have and sql injection on there.

2

u/Zinin2018 Oct 13 '19

Whats the difference betn using query or exec?

2

u/greg8872 Oct 13 '19

assuming this is for plain PDO, query() returns a PDO Statement Object (which you can loop through and process the records returned), where exec() just runs the query and returns how many rows were affected. So if you doing a query that does not return records and you are not using any data that needs protected (submitted by user), use exec()

0

u/brilliantmojo Oct 13 '19

Does your DB login have all privileges?