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());
4

1 回答 1

1

如果在双引号中包含有效变量名的内容,则在 php 中使用双引号 ",php 将插入该变量,如果它不存在,它将解析为空,或抛出错误。请参见此处

您应该转义 $ 符号,例如:

$stringData = "\$dbservertype='mysql';\n";
于 2012-10-25T21:46:23.133 回答