.

Text form can't accept apostrophes Text form can't accept apostrophes

Text form can't accept apostrophes


  CodingTips[Updated on:Sep-1-2021]    




My text forms won't allow single " ' " to occur in the input fields. I get an sql syntax error. Is there any good way to allow single apostrophes to be allowed in my text field?

here's my code

html

<input class='what' type='text' name='one' required>
    <textarea name='two' required></textarea>
    <input type='submit'>
    </form>

 

My database

 

  // Create connection
    $conn = mysqli_connect($servername, $username, $password, $dbname);
    // Check connection
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }

    $sql = "INSERT INTO whatsgood (one, two)
    VALUES ('$one', '$two')";

    if (mysqli_query($conn, $sql)) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . mysqli_error($conn);
    }

    mysqli_close($conn);
    ?>

 

Best Answer

Use addslashes PHP function (It Quote string with slashes)

$sql = "INSERT INTO whatsgood (one, two) VALUES ('".addslashes($one)."', '".addslashes($two)."')";

Example:

 

<?php
$str = "Is your name O'Reilly?";

// Outputs: Is your name O'Reilly?
echo addslashes($str);
?>

 


Like & Share

Leave a Comment


Login to post a public Comment

There are no comments yet. Comment to discuss