I have the following two prepared statements addressing the same database table (they follow directly upon each other) and I wonder if it's possible to combine/merge these in one statement. (the connection data are defined in $conn1
, session_id
is the primary key of that table)
if($p1 = $conn1->prepare("INSERT INTO data1 (session_id) VALUES (?) ON DUPLICATE KEY UPDATE current_time = ?")) {
$p1->bind_param("ss", $sessionid, $current_time);
$p1->execute();
$p1->close();
}
if($p2 = $conn1->prepare("SELECT xxx1, xxx2, xxx3 FROM data1 WHERE session_id = ?")) {
$p2->bind_param("s", $sessionid);
$p2->execute();
$p2->bind_result($xxx1, $xxx2, $xxx3);
$p2->fetch();
}
In plain words: When a new session is initialized, I want the session ID to be saved in the data1
table. If the session ID already exists, I want the current_time
value to be updated and some other values (xxx1, xxx2, xxx3
) to be fetched from data1
.
The way I wrote it above it works, but I'd prefer to have only one query. From what I read it might be possible if it were only a simple INSERT
followed by a SELECT
, but not with the ON DUPLICATE KEY UPDATE
involved. But I'd be happy to learn that it can be done in one query...