テーブルを作成するphpのリストです。
おそらく単純ミスだと思いますがテーブルが作成されず、私の環境ではエラーも出ません。
どこが間違っているのでしょうか?(リストはほぼそのままで実行できると思います)
ご指摘うけましたので質問を修正します。
dbの接続は問題ありません
可変変数に関してですが
$string="CREATE TABLE userTable(? ?, ? ?, ? ?, 〜続く )"の形で意図した形です
SQLについては"create table userTable(Id int, inTime datetime, outTime dateTime, comment text);"を
直で入力して確かめています
最終的にはprepareをやめqueryにして$stringに直接修正する形で実行を確認しています。(質問投稿後に確認しました)がなぜprepareで動作がうまくいかなかったかはわかりません
php
1<?php 2//db_controle class 3//db_configで指定されたテーブルを探し、無ければ作成し、あれば 4$db_controle=new db_controle(); 5print "<pre>"; 6print_r($db_controle); 7print "</pre>"; 8 9class db_controle{ 10 11 private $errorMessage=null; 12 public $constructError=null; 13 14 //db_configからカラムを受け取り 15 //attendanceAndLeavingTable,userTableを作成する 16 function __construct(){ 17 require(dirname(__FILE__)."/db_config.php"); 18 //接続 19 try{ 20 $this->PDO=new PDO("mysql:host=".$host.";dbname=".$db,$user,$password); 21 22 //テーブルネームリストに従い 23 //テーブルを確認、作成する 24 foreach($tableNameList as $tableName){ 25 $result=$this->CreateTable($tableName); 26 if( $result===false ){ 27 $this->constructError="false"; 28 $this->execute=array_keys($$tableName); 29 return; 30 } 31 } 32 return; 33 //接続失敗 34 }catch (PDOException $e) { 35 $this->errorMessage= "PDO connect error! " . $e->getMessage(); 36 $this->constructError=false; 37 return; 38 } 39 40 41 } 42 43 //引数に従い 44 //テーブルの作製を行う 45 private function CreateTable($tableName){ 46 require(dirname(__FILE__)."/db_config.php"); 47 $question=$this->gattaiArray($$tableName); 48 $string="CREATE TABLE ".$tableName." (".implode(' ', array_fill(0,count($question),'?') ).")"; 49 $stmt=$this->PDO->prepare($string); 50 if( $stmt===false ){ 51 $this->errotMessage="CreateTable create table prepare error"; 52 $this->$tableName=$string; 53 $this->$tableName->question=$question; 54 $this->PDO=null; 55 return false; 56 } 57 $stmt->execute($question); 58 if( $stmt===false ){ 59 $this->errotMessage="CreateTable create table execut error"; 60 $this->$tableName=$string; 61 $this->$tableName->question=$question; 62 $this->PDO=null; 63 return false; 64 65 } 66 $this->$tableName=$string; 67 $this->question=$question; 68 return; 69 70 71 } 72 //エラー取得メソッド 73 public function getError(){ 74 return $this->errorMessage; 75 } 76 //配列とキーを全部数値添字の配列に組み替える 77 //ついでにカンマもつける 78 private function gattaiArray($arrayName){ 79 require(dirname(__FILE__)."/db_config.php"); 80 $keyArray=array_keys($arrayName); 81 $valueArray=array_values($arrayName); 82 $result=array(); 83 foreach($keyArray as $index => $key){ 84 $result[]=$key; 85 $result[]=$valueArray[$index].","; 86 } 87 //最後のカンマを外す 88 $last=array_pop($result); 89 $result[]=substr($last, 0, -1); 90 return $result; 91 92 } 93} 94?> 95 96
php
1<?php 2$host="hogehost"; 3$user="hogeuser"; 4$password="hogepassword"; 5$db="hogedb"; 6$tableNameList=array("userTable"); 7 8$userTable=array( 9 "ID"=>"int", 10 "inTime"=>"datetime", 11 "outTime"=>"datetime", 12 "comment"=>"text" 13) 14?> 15 16コード
回答1件
あなたの回答
tips
プレビュー