2014-07-22 2 views
0

MySQL 데이터베이스에 데이터를 삽입하기위한 웹 애플리케이션을 구축하고 있습니다. PHP의 PDO API를 사용하여 자동 증가 기본 키를 얻기 위해 데이터베이스를 쿼리합니다. MySQL Console에서 쿼리를 실행하면 올바른 결과가 생성됩니다. 하지만 PHP에서 쿼리를 실행하려고하면 null이 반환됩니다.SQL 쿼리는 PHP에서는 null을 반환하지만 MySQL에서는 올바른 결과를 반환합니다.

쿼리 : MySQL의 콘솔에서

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

결과 :

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

관련 PHP 코드 :

// 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"; 

아무것도 페이지에 출력되지는 출력 자동을해야하지만 ID를 증가시킨 다음 "Hello world". 내가 쓴 오타가 보이지 않아. 콘솔에서 쿼리가 작동하지만 PHP에서는 작동하지 않는 이유는 무엇입니까?

+1

이 경우'$ id'가 결과 세트가 될 것이라고 믿기 때문에'$ id [0] [ 'Auto_Increment']'를 사용하여 액세스하십시오. 또는'var_dump ($ id)'를 실행하여 변수가 무엇을 포함하는지 정확하게 확인하십시오. – Supericy

+0

무엇인가? 'echo $ id [0] [ 'Auto_Increment'];'또한 아무것도 출력하지 않았습니다 : /. – Lou

+0

흥미 롭습니다. 내가 var_dump했을 때, 다음과 같은 결과를 출력하고, 그것이 무엇을 의미하는지 모르겠다 :'object (PDOStatement) # 2 (1) {[ "queryString"] => string (80) "SELECT auto_Increment FROM information_schema.tables WHERE table_name = 'charlist' "}'. – Lou

답변

1

당신은 당신이 배열로 결과를 액세스 할 필요가 원하는 결과를 액세스하기 위해, 결과를

$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"; 
+0

완벽하게 작동합니다. 큰! – Lou

1

사용)

많은 방법으로 로마로 통한다 : 인 print_r ($ 아이디);

쿼리 결과의 내용을 확인하십시오. 쿼리 결과의 출력은 배열입니다. you shou

관련 문제