2014-01-26 4 views
0
PHP5

그래서 쿼리를 처리하는 기능이 있습니다동적 쿼리에 배열에 결과

function cfquery($query){ 
    // Connection's Parameters 
    $db_host="localhost"; 
    $db_name="d"; 
    $username="u"; 
    $password="p"; 
    $db_con=mysql_connect($db_host,$username,$password); 
    $connection_string=mysql_select_db($db_name); 
    // Connection 
    mysql_connect($db_host,$username,$password); 
    mysql_select_db($db_name); 

    // Query 
    $sql = $query; 
    $results = mysql_query($sql); 
    return $results; 
} 

그리고이 결과를 가지고 배열로 넣어하는 함수를 작성하기 위해 노력하고있어,하지만이 기능을 '자원'을 생성하고 있으며 인터넷에서 찾은 모든 것이 해당 데이터 유형에 대해 작동하지 않거나 동적으로 생성되지 않습니다. 데이터를 가져 오기 위해 열 이름을 알아야 할 필요가 있습니다. 예를 들어

:

while ($row = mysql_fetch_array($results)){ 
    echo $row['name'] . ',' ; 
    echo $row['email'] . ',' ; 
    echo $row['city'] . ',' ; 
} 

나는 결과에서 열 이름을 얻을 것이다 뭔가를 찾고 있어요. 이처럼 : 당신이 말할 수없는 경우에, 나는 ColdFusion에서에서 전환, 그래서 내가 (일부 문서를 읽은 후) 「자원은 "무엇의 막연한 생각을 가지고 있고,

$array = new array(); 
loop rows index x { 
    loop column_names index y { 
     $array[x][y] = $results[rows][column_names]; 
    } 
} 

아무 생각이 왜 배열을 가져올 수 없습니다.

+1

그것을 새로운 개발을 위해 이전 MySQL 확장을 사용하지 않는 것이 좋습니다 ** ** PHP 5.5.0부터 ** 사용되지 않으므로 향후에 제거 될 예정입니다. [MySQL : API 선택하기] (http : //in2.php.net/manual/en/mysqlinfo.api.choosing.php) –

답변

2

당신이 MySQLi 사용할 수있는 경우 : 필드에 메타 데이터를 얻을 수 사용 mysqli_fetch_field_direct()을.

필드 이름

은과 같이 액세스 할 수 있습니다 (결과 내 루프) : 당신이 사용되지 않는 (5.5 현재) mysql 기능을 사용하여 부착하는 경우

$metadata = mysqli_fetch_field_direct($row, $field_index); 
$name = $metadata->name; 

:는 대신에 mysql_field_name($result, $field_index)을 사용할 수 있습니다 이름은 객체가 아닌 문자열로 직접 반환되지만 동일한 방식입니다.

당신은 MySQLi에 읽을 수 있으며 여기에 구현이다 : *되지 않습니다 http://uk1.php.net/mysqli

0

mysql_로 ... mysqli_를 사용 * 또는 PDO MySQL의에서

...

function cfquery($query) 
{ 
    $return = array(); 

    $cn = mysql_connect("localhost","u","p") or die('connection error'); 
    mysql_select_db("d", $cn) or die('select db error'); 

    $results = mysql_query($query, $cn) or die(mysql_error($cn)); 

    while ($row = mysql_fetch_array($results)) 
     $return[] = $row; 

    mysql_free_result($results); 
    mysql_close($cn); 

    return $return; 
} 
+1

당신은 당신의 대답에 비추천 함수를 사용했습니다. –

+0

사용자가 mysql_ * function을 사용합니다 ... 경고했습니다 –

+0

댓글을 달았습니다. 당신의 예제가 혼란을 막기 위해 deprecated 함수를 사용한다고 명시 적으로 기술 할 것입니다. –