How can I know if the table exists

0

The problem is that I do not know how I can check that logeo. I currently do a query directly to a table, when there is perfect nothing happens, it shows me the information. when it does not exist it throws me the following error:

Unexpected '<'

my code in php:

    <?php
if($_SERVER["REQUEST_METHOD"]=="POST"){
    include('conexion.php');
    header('Content-Type: application/json; charset=utf8');
    $usuario= $_POST['usuario'];

    $result  = mysqli_query($con,"SELECT * from $usuario") or mysqli_error($con);
        while ($row = $result->fetch_assoc()) {
             $arr[] = $row;
        }
        $json = json_encode($arr,JSON_UNESCAPED_UNICODE);
        echo $json;
}
?>
    
asked by DoubleM 13.02.2018 в 00:12
source

2 answers

1

You can use the object-oriented style to know the number of records obtained;

 $mysqli_result->num_rows;

This throws a whole number, 0 in the case that there is no record with the criteria you are looking for;

an example:

$mysqli_result->num_rows;

if($mysqli_result->num_rows > 0){
    //encontro registros existentes
}else{
    //No encontro ningun registro
}

Reference link

    
answered by 13.02.2018 в 00:22
0

You can determine first if the table with a Query exists, using SHOW TABLES LIKE if the value is equal to 1, it means that the table exists:

<?php
if($_SERVER["REQUEST_METHOD"]=="POST"){
    include('conexion.php');
    header('Content-Type: application/json; charset=utf8');
    $usuario= $_POST['usuario'];
    if ($result = mysqli_query("SHOW TABLES LIKE '$usuario'")) {
        if($result->num_rows == 1) {
            //La tabla existe
            $query  = mysqli_query($con,"SELECT * from $usuario");
            while ($row = $query->fetch_assoc()) {
                $arr[] = $row;
            }
            $json = json_encode($arr,JSON_UNESCAPED_UNICODE);
            echo $json;
        }
    }
    else {
        echo "La tabla no existe";
    }            
}
?>
    
answered by 13.02.2018 в 00:24