Search code examples
phpmysqlsqlpdoauto-increment

SQL query returns null in PHP, but correct result in MySQL


I'm building a web application for inserting data into a MySQL database. I'm using PHP's PDO API to query the database to obtain an auto-incrementing primary key. When I run the query in MySQL Console, it produces the correct output. But when I try to run the query in PHP, it returns null.

Query:

mysql> SELECT Auto_Increment FROM information_schema.tables WHERE table_name='charlist';

Result in MySQL console:

+----------------+
| Auto_Increment |
+----------------+
|              7 |
+----------------+

Relevant PHP code:

    // Configuration.
    $username = "root";
    $password = "root";
    $hostname = "localhost";
    $dbname = "asoiaf";
    $tablename = "charlist";

    // Opens a connection to the database.
    try {
        $conn = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch(PDOException $e) {
        echo $e->getmessage();
    }

    // Gets all the information from POST.
    $autoidquery = "SELECT Auto_Increment FROM information_schema.tables WHERE table_name='$tablename'";
    $id = $conn->query("SELECT Auto_Increment FROM information_schema.tables WHERE table_name='$tablename'");
    // This should output the auto-incremented primary key, but nothing is output.
    echo $id."<br>Hello world";

Nothing is output on the page, although it should output the auto-incremented id and then "Hello world". I can't see any typos that I've made. Why would the query work in the console, but not in PHP?


Solution

  • You need to fetch the result

    $qry = $conn->query("SELECT Auto_Increment FROM information_schema.tables WHERE  table_name='$tablename'");
    $result = $qry->fetch();
    $id = $result['Auto_Increment'];
    echo $id."<br>Hello world";