Error knowing if a MySQL table is empty

2

I have the following php code and it does not detect me if there is a record in the table or not and I do not know what it can be:

$server = "localhost";
$user = "root";
$pass = "";
$bd = "crypto4all";

//Creamos la conexión
$conexion = mysqli_connect($server, $user, $pass, $bd) 
or die("Ha sucedido un error inexperado en la conexion de la base de datos");

$consulta = mysqli_query($conexion,"SELECT COUNT(*) FROM criptomoneda");

if($consulta == '0'){
    foreach ($criptomoneda as $c) {
        mysqli_query($conexion,"INSERT INTO criptomoneda (nombre,ranking,volumen_24h,porcentaje_1h,porcentaje_24h,porcentaje_7d,fecha) 
        VALUES ('".$c['name']."','".$c['rank']."','".$c['24h_volume_usd']."','".$c['percent_change_1h']."','".$c['percent_change_24h']."','".$c['percent_change_7d']."','".$fecha."')");
    }
}else{
    foreach ($criptomoneda as $c) {
        mysqli_query($conexion,"UPDATE criptomoneda SET volumen = ('".$c['24h_volume_usd']."') WHERE nombre = '".$c['name']."'");
        mysqli_query($conexion,"UPDATE criptomoneda SET fecha = ('".$fecha."') WHERE nombre = '".$c['name']."'");
    }
}
    
asked by charli 14.05.2018 в 20:35
source

1 answer

2

mysqli_query returns an objero not the amount of the column count (), you must use mysqli_fetch_assoc for example to obtain the row of results and compare by the column.

Example:

$server = "localhost";
$user = "root";
$pass = "";
$bd = "crypto4all";

//Creamos la conexión
$conexion = mysqli_connect($server, $user, $pass, $bd) 
or die("Ha sucedido un error inexperado en la conexion de la base de datos");

// añadimos un alias para identificar mas facil:  AS total
$resultado = mysqli_query($conexion,"SELECT COUNT(*) AS total FROM criptomoneda");

// obtenemos la primera fila como array asociativo, en este caso solo tendremos una
$row = mysqli_fetch_assoc($resultado);

// comparamos con el alias total que dimos en la consulta
if($row['total'] == '0'){
  // si no hay registros
}else{
  // si hay registros
}
    
answered by 14.05.2018 / 20:43
source