Taking an SQL field value after function return

Asked

Viewed 110 times

1

How do I get a certain value from the SQL table after I have made a select. It will always return a single value

$sql = "SELECT MAX(cod_periodo) from periodo_edital";
$query = $this->db->query($sql);
$result = $query->result();

This is my code I need to access the cod_periodo field. Is there a specific command to execute?

  • Try to var_dump the variable $result, may be easier to solve

  • It returns correct, but when I use $cod_periodo in my query it inserts as () and the error in the database

  • It seems that not coming the field you want, puts the query in the question, maybe the problem is there.

  • I changed it, but another problem came up. It returns an array as I do to take the string value it returned and switch to integer

  • You use PDO or mysqli?

  • To using PDO

Show 1 more comment

1 answer

0


You can create a name (alias) for the MAX of the query, facilitates at the time of use.

$sql = "SELECT MAX(cod_periodo) AS max_cod_pedido from periodo_edital";

and to recover the value that will return as an array you can do so:

echo $result[0]->max_cod_pedido;

within the $result[0] there will probably be an object

and that you access the attribute with ->max_cod_pedido

if it is an array

echo $result[0][max_cod_pedido];

As you commented that the return is single-line, not the need to iterate.

But it might be nice to validate the expected result, in order not to generate errors.

Something like that, for example:

if (isset($result[0])) {
  • It worked, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.