Jump to content

Select single value from database


Adamhumbug

Recommended Posts

Hi,

I am trying to select a single value from a database which will be the highest integer in a column.

I have written

  $sql1 = "SELECT MAX(transaction_id) from pos_basket";
  $result1 = $conn->query($sql1);
  $value =mysqli_fetch_object($result1);
  $_SESSION['transaction_id']=$value;

Which is returning 

Array ( [transaction_id] => stdClass Object ( [MAX(transaction_id)] => 3 )

I would like it to be returning just the number 3

I have tried several fetch variations but seem to be getting a lot of fatals.

I am sure that this is a very simple solution.

Thanks in advance

Link to comment
Share on other sites

When selecting results of a function, use a column alias so you can easily access the value. EG

MAX(transaction_id) as maxid

Now you can

 $sql1 = "SELECT  
             MAX(transaction_id) as maxid
           FROM pos_basket";
  $result1 = $conn->query($sql1);
  $value = $result1->fetch_object();
  $_SESSION['transaction_id'] = $value->maxid;

 

As you are learning, I would recommend putting the effort into PDO instead of mysqli. It is a lot easier.

With PDO it would be

$sql1 = "SELECT  
             MAX(transaction_id) as maxid
           FROM pos_basket";
  $result1 = $conn->query($sql1);
  $_SESSION['transaction_id'] = $result1->fetchColumn();
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.