0

I am having trouble inserting data into my database. This is my first time dealing with SQL injection.

$stmt = $dbConnection->prepare('INSERT INTO users(name) VALUES('name = ?')');
$stmt->bind_param('s', $name);

$stmt->execute();

But that doesn't work. Any help would be appriciated!

0

2 Answers 2

3

You have a few syntax errors in your code. Try this:

$stmt = $dbConnection->prepare('INSERT INTO users (name) VALUES (:s)');
$stmt->bindParam(':s', $name);
$stmt->execute();

If you want to insert and define more values, do it like this:

$stmt = $dbConnection->prepare('INSERT INTO users (name, email) VALUES (:s, :email)');
$stmt->bindParam(':s', $name);
$stmt->bindParam(':email', $email);
$stmt->execute();

If you're using mysqli, your code will look like this:

$stmt = $dbConnection->prepare('INSERT INTO users (name) VALUES (?)');
$stmt->bind_param('s', $name);
$stmt->execute();
Sign up to request clarification or add additional context in comments.

9 Comments

That works! But if I want to add more, should I do (:s,:s,:s) ?
@J.Doe Nope, I'll add an example in my post, hang on :)
Oh, it's like that! Thank you very much!
@J.Doe No problemo! :)
The code in the question is using mysqli, not PDO. How can this answer work?
|
2

You don't need name = in the SQL, the column name is specified in the list (name) after the table name. Just put a ? where you would normally put the value.

$stmt = $dbConnection->prepare('INSERT INTO users(name) VALUES(?)');
$stmt->bind_param('s', $name);
$stmt->execute();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.