I have a simple form that I am passing data from to a php page using session variables. I have two functions in an external function page, but I cannot get the variables in each function to work globally unless I name the variable in each particular function.
Here is an example that I am hoping someone can help with.
$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;
}
}
In my OTHER function I put the variables INSIDE the function. Doesnt seem to matter what combo I use, my variables have to be REDECLARED every function I use. I tried using GLOBAL in front but that just causes an error. Here is the other function:
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>");
}
}
}
You should put those database access variables in a different php file (maybe
db_config.php?). You can then use arequiredirective in files where you need the values of said variables.Also, don’t use
mysql_*functions. They have been deprecated in favor ofPDOorMySQLi. This will help you write better code and prevent SQL injection vunerabilities.