如何将mysqli查询结果值赋给php变量?

时间:2017-08-18 07:32:04

标签: php mysql mysqli

<?php                
    $con=mysqli_connect("localhost","user","pass","db");

    // Check connection
    if (mysqli_connect_errno()){
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    // Perform queries 
    $result = mysqli_query($con,"SELECT COUNT(*)\n"
          . "FROM INFORMATION_SCHEMA.COLUMNS\n"
          . "WHERE table_name = \'CustomersTable\'");       

    $something = mysqli_fetch_assoc($result);

    echo $something;             

    mysqli_close($con);
?>

我希望代码能够回显某些内容的值,即表中的列数。但我没有看到任何印刷品。我做错了什么?

1 个答案:

答案 0 :(得分:1)

您的查询错误。如下所示: -

 <?php       

    $con=mysqli_connect("localhost","user","pass","db");

    if (mysqli_connect_errno()){
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    $result = mysqli_query($con,"SELECT COUNT(*) as total_count FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'CustomersTable'") or die(mysqli_error($con));

    $something = mysqli_fetch_assoc($result);

    echo $something['total_count'];//or do var_dump($something);

    mysqli_close($con);
?>