文本表单不能接受撇号

时间:2015-12-04 04:35:57

标签: php mysql mysqli

我的文字表单不允许单个" ' "发生在输入字段中。我得到一个SQL语法错误。有没有什么好方法允许在我的文本字段中允许单撇号?

这是我的代码

HTML       

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

我的数据库

  // 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);
    ?>

任何帮助都将非常感激。谢谢!

3 个答案:

答案 0 :(得分:4)

使用addslashes PHP函数(使用斜杠引用字符串)

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

示例:

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

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

您还可以使用mysqli_real_escape_string(在SQL语句中使用字符串中的特殊字符转义,并考虑连接的当前字符集)

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

答案 1 :(得分:2)

使用预处理语句,这比SQL-Injections更安全,而不仅仅是转义。

改变这个:

$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);
}

对此:

$stmt = $conn->prepare("INSERT INTO whatsgood(`one` , `two`) VALUES ( ? , ? )");

$stmt->bind_param("ss", $one , $two);

if($stmt->execute()){
echo "New record created successfully";
}
else{
echo "Error: " . $stmt->error;
}

答案 2 :(得分:0)

mysqli_real_escape_string期间使用INSERT来转义值。

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