0

When I use (') in texts I get an error

How can I use mysqli_real_escape_string(); for this codes?

QUERY FAILED:You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near


<?php

                    if(isset($_POST["add_post"])){
                        $post_title = $_POST["post_title"];
                        $post_category = $_POST["post_category"];
                        $post_tags = $_POST["post_tags"];
                        $post_text = $_POST["post_text"];
                        $post_date = date("d/m/y");

                        $post_image = $_FILES["post_image"]["name"];
                        $post_image_temp = $_FILES["post_image"]["tmp_name"];

                        move_uploaded_file($post_image_temp, "../images/$post_image");

                        $query = "INSERT INTO posts (post_title, post_category, post_text, post_tags, post_date, post_image)";

                        $query .= "VALUES('$post_title', '$post_category', '$post_text', '$post_tags', now(), '$post_image')";

                        $create_post_query = mysqli_query($conn, $query) ;

                        if(!$create_post_query) {
                            die("QUERY FAILED:" .mysqli_error($conn));
                        } else {

                        header("Location: posts.php");

                    }
                    }

                    ?>

  • Possible duplicate of [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – user3783243 Jun 09 '19 at 14:10
  • You shouldn't use `mysqli_real_escape_string`. Parameterize the query and use a prepared statement. See the dup. – user3783243 Jun 09 '19 at 14:29

1 Answers1

1

You put raw values from POST. Do not do this. There are at least two reasons:

  1. Some of values may contains ' symbol which leads to sql syntax error. You should escape all values concatenating in sql query.
  2. This approach leads to sql injection (a kind of hacking).

I would recommend to use PDO instead or at least mysql-real-escape-string function

heximal
  • 10,327
  • 5
  • 46
  • 69