Mysqli prepared statements to multiple databases
I'm working on an import feature from one database to another and thought I'd try out the built in Mysqli features.
I have opened two connections, one for each database, and am looping through the old one (to get the existing users) and running checks on the new one before choosing whether or not to insert the data.
Now I'm not sure if I'm misusing the prepared statements feature or what as I am having trouble getting the correct results. A simple test case is:
$oldDB = new Mysqli(HOST, USER, PASS, 'oldDB'); $newDB = new Mysqli(HOST, USER, PASS, 'newDB'); /* * Prepared statments */ $searchUserStmt = $newDB->prepare('SELECT user_id FROM members WHERE user_id=?'); $searchUserStmt->bind_param('i', $old_user_id); $searchUserStmt->bind_result($user_id); /** * Loop through users */ $result = $oldDB->query('SELECT * FROM member_profile LIMIT 10'); while($row = $result->fetch_assoc()) { var_dump($row['user_id']); // Check if 开发者_Python百科user is already in DB $old_user_id = $row['user_id']; $searchUserStmt->execute(); $searchUserStmt->fetch(); $searchUserStmt->reset(); var_dump($user_id); }
My first query on $oldDB
runs fine and loops through the users however when I look up the user_id
in the $newDB
with the prepared statement it only returns the user_id
of the first result.
Here's a sample of the output I get:
string(1) "1" int(1) string(2) "31" int(1) string(2) "26" int(1) string(3) "105" int(1) string(2) "34" int(1) string(3) "119" int(1) string(2) "36" int(1) string(2) "37" int(1) string(2) "38" int(1) string(2) "39" int(1)
Does anyone have any idea what I'm doing wrong? I've been through the Mysqli docs but didn't find anything that helped me.
Ok I found the problem, things were working correctly however it appears that the variable used in mysqli_stmt::bind_result()
doesn't get updated unless there is a row found. In my tests only the first user was found which resulted in the 1 being returned everytime.
mysqli_stmt::fetch()
will return NULL
when no results are found so I simply had to modify my code slightly like so:
while($row = $result->fetch_assoc()) { var_dump($row['user_id']); // Check if user is already in DB $old_user_id = $row['user_id']; $searchUserStmt->execute(); if($searchUserStmt->fetch() === NULL) { // Insert user here } $searchUserStmt->reset(); }
精彩评论