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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.