How to check if a variable is a MYSQL query? It needs to exclude sql injection. I tried to write regular expressions, but it's veeeery hard. I think, that checking it would be easier.


If you want to prevent any SQL injection occurring your best option would be to use Prepared Statements. This removes the need to check the content of the variable to detect with it contains any SQL.

For example:

$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);

// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";

$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";

in the bind_param function, the first parameter sets the type of data. s for string and i for int. Then specify the variables you would like to add.

Then all you need to do is change the variables value and call the execute function.

See this link for more details: https://www.w3schools.com/php/php_mysql_prepared_statements.asp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.