2012-10-25 21 views
0

我試圖爲我的應用程序創建安裝嚮導。在嘗試將用戶連接詳細信息寫入/存儲到文件的其中一個步驟中。有誰知道更好的方法來做到這一點。我的代碼在達到$符號時顯然會中斷。在安裝過程中將用戶數據庫信息寫入文件

$myFile = "../functions/config2.php"; 
    $fh = fopen($myFile, 'w') or die("can't open file"); 

    $stringData = "<? #DATABASE CONNECTIONS\n"; 
    fwrite($fh, $stringData); 

    $stringData = "$dbservertype='mysql';\n"; 
    fwrite($fh, $stringData); 

    $stringData = "$servername='".$_POST['host']."';\n"; 
    fwrite($fh, $stringData); 

    $stringData = "$dbusername='".$_POST['dbusername']."';\n"; 
    fwrite($fh, $stringData); 

    $stringData = "$dbpassword='".$_POST['dbpass']."';\n"; 
    fwrite($fh, $stringData); 

    $stringData = "$dbname='".$_POST['dbname']."';\n"; 
    fwrite($fh, $stringData); 

    $stringData = "global $link;\n"; 
    fwrite($fh, $stringData); 

    $stringData = "$link=mysql_connect ('$servername','$dbusername','$dbpassword');\n"; 
    fwrite($fh, $stringData); 

    $stringData = "if(!$link){die('Could not connect to MySQL');}\n"; 
    fwrite($fh, $stringData); 

    $stringData = "mysql_select_db('$dbname',$link) or die ('could not open db'.mysql_error());\n"; 
    fwrite($fh, $stringData); 

    fclose($fh); 

我想的書面文件,以最終看起來像這樣

<? 
    //DATABASE CONNECTIONS 
    $dbservertype='mysql'; 
    $servername='posted_server'; 
    $dbusername='posted_user'; 
    $dbpassword='posted_pass'; 
    $dbname='posted_dbname'; 

    global $link; 
    $link=mysql_connect ("$servername","$dbusername","$dbpassword"); 
    if(!$link){die("Could not connect to MySQL");} 
    mysql_select_db("$dbname",$link) or die ("could not open db".mysql_error()); 
    ?> 

我的輸出現在看起來像這樣

<? #DATABASE CONNECTIONS 
    ='mysql'; 
    ='host'; 
    ='user'; 
    ='pass'; 
    ='dbname'; 
    global ; 
    =mysql_connect ('','',''); 
    if(!){die('Could not connect to MySQL');} 
    mysql_select_db('',) or die ('could not open db'.mysql_error()); 
+0

一些進一步的建議。避免短標籤<?而是使用完整的<?php,並且您應該避免使用mysql_ *函數,因爲它們已被棄用,請閱讀[this](http://www.php.net/manual/en/mysqlinfo.api.choosing.php) – wgcrouch

回答

1

您正在使用雙引號「 在PHP如果你在雙引號中包含了一個有效的變量名,那麼php會插入該變量,如果它不存在,它將解析爲空,或者拋出錯誤。

你應該逃避$符號如:

$stringData = "\$dbservertype='mysql';\n"; 
+0

真棒工作!謝謝! – Hector

相關問題