Hello! Is it appropriate to connect to the database using constants? Constants are defined, but in the code:

$pdo = new PDO("mysql:host=HOST; dbname=DB;charset=utf8", "USER", "PASS"); 

gives an error message

ERROR: SQLSTATE [HY000] [2005] Unknown MySQL server host 'HOST' (1)

  • @Torawhite, well, you did not specify the address of the server to which you are connecting. For most cases, mysql should be: host = localhost - sinedsem
  • @Dazar, an excellent answer, taking into account what I see right now:> mysql: host = HOST - etki

2 answers 2

php cannot interpol strings with constants. They simply do not physically differ from words, so it would be unclear what to do with words whose name coincides with the name of a constant.

  $dsn = sprintf('mysql:host=%s;dbname=%s;charset=utf8', HOST, DB); $pdo = new PDO($dsn, USER, PASS); 

Now I have one question: why do you even save this in constants?

  • @Etki in the training video was such an example. Is it better to just put them into variables? As I understand it, the author of the lesson works with constants, which are better suited, for the simple reason that they are permanent, probably. But his connection goes through mysql_connect. In general, I configure config.php - Torawhite
  • @Torawhite, well, it is advisable to throw them out of the config into the creation of a PDO with no traces in the global scope. - etki
  • @Etki, something for me is a dark forest. If possible, explain it in a simpler language, for a teapot, so to speak. - Torawhite
  • In the current version of @Torawhite, you will inherit absolutely unnecessary constants that will be visible to everyone, and any uploaded library that also uses USER will not be able to set it down and will fall. The constants must be truly immutable values ​​- the version of the program, the end-of-line character, while they must lie in the classes, so as not to litter the common scope. - etki

Catch:

 $pdo = new PDO('mysql:host='.HOST.'; dbname='.DB.';charset=utf8', USER, PASS); 
  • Try to write more detailed answers. Explain what is the basis of your statement? - Nicolas Chabanovsky