The databases related to PDO usage are as follows: CREATE & nbsp; TABLE & nbsp; 'session '& nbsp; (& nbsp; 'skey' & nbsp; char (32) & nbsp; CHARACTER & nbsp; SET & nbsp; ascii & nbsp; NOT & nbsp; NULL, & nbsp; 'data' & nbsp; text & ask questions about PDO usage
The related databases are as follows:
CREATE TABLE `session` (
`skey` char(32) CHARACTER SET ascii NOT NULL,
`data` text COLLATE utf8mb4_bin,
`expire` int(11) NOT NULL,
PRIMARY KEY (`skey`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
The related PHP code is roughly as follows (I have hidden some irrelevant code ):
define('DNS', 'mysql:host=localhost;dbname=db;charset=utf8mb4');
define('USR', 'usr');
define('PWD', 'pwd');
define('MAXLIFETIME', 1440);
function write($id, $data) {
try {
$dbh = new PDO(DNS, USR, PWD, array(
PDO::ATTR_PERSISTENT => TRUE,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => FALSE
));
try {
$expire = time() + MAXLIFETIME;
$sql = 'INSERT INTO `session` (`skey`, `data`, `expire`) '
. 'VALUES (:skey, :data, :expire) '
. 'ON DUPLICATE KEY UPDATE '
. '`data` = :data, `expire` = :expire';
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':skey', $id, PDO::PARAM_STR);
$stmt->bindValue(':data', $data, PDO::PARAM_STR);
$stmt->bindValue(':expire', $expire, PDO::PARAM_INT);
$stmt->execute();
$dbh = NULL;
} catch (Exception $e) {
echo $e->getTraceAsString();
}
} catch (Exception $e) {
echo $e->getTraceAsString();
}
}
write('12345678', '87654321');
The key here seems to be
PDO::ATTR_PERSISTENT => TRUE,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
.
Only comment out the two sentences and run OK. if any of the two statements takes effect, an exception occurs.
What is the situation? Please advise.
------ Solution --------------------
Is the data inserted? the exception information is printed out, and the nested try in try does not seem to be written in this way.
------ Solution --------------------
Your SQL command requires five parameters, but you only gave three!
Echo $ e-> getTraceAsString ();
Change
Echo $ e-> getMessage ();
You can see:
Error! : SQLSTATE [HY093]: Invalid parameter number
PDO: ATTR_ERRMODE => PDO: ERRMODE_EXCEPTION,
Enable exception handling mode
Comment out is the default error handling mode, and the error information can be obtained through errorInfo
PDO: ATTR_PERSISTENT => TRUE,
Enable persistent connection
An exception is thrown only when the connection is reused.