0

So I just wanted to insert a new record to database using by below query:

INSERT INTO ratings VALUES(\'\','".$userid."','".$rating."','".$itemid."')

I also tried it with parameters but that didn't work either.

This is the query printed to console:

INSERT INTO ratings VALUES('','13','3.5','5228')"

The Php Code is this:

$query = "INSERT INTO ratings VALUES(\'\','".$userid."','".$rating."','".$itemid."')";
echo '<script>console.log("'.$query.'");</script>';
DB::query($query);

And the function to execute the query:

public static function query($query, $params = array()) {
    $statement = self::connect()->prepare($query);
    $statement->execute($params);

    if (explode(' ', $query)[0] == 'SELECT') {
        $data = $statement->fetchAll();
        return $data;
    }
}

And the Error that i get is following:

Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation:
    1064 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 '\'\','13','4','5228')'
at line 1 in D:\xampp\htdocs\updatedcollector\classes\DB.php:12
4
  • 2
    This is missing a lot of information. What was the php code? What's the error output? Commented Dec 28, 2020 at 19:46
  • Are you getting any errors? Try error_reporting(E_ALL); (place that on the top of your PHP script) and check your MySQL error logs. Also, show more code. Commented Dec 28, 2020 at 19:46
  • Im only get the Syntax-Error but i checked everything and i cant find any syntax error Commented Dec 28, 2020 at 19:50
  • 1
    You're in a double-quoted string, so you don't need to escape your single quotes. If you echo your query, you'll probably see the slashes still there. Commented Dec 28, 2020 at 19:57

1 Answer 1

2

Given this function:

public static function query($query, $params = array()) {
    $statement = self::connect()->prepare($query);
    $statement->execute($params);

    if (explode(' ', $query)[0] == 'SELECT') {
        $data = $statement->fetchAll();
        return $data;
    }
}

It seems like what you want to do is this:

$query = "INSERT INTO ratings VALUES('', ?, ?, ?)";
DB::query($query, [$userid, $rating, $itemid]);

This provides you with protection against SQL injection attacks.

Sign up to request clarification or add additional context in comments.

3 Comments

yes, but i've done it in the other way like hundreds of times already why does it fail so suddenly? but anyway thanks
Well don't do it the other way. It's unsafe and guaranteed to break.
Also, if the first column of ratings is an auto-increment, that empty string should more properly be a NULL.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.