Page 1 of 1

PHP/JSON not working

Posted: Thu Aug 13, 2009 9:59 am
by core000
I think I'm getting the array conversion wrong. I am trying to copy the results of the query from one array to another. However I am not sure how to assign name/value pairs into the array. Code below:

Code: Select all

<?php
$myServer = "myserver.com";
$myUser = "user";
$myPass = "pass";
$myDB = "Northwind";
 
//create an instance of the  ADO connection object
$conn = new COM ( "ADODB.Connection" ) or die ( "Cannot start ADO" );
 
//define connection string, specify database driver
$connStr = "PROVIDER=SQLOLEDB;SERVER=" . $myServer . ";UID=" . $myUser . ";PWD=" . $myPass . ";DATABASE=" . $myDB;
$conn->open ( $connStr ); //Open the connection to the database
 
 
//declare the SQL statement that will query the database
$query = "
SELECT * from Employees
";
 
//execute the SQL statement and return records
$rs = $conn->execute ( $query );
 
$num_columns = $rs->Fields->Count ();
//echo $num_columns . "<br>"; 
 
$returnArray = array();
 
for($i = 0; $i < $num_columns; $i ++) {
    $fld [$i] = $rs->Fields ( $i );
}
 
for($i = 0; $i < $num_columns; $i ++) {
    array_push($returnArray, $fld);
}
 
//Start the output of XML
while ( ! $rs->EOF ) //carry on looping through while there are records
{
    
    for($i = 0; $i < $num_columns; $i ++) {
        array_push($resultarray, $fld [$i]->value); 
        //$rs->MoveNext ();
    }
    
     //move on to the next record
}
 
echo json_encode($returnArray);
 
 
//close the connection and recordset objects freeing up resources 
$rs->Close ();
$conn->Close ();
 
 
 
$rs = null;
$conn = null;
?>

Re: PHP/JSON not working

Posted: Thu Aug 13, 2009 10:46 am
by pickle
If your query has 3 columns, "apple", "orange", "peach", and you want to put those three words in an array as keys, with the values of the columns as array values, you do this:

Code: Select all

$myArray['apple'] = 'n';
$myArray['orange'] = 'n+1';
$myArray['peach'] = 'n+2';
If you use mysql_fetch_assoc() (or the equivalent for whichever database you're using), the value returned from the function will already be an associative array like '$myArray' above.

Re: PHP/JSON not working

Posted: Fri Aug 14, 2009 10:51 am
by core000
Do you know the 'fetch_assoc' equivalent for ADO? i think that's what i need.

I'm not advanced enough in PHP to create workaround. I guess the goal is to convert the query results to an array so I can export it via JSON.

Re: PHP/JSON not working

Posted: Fri Aug 14, 2009 11:11 am
by pickle
No I don't know. I'm sure the docs would though.