How to escape quotes when inserting into database with PHP

前端 未结 4 566
闹比i
闹比i 2021-01-12 07:22

I\'m quite new to PHP so sorry if sounds such an easy problem... :)

I\'m having an error message when inserting content which contains quotes into my db. here\'s wha

相关标签:
4条回答
  • 2021-01-12 07:26

    Your code

    $sql="INSERT INTO articles (title, body, date) VALUES ('$title','$body','$nowdate'),";
    

    should be as follows

    $sql="INSERT INTO articles (title, body, date) VALUES ('$title','$body','$nowdate')";
    

    comma should not be there at the end of query

    0 讨论(0)
  • 2021-01-12 07:32

    With any database query, especially inserts from a web based application, you should really be using parameters. See here for PHP help on how to use parameters in your queries: PHP parameters

    This will help to prevent SQL injection attacks as well as prevent you from having to escape characters.

    0 讨论(0)
  • 2021-01-12 07:33

    it should work without the sprintf stuff

    $title = mysql_real_escape_string($_POST[title]);
    $body = mysql_real_escape_string($_POST[body]);
    
    0 讨论(0)
  • 2021-01-12 07:48

    Please start using prepared parameterized statements. They remove the need for any SQL escaping woes and close the SQL injection loophole that string-concatenated SQL statements leave open. Plus they are much more pleasing to work with and much faster when used in a loop.

    $con  = new mysqli("localhost", "u", "p", "test");
    if (mysqli_connect_errno()) die(mysqli_connect_error());
    
    $sql  = "INSERT INTO articles (title, body, date) VALUES (?, ?, NOW())";
    $stmt = $con->prepare($sql);
    $ok   = $stmt->bind_param("ss", $_POST[title], $_POST[body]);
    
    if ($ok && $stmt->execute())
      header('Location: index.php');
    else
      die('Error: '.$con->error);
    
    0 讨论(0)
提交回复
热议问题