0

I am making a simple thing to use my php knowledge and learn it and its working so far but i run into a problem when ever the string has ' in it. I get why it's doing it and i know there are ways to do it but i can't find a specific answer to this question.

<?php
if (isset($_POST['submit'])){
    $title = $_POST['title'];
    $text = $_POST['text'];
    $connection = mysqli_connect('localhost','root','','blog');
    if (strpos($text,"\'") !== false){
        str_replace("\'","\'",$text);
    }
    $query = "INSERT INTO `posts`(`title`, `text`) VALUES ('".$title."', '".$text."')";
    $result = mysqli_query($connection,$query);
    if (!$result){
        die("error" . mysqli_error($connection));
    } else {
        header("Location:http://localhost/blog-testing/");
        die();
    }
}

How can i make it automatically find ' and fix it so it doesn't mess up the string?

  • Use parameters. Don't munge queries with literal values. – Gordon Linoff Mar 01 '20 at 17:00
  • 1
    you should use **prepared** statements** to prevent **sql jection++ Please read up on https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – nbk Mar 01 '20 at 17:06
  • 2
    If you use a Prepared and bound parameterised query, you will NEVER have to worry about quotes in the data ever again – RiggsFolly Mar 01 '20 at 17:12

1 Answers1

1

If you use a bound query, it automatically protects you against quotes in the data and against SQL Injection Attack.

<?php
$connection = mysqli_connect('localhost', 'root', '', 'blog_test');
if ($connection){
    echo "connection success";
} else {
    echo "connection failure";
}

$query ="INSERT INTO `text-test` (`title`, `content`) VALUES (?,?)";

$stmt = $connection->prepare($query);
$stmt->bind_param('ss',$_POST['title'], $_POST['text']);
$result = $stmt->execute();

if (!$result){
    //die("Query failed" . mysqli_error());
    //Dont die(), report an error into a log file
} else {
    header( "Location: http://localhost/blog-testing/");
    exit;
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149