我有一個簡單的表單,我使用會話變量將數據傳遞給一個php頁面。我在一個外部函數頁面中有兩個函數,但我不能讓每個函數中的變量全局工作,除非我在每個特定函數中命名該變量。PHP函數變量需要的建議
這裏是一個我希望有人可以提供幫助的例子。
$dbName = $_SESSION['dataBaseName'];
$tableName = $_SESSION['tableName'];
$artistName = $_SESSION['artistName'];
$songName = $_SESSION['songName'];
function table_exists($tableName)
{
if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$tableName."'"))==1)
{
echo "Table exists <br />";
}
else
{
$sql = "CREATE TABLE songList (songId int NOT NULL AUTO_INCREMENT PRIMARY KEY, artistName varchar(60), songName varchar(25))";
$result= mysql_query($sql) or die(mysql_error());
return $result;
}
}
在我的OTHER函數中,我把變量INSIDE函數。似乎不重要我使用的組合,我的變量必須REDECLARED我使用的每個功能。我在前面嘗試使用GLOBAL,但這只是導致錯誤。下面是其他功能:(?也許db_config.php
)
function tableWrite()
{
$dbName = $_SESSION['dataBaseName'];
$tableName = $_SESSION['tableName'];
$artist = $_SESSION['artist'];
$song = $_SESSION['song'];
if(!empty($_REQUEST['insert']))
{
$sql = "INSERT INTO $tableName (artistName, songName) values ('$artist', '$song')";
$result = mysql_query($sql) or die(mysql_error());
$showaresult = mysql_query("SELECT * from $tableName where artistName = '$artist' AND songName= '$song' ") or die("Invalid query: " . mysql_error());
echo ("New entry added");
$row = mysql_fetch_array($showaresult);
echo ("<br> Catalog Number = ". $row["songId"] . "<br> Artist Name = " . $row["artistName"] . "<br>");
echo("Song Name = " . $row["songName"] . "<br>");
echo ("<h1> Current Catalog </h1>");
$showresult = mysql_query("SELECT * from $tableName") or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_array($showresult))
{
echo ("<br> Catalog Number = ". $row["songId"] . "<br> Artist Name = " . $row["artistName"] . "<br>");
echo("Song Name = " . $row["songName"] . "<br>");
}
}
}
如果我理解正確,你想要一箇舊的,凌亂的PHP4行爲?我認爲這應該是這樣的:你需要一個變量,你聲明它。該會話將只允許您在呼叫中保留一個值。 –
1.不推薦使用'mysql_ *'函數(請參閱[紅盒子](http://php.net/mysql_query))。 2.你的代碼很容易被SQL注入,正確地逃脫你的變量名。 3.您的代碼容易受到XSS攻擊,在將變量輸出到HTML時使用['htmlspecialchars'](http://php.net/htmlspecialchars)。 –
好的,我爲我的變量設置了一個db_config文件。只要閱讀說明書就可以了。謝謝你的提示 –