4

I'm using pdo and I have a query like this

$stmt=$db->query("SET @update_id := 0;  
                    UPDATE table SET column = something, id = (SELECT @update_id := id)  
                    WHERE condition  
                    LIMIT 1;   
                    SELECT @update_id;"); 

It is supposed to update a row and return the id.
I'm sure the query itself is working because I ran it in phpmyadmin and it returned a column named @updated_id with the value of the updated row like this:

|   @updated_id    |  
|------------------|   
|  *correct id*    | 

I want to fetch the value of @updated_id and store it in a php variable.
I tried $stmt->fetchColumn(); and $stmt->fetchColumn(); but I get SQLSTATE[HY000]: General error.
I've been searching for something to work but I can't find anything.
so anybody knows how to store the value of @updated_id in a php variable?
thanks

3
  • Execute your query in phpMyAdmin. What does it return? Additionally, should't it read like this: SET @update_id = 0; Commented Sep 3, 2012 at 20:51
  • @SteAp as I said it returns a column named @updated_id with the correct value beneath it. also I used the query from here stackoverflow.com/a/1751282/919944 and it seems it's correct because it's working in phpmyadmin. Commented Sep 3, 2012 at 21:00
  • 1
    Perhaps you need to look at multiple row sets: php.net/manual/en/pdostatement.nextrowset.php Commented Sep 3, 2012 at 21:29

2 Answers 2

3

As Petah suggested in the comments, you need to iterate through each rowset until you get to the SELECT statement you want to fetch.

Given you example above, this should work:

$stmt=$db->query("SET @update_id := 0;  
                UPDATE table SET column = something, id = (SELECT @update_id := id)  
                WHERE condition  
                LIMIT 1;   
                SELECT @update_id;"); 
$stmt->nextRowset();
$stmt->nextRowset();
$update_id =  $stmt->fetchColumn();
Sign up to request clarification or add additional context in comments.

Comments

0
<?php
$id = 123;
$query = "UPDATE table SET column = something, id = ? WHERE condition LIMIT 1;"
$st = $db->prepare($query);
$st->execute(array(
 $id
));

$result = $st->fetch(PDO::FETCH_ASSOC);

var_dump($result);

Do you tried something like this?, fetching the modified statement

1 Comment

sry for late response. the problem is I don't have the id and I have to either select the id in a different query and update it later or use the query written in the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.