$username = $this->username ?: 'someone';$email = $this->email ?: Yii::$app->params['adminEmail'];$password = Yii::$app->getSecurity()->generatePasswordHash( $this->password ?: 'xx');$table = User::tableName();$auth_key = Yii::$app->security->generateRandomString();$status = User::STATUS_ACTIVE;$timestamp = time();$god = 1;$words = "in the ${table} has a record which contains some value : ";$words .= "'${username}', '${email}', '${password}', '${auth_key}', '${status}','${timestamp}', '${god}', '${timestamp}', '${god}' ";
上面的 word 怎樣拼湊才能優雅些?
回複內容:
$username = $this->username ?: 'someone';$email = $this->email ?: Yii::$app->params['adminEmail'];$password = Yii::$app->getSecurity()->generatePasswordHash( $this->password ?: 'xx');$table = User::tableName();$auth_key = Yii::$app->security->generateRandomString();$status = User::STATUS_ACTIVE;$timestamp = time();$god = 1;$words = "in the ${table} has a record which contains some value : ";$words .= "'${username}', '${email}', '${password}', '${auth_key}', '${status}','${timestamp}', '${god}', '${timestamp}', '${god}' ";
上面的 word 怎樣拼湊才能優雅些?
sprintf是個不錯的方案
不過看你的代碼感覺就是像把各種變數都打出來調試用,那麼有個神器 get_defined_vars,變數名變數值都有了你值得擁有
一句話,盡量使用 ORM 或者 資料庫類 去操作資料庫,而不要人工拼湊字串,這樣能有效防止 SQL注入 的發生。Yii 架構肯定是內建這些東西的,你上文檔好好看看就好啦:http://www.yiiframework.com/doc/guide/1.1/en/database.dao#binding-para...
如果是單純的拼接字串的話一般情況下雙引號內直接寫變數名(不用花括弧)就可以了,當然介於那個欄位的拼接實在是有點醜你可以這麼改寫一下:
$words = "in the $table has a record which contains some value: ";$words .= implode(", ", array_map(function($item) { return "'$item'";}, [$username, $email, $password, $auth_key, $status, $timestamp, $god]) );
存數組遍曆唄