How can I use the “excapesinglequotes” function in my code to prevent SQL injection attacks?

149    Asked by CrownyHasegawa in Salesforce , Asked on May 22, 2024

I am a developer and I am currently working on a particular web-based application that allows users to submit their review for the product. The reviews are stored in a database, and I am responsible for implementing the functionality for properly handling the input of the users. How can I use the “excapesinglequotes” function in my code to prevent SQL injection attacks when storing user reviews in the database? 

Answered by Csaba Toth

 In the context of Salesforce, you can prevent SQL injection attacks during the time of when storing the review of the users in a database by using the “escapesinglequotes” function or its equivalent in your programming language.


 Here Is the example given in PHP:-

// Establishing a database connection (replace with your actual database credentials)

$servername = “localhost”;
$username = “username”;
$password = “password”;
$dbname = “mydatabase”;
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
If ($conn->connect_error) {
    Die(“Connection failed: “ . $conn->connect_error);
}
// Function to escape single quotes in user input
Function escapesinglequotes($input) {
    Global $conn;
    Return $conn->real_escape_string($input);
}
// Handling form submission
If ($_SERVER[“REQUEST_METHOD”] == “POST”) {
    $userReview = $_POST[‘review’];
    // Sanitize and escape user input
    $sanitizedReview = htmlspecialchars($userReview); // Sanitize HTML tags
    $escapedReview = escapesinglequotes($sanitizedReview);
    // Prepare and execute SQL statement
    $stmt = $conn->prepare(“INSERT INTO reviews (review_text) VALUES (?)”);
    $stmt->bind_param(“s”, $escapedReview);
    If ($stmt->execute()) {
        $message = “Review submitted successfully!”;
    } else {
        $message = “Error submitting review.”;
    }
}

?>




    <meta</span> charset=”UTF-8”>

    <meta</span> name=”viewport” content=”width=device-width, initial-scale=1.0”>

    Submit Review



    Submit Review

    $message

”; } ?>

   

”>

        Your Review:

       

       

   




// Close the database connection

$conn->close();

?>

Here is the example given in java programming language:-

Import java.sql.Connection;
Import java.sql.DriverManager;
Import java.sql.PreparedStatement;
Import java.sql.SQLException;
Public class ReviewSubmission {
    // JDBC database URL, username, and password (replace with your actual database credentials)
    Private static final String DB_URL = “jdbc:mysql://localhost:3306/mydatabase”;
    Private static final String USER = “username”;
    Private static final String PASS = “password”;
    Public static void main(String[] args) {
        // Establishing a database connection
        Try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS)) {
            // Function to escape single quotes in user input
            String escapedReview = escapesinglequotes(“User’s review with ‘single quotes’”);
            // Prepare and execute SQL statement to insert review
            String sql = “INSERT INTO reviews (review_text) VALUES (?)”;
            Try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                Pstmt.setString(1, escapedReview);
                Int rowsAffected = pstmt.executeUpdate();
                If (rowsAffected > 0) {
                    System.out.println(“Review submitted successfully!”);
                } else {
                    System.out.println(“Error submitting review.”);
                }
            } catch (SQLException ex) {
                System.out.println(“SQL error: “ + ex.getMessage());
            }        } catch (SQLException ex) {            System.out.println(“Connection failed: “ + ex.getMessage());
        }
    }    // Function to escape single quotes in user input
    Private static String escapesinglequotes(String input) {
        Return input.replace(“’”, “’’”);
    }
}

Here is the example given in python programming language:-

  Import pymysql

# Database connection parameters (replace with your actual database credentials)

Host = “localhost”
User = “username”
Password = “password”
Database = “mydatabase”
# Function to escape single quotes in user input
Def escapesinglequotes(input_text):
    Return input_text.replace(“’”, “’’”)

Try:

    # Establishing a database connection
    Connection = pymysql.connect(host=host, user=user, password=password, database=database)
    # Create a cursor object
    Cursor = connection.cursor()
    # User input (replace with your actual user input handling)
    User_review = “User’s review with ‘single quotes’”
    # Escape single quotes in user input
    Escaped_review = escapesinglequotes(user_review)
    # SQL statement to insert escaped review into database
    Sql = “INSERT INTO reviews (review_text) VALUES (%s)”
    # Execute the SQL statement with the escaped review
    Cursor.execute(sql, (escaped_review,))
    # Commit changes to the database
    Connection.commit()
    Print(“Review submitted successfully!”)
Except pymysql.Error as e:
    Print(“Error:”, e)

Finally:

    # Close cursor and database connection
    If cursor:
        Cursor.close()
    If connection:
        Connection.close()

Your Answer

Interviews

Parent Categories