Connection to MySQL fails via PHP while command-line works fine
Found the answer in the MySQL manual, Pluggable Authentication:


  As of MySQL 5.5.7, the server authenticates clients using a plugin. Selection of the proper account row from the mysql.user table is based on the user name and client host, as before, but the server authenticates the client by determining from the account row which authentication plugin applies for the client.


The MySQL package creates a root user using the auth_socket authentication plugin, so only connections via a socket are permitted, and the username of the Linux account is checked as well.

The mysql command uses a socket by default, and runs as root in my script, so it was allowed to connect.

According to the PHP manual, a PDO MySQL connection to localhost also uses a socket; but PHP is run as an unprivileged user, so the connection is refused by the auth_socket plugin.

I fixed my script by adding this line:

mysql --user=root -e \
"UPDATE mysql.user SET plugin='mysql_native_password'; FLUSH PRIVILEGES";


And it now works fine.