'PHP PDO using bindParam first argument without colon [duplicate]

check this please

  $user_id = (int)$_GET['user_id'];
  $sql = 'DELETE FROM users WHERE user_id=:user_id';
  $query = $db->prepare($sql);
  $query->bindParam('user_id',$user_id,PDO::PARAM_STR);

  $delete = $query->execute();

actually it is wokring prperly and it deletes the user row from database

but the question here is that i didn't write ':' that column in the bind query i mean

this should be wrong

$query->bindParam('user_id',$user_id,PDO::PARAM_STR);

this should be correct

$query->bindParam(':user_id',$user_id,PDO::PARAM_STR);

but it doesn't throw any exception and the user row is being deleted successfully

any explaination about this ?



Solution 1:[1]

This post explains why the use of the colon is needed.

Is the leading colon for parameter names passed to PDOStatement::bindParam() optional?

From the post:

No, since the documentation doesn't mention this I think it's safe to assume that this behaviour isn't officially supported and shouldn't be relied upon.

However, it does actually happen to work (in PHP 5.3.24 at least) - internally a colon will be added to the parameter if it's missing (see ext/pdo/pdo_stmt.c:363 in the PHP 5.3.24 source code).

Solution 2:[2]

Old thread I know but I just came across this information in the PHP Documentation for PDO (https://www.php.net/manual/en/pdostatement.execute.php)

In the examples, it shows two ways to bind a value to a parameter, either with a colon or without it.

It even explicitly states that they are optional:

/* Names can be prefixed with colons ":" too (optional) */

From testing on PHP 7.4.28 I can confirm that using with or without a colon works when using ->bindValue and when passing an associative array directly into ->execute(...)

I'm not sure if this has always been there or when it was added, but as of now it seems that either way is fine.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 Rylee