Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sample PHP Code (MySQLi insert query) to prevent SQL injection
<?php
/* Use mysql parameterized statements rather than simple mysql query to prevent sql injection */
// Connect to MySQLi - Change DB_HOST, DB_USER, DB_PASS, DB_NAME with appropriate values
$mysqli = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME) or DIE ('Could not connect to the database:' . mysqli_connect_error());
mysqli_set_charset($mysqli, 'utf-8');
// Change field1 and so on with database fields.
$stmt = $dbc->prepare("INSERT INTO database_name (field1, field2, field3, field4, field5)
VALUES (?, ?, ?, ?, ?)");
// s = string, i = integer, d = double
// Change 'string_value_1' and so on to it's appropriate values
$stmt->bind_param("sssid", 'string_value_1', 'string_value_2', 'string_value_3', integer_value, double_value);
// Execute the query
$stmt->execute();
// Close the prepared statement
$stmt->close();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment