Neo
Neo

Reputation: 817

how to assign a mysqli query result value to a php variable?

<?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);
?>

I want the code to echo the value of something, which is the number of columns in the table. But I don't see anything printed. What am I doing wrong?

Upvotes: 1

Views: 3323

Answers (1)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72289

Your query is wrong. Do like below:-

 <?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);
?>

Upvotes: 1

Related Questions