J. Doe J. Doe - 7 months ago 26
PHP Question

Preventing SQL injection insert into

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!

Answer

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();
Comments