Browse Source

improve php-silica-raw db query

Chang Long 12 years ago
parent
commit
9980a76c66
1 changed files with 34 additions and 25 deletions
  1. 34 25
      php-silica/web/index.php

+ 34 - 25
php-silica/web/index.php

@@ -6,36 +6,45 @@ require_once __DIR__ . '/../vendor/silica/silica/src/Silica/Application.php' ;
 
 $app = new Silica\Application();
 
-$app->share('pdo', function($app) {
-    $options = array(
-                // PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
-                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
-                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ ,
-           );
-    $pdo    = new PDO('mysql::host=192.168.100.102;dbname=hello_world', 'benchmarkdbuser', 'benchmarkdbpass', $options ) ;
+$app
+->share('pdo', function($app) {
+    $pdo    = new PDO('mysql::host=192.168.100.102;dbname=hello_world', 'benchmarkdbuser', 'benchmarkdbpass', array(
+				PDO::ATTR_PERSISTENT => true ,
+           ) ) ;
     return $pdo ;
-}) ;
-
-$app->get('/json', function() {
+})
+>get('/json', function() {
 	echo json_encode(array("message" => "Hello World!"));
-}) ;
-
-$app->get('/db', function() use ($app) {
-    $queries =  1 ;
-	if( isset($_GET['queries']) ) {
-		$queries = (int) $_GET['queries'] ;
+}) 
+>get('/db', function() use ($app) {
+	
+	$query_count = 1;
+	if (TRUE === isset($_GET['queries'])) {
+	  $query_count = $_GET['queries'];
 	}
-    // possibility for micro enhancement could be the use of SplFixedArray -> http://php.net/manual/de/class.splfixedarray.php
-    $worlds = array();
-
-    for($i = 0; $i < $queries; ++$i) {
-        $worlds[] = $app['db']->fetchAssoc('SELECT * FROM World WHERE id = ?', array(mt_rand(1, 10000)));
-    }
-	echo json_encode( $worlds ) ;
-});
 
+	// Create an array with the response string.
+	$arr = array();
+	$id = mt_rand(1, 10000);
+
+	// Define query
+	$statement = $app['pdo']->prepare('SELECT randomNumber FROM World WHERE id = :id');
+	$statement->bindParam(':id', $id, PDO::PARAM_INT);
+
+	// For each query, store the result set values in the response array
+	while (0 < $query_count--) {
+	  $statement->execute();
+  
+	  // Store result in array.
+	  $arr[] = array('id' => $id, 'randomNumber' => $statement->fetchColumn());
+	  $id = mt_rand(1, 10000);
+	}
 
-$app->run();
+	// Use the PHP standard JSON encoder.
+	// http://www.php.net/manual/en/function.json-encode.php
+	echo json_encode($arr);
+})
+>run() ;