Quantcast
Channel: Microsoft Drivers for PHP for SQL Server forum
Viewing all articles
Browse latest Browse all 391

Insert JSON records into SQL Server table using PHP

$
0
0

I hope this is the correct forum for PHP questions related to sql server.

I would like to pull data for all the cities in my county from the census API into a table in sql server.  I have been working on the code and was successful in having it write a record to the database table for the total number of items in the array returned by the API, unfortunately, they are all blank records.

I imagine this is something simple, and I will work to resolve, but if anyone has a thought, it is greatly appreciated.

Thanks.

<html><head></head><body><?php
	$serverName = "server";
	$connectionInfo = array( "Database"=>"database", "UID"=>"username", "PWD"=>"password" );
	$conn = sqlsrv_connect( $serverName, $connectionInfo );
	if( $conn ) {
		echo "Connection established. <br /> <br />";
	}else{
		echo "Connection could not be established. <br /> <br />";
		die( print_r( sqlsrv_errors(), true));
	}

	$homepage = file_get_contents("https://api.census.gov/data/2020/dec/responserate?get=NAME,DRRALL,CRRINT,RESP_DATE,CRRALL,GEO_ID,DRRINT&for=place:*&in=state:13");
	$content = json_decode($homepage, true);
	$totalrecords = count($content)."<br /> <br />";

	$NAME = $content['NAME'];
	$DRRALL = $content['DRRALL'];
	$CRRINT = $content['CRRINT'];
	$RESP_DATE = $content['RESP_DATE'];
	$CRRALL = $content['CRRALL'];
	$GEO_ID = $content['GEO_ID'];
	$DRRINT = $content['DRRINT'];
	$state = $content['state'];
	$place = $content['place'];
		
	$trunc = "TRUNCATE TABLE edtable.dbo.Demog_CensusResponse_Test";
	$stmt2 = sqlsrv_query( $conn, $trunc );
	//foreach ($content as $contentvalue) {
		for ($x = 1; $x <= $totalrecords; $x++) {
			//Create SQL query
			$sql = "INSERT INTO edtables.dbo.Demog_CensusResponse_Test(NAME, DRRALL, CRRINT, RESP_DATE, CRRALL, GEO_ID, DRRINT, state, place)
			VALUES('$NAME', '$DRRALL', '$CRRINT', '$RESP_DATE', '$CRRALL', '$GEO_ID', '$DRRINT', '$state', '$place')";
			//WHERE $place LIKE '42425'";

			//Execute SQL query
			$stmt = sqlsrv_query( $conn, $sql );
			if( $stmt === false ){
				echo "Something went wrong with the query, check error below <br /> <br />";
				die( print_r( sqlsrv_errors(), true));
			}
			else {
				echo "Statement executed <br /> <br />";
			}
		}
	//}
	sqlsrv_free_stmt( $stmt );
	sqlsrv_close( $conn );
	?></body></html>


Viewing all articles
Browse latest Browse all 391

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>