I need to save the user agent of a visiting user.
This is my snippet:
// User Agent
$ua = $_SERVER['HTTP_USER_AGENT']??'';
$ua_md5 = md5($ua);
// Search if the UA already exists in the user_agents table
$ua_id = $db->query("SELECT id FROM user_agents WHERE md5='".$ua_md5."';")->fetchColumn();
if(!$ua_id) {
// If it doesn't exist, insert it and get its id
$db->query("INSERT INTO user_agents (md5, user_agent) VALUES ('$ua_md5', ".$db->quote($ua).")");
$ua_id = $db->lastInsertId();
}
I use PDO:quote instead of prepared statements only for performance reasons (it's faster and this script runs thousands of times per second).
It happens that some users has this user agent:
Mozilla/5.0 (Linux; Android 5.0; \xD6wn Smart Build/LRX21M) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/37.0.0.0 Mobile Safari/537.36
And the insert fails for this error:
"PHP message: SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xD6wn Sm...' for column 'user_agent' at row 1" while reading response header from upstream
What is the reason and how can it be fixed?
Edit: more debugging found out the $ua
value is:
Mozilla/5.0 (Linux; Android 5.0; ÖWN S1 Build/LRX21M) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/37.0.0.0 Mobile Safari/537.36
var_dump
of the query you're trying to execute with the supposedly quoted value. – deceze