convert query result Mysql to INT

3

If I have the following function:

    function obtener_id(){
    $conn = db_connect();
    $query = "SELECT max(idproblema) FROM problemas";
    $result = @$conn->query($query);    
    return $result; 
}

What I want to do is that what I return that query is the number marked in the image and being an INT ... for example that $ result is only a 1, this query is done to know the last id of the table.

I want it to turn out to be a number, I do not want it that way:

    
asked by Yept 21.02.2018 в 22:48
source

1 answer

3

I would write a function that is safe ( safe ), as follows:

function obtener_id(){
    $conn = db_connect();
    $query = "SELECT max(idproblema) maximo FROM problemas";
    $result = $conn->query($query);

    $maximo=0;

    if ($result) {
        $fila = $result->fetch_assoc();
        $maximo = ($result->num_rows === 0) ? 0 :  $fila["maximo"];
    }
    return (int) $maximo;
}

In the same I have contemplated the following logic:

  • Input the value 0 to variable $maximo
  • Verify if the query was successful. If it has been, then I proceed to assign the value
  • I have given the alias maximo to the column resulting from the SELECT , to then be able to recover it using fetch_assoc (this is a matter of preferences, code clarity ... other methods are possible).
  • Use a ternary operator to assign $maximo to 0 if you can not find data, be the value of the column obtained.
  • Return $maximo , as an integer. You can try it with var_dump($maximo); .

NOTE: I've removed @ . It is bad programming practice to silence errors.

I hope it serves you.

    
answered by 21.02.2018 / 23:33
source