3

I select data from tab1 to a variable, and use it in another query, which updates tab1. Target column target is of type INT, so I round it before its set.

It works well in mysql workbench, also getting no error from php (error_reporting set to -1). It just doesn't really update the target column - it stays zero.

Any idea why?

$q = 'SELECT @tmp = ( SELECT t
                      FROM tab1
                      WHERE a_id = :id1 );
      UPDATE tab1
      SET target = ( SELECT ROUND( @tmp / ( SELECT COUNT(*)
                                            FROM tab2
                                            WHERE b_id = :id2 )));
      ';

$sth = $dbh->prepare( $q );
$sth->execute( array( ':id1' => $id, ':id2' => $id ) );
11
  • 1
    You cannot use a named parameter marker of the same name twice in a prepared statement. Also, to support multi-queries, you need to make sure the PDO::ATTR_EMULATE_PREPARES attribute is set to true Commented Jan 12, 2014 at 22:39
  • 1
    By default user variables in MySql are disabled. You have to allow them in your connection. I'll see if I can find how in google. Commented Jan 12, 2014 at 22:53
  • 2
    stackoverflow.com/questions/4683110/… Commented Jan 12, 2014 at 22:54
  • 2
    @MathewFoscarini I think you can do multi-queries with PDO_MYSQLND and ATTR_EMULATE_PREPARES set to true. Commented Jan 12, 2014 at 23:04
  • 1
    User variables for MySQL.NET connector are disabled by default, but I can not confirm this is true for PDO/PHP. You'd have to run a simple SET @t = 1; SELECT @t; test. Commented Jan 12, 2014 at 23:28

1 Answer 1

0

When using SELECT with user variables, we must use a different assignation, which is :. be sure to have emulate prepares set to true.

$q = 'SELECT @tmp:= ( SELECT t
                  FROM tab1
                  WHERE a_id = :id1 );
      UPDATE tab1
      SET target = ( SELECT ROUND( @tmp / ( SELECT COUNT(*)
                                        FROM tab2
                                        WHERE b_id = :id2 )));
     ';
$sth = DB::query( $q );
var_dump($sth->fetch());
$sth->nextRowset();
var_dump($sth);

but mysql reference http://dev.mysql.com/doc/refman/5.0/en/user-variables.html states that we should set user-defined variables with SET

so in your case:

$q = 'SET @tmp = ( SELECT t
                      FROM tab1
                      WHERE a_id = :id1 );
      UPDATE tab1
      SET target = ( SELECT ROUND( @tmp / ( SELECT COUNT(*)
                                            FROM tab2
                                            WHERE b_id = :id2 )));
      ';
Sign up to request clarification or add additional context in comments.

Comments

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.