0

I want to get the last row inserted into the database, but only get the first row. How I can fix it?

In phpmyadmin everything works: phpmyadmin But the code does not work:

Último precio: 28.41

Code:

            $skip = 0;
            $max = 1;
            $id = 'gooo_id';
            $q = $conn->prepare('SELECT * FROM price WHERE asin = :asin ORDER BY :id DESC LIMIT :skip, :max');
            $q->bindValue(':asin', $asin, PDO::PARAM_STR);
            $q->bindValue(':id', $id, PDO::PARAM_STR);
            $q->bindValue(':skip', (int) trim($skip), PDO::PARAM_INT);
            $q->bindValue(':max', (int) trim($max), PDO::PARAM_INT);
            $q->execute();
            $result_row = $q->fetchObject();
            $lastprice = $result_row->price;
            echo 'Último precio: '.$lastprice.'';

Solution

$skip = 0;
            $max = 1;
            $q = $conn->prepare('SELECT * FROM price WHERE asin = :asin ORDER BY gooo_id DESC LIMIT :skip, :max');
            $q->bindValue(':asin', $asin, PDO::PARAM_STR);
            $q->bindValue(':skip', (int) trim($skip), PDO::PARAM_INT);
            $q->bindValue(':max', (int) trim($max), PDO::PARAM_INT);
            $q->execute();
            $result_row = $q->fetchObject();
            $lastprice = $result_row->price;
            echo 'Último precio: '.$lastprice.'';
treska
  • 21
  • 7
  • 1
    http://stackoverflow.com/questions/2542410/how-do-i-set-order-by-params-using-prepared-pdo-statement – Jompper Dec 30 '13 at 14:10
  • I don't think you can pass field names with bindValue. In your case field is converted to string so 'gooo_id' – Jompper Dec 30 '13 at 14:11

1 Answers1

1

You need to use the attribute name from SQL table after ORDER BY in your query. You put in the value as argument which is the same for all rows. Thus it doesn't do anything with the order.

The query should be something like:

$q = $conn->prepare('SELECT * FROM price WHERE asin = :asin ORDER BY gooo_id DESC LIMIT :skip, :max');

Of course you need to adjust the bind variables...

Kamil Šrot
  • 2,141
  • 17
  • 19