SQL文 を半自動で生成する


$statement = $pdo->query($sql);
$item = $statement->fetch(PDO::FETCH_ASSOC);
$i = 0;
foreach($item as $key => $val){
    if($i == 0){
        $kanma = '';
    }else{
        $kanma = ',';
    }
    $key_text .= $kanma."`".$key."`";
    $val_text .= $kanma."'".$_POST[$key]."'";
    $i ++;
}

echo '<hr>'.$key_text.'<hr>';
echo $val_text.'<hr>';

$sql = "INSERT INTO `tb_staff` ($key_text) VALUES($val_text)";
echo $sql;

$statement = $pdo->query($sql);
$pdo = new PDO('mysql:host = '.DB_SERVER.';dbname='.DB_NAME.';charset=utf8', DB_USER, DB_PASSWORD);
$sql = "SELECT * FROM `wr_user` LIMIT 1";
$statement = $pdo->query($sql);
$item = $statement->fetch(PDO::FETCH_ASSOC);

$i = 0;
foreach($item as $key => $val){

	if($i == 0){
		$kanma = '';
	}else{
		$kanma = ',';
	}

	$key_text .= $kanma."`".$key."`";
	$val_text .= $kanma."'$".$key."'";

	$i ++;
}
echo '<hr>'.$key_text.'<hr>';
echo $val_text.'<hr>';


$sql = "INSERT INTO `wr_user` ($key_text) VALUES($val_text)";
echo $sql;
$db = mysql_connect(DB_HOST.":".DB_PORT,DB_USER,DB_PASSWORD);
// mysql_query("SET NAMES utf8");
mysql_set_charset('utf8');
mysql_select_db(DB_NAME, $db);


$sql = "SELECT * FROM wr_posts LIMIT 1";
$rs = mysql_query($sql,$db);
$item = mysql_fetch_assoc($rs);
var_dump($item);


$i = 0;
foreach($item as $key => $val){

	if($i == 0){
		$kanma = '';
	}else{
		$kanma = ',';
	}

	$key_text .= $kanma."`".$key."`";
	$val_text .= $kanma."'$".$key."'";

	$i ++;
}
echo '<hr>'.$key_text.'<hr>';
echo $val_text.'<hr>';

自動生成の例
INSERT INTO `wr_user`
  (`user_id`,`f1`,`f2`,`f3`)   
  VALUES
  (‘exampleuser_id’,’examplef1′,’examplef2′,’examplef3′)