is there a way that i can check to see if a mysql table exists and if not add the table to the database with a session_id as a table name

Try this. I haven't tested it but it should do the trick. The key is to use the @ sign on line 2 to prevent the error message from showing up on the clients browser. Also, if you add or die(mysql_error()) to the end of line 2, the script will stop.

$sql="SELECT * FROM $table";
$result=@mysql_query($sql);
if (!$result)
{
echo "No table exists";
// Create a MySQL table 
$tblname=$_SESSION['ID'];
mysql_query("CREATE TABLE $tblname(
id INT NOT NULL AUTO_INCREMENT, 
PRIMARY KEY(id),
 name VARCHAR(30), 
 age INT)")
 or die(mysql_error());  
echo " so I created one!";
}

Had same problem ... google it and came up with this little code :

$sql= 'DESC table_name;';
            mysql_query($sql,$con);
            if (mysql_errno()==1146){
                //table_name doesn't exist
            }
            elseif (!mysql_errno())
               //table exist

let me know if this what you want.

If you're trying to log session variables to a session_id, there may be a more efficient way of doing this. Instead of creating a new table/records/fields, you could have a general 'sessions' table with the following fields:

id (int, autoincrement, PK); session_id(varchar[32]); user_id[int, FK]; session_vars[text]; last_impression[datetime*];

*datetime could be integer if you want to store time from unix epoch.

The session_id is inserted on login. Vars can be taken from user settings/ preferences page user actions etc etc. This field contains serialized data. The last_impression field is updated every time a new page (or element, if using ajax) is accessed. If the last_impression is > 30 minutes, a script could delete the session, forcing an user to login again.

Edited 7 Years Ago by diafol: n/a

function table_exists($tableName)
{ 
	$dbName = 'NAME_OF_DATABASE';
	
	$sql ='SHOW TABLES WHERE Tables_in_' . dbName . ' = \'' . $tableName . '\'';
	$rs = mysql_query($sql);

	if(!mysql_fetch_array($rs))
		return FALSE;
	else
		return TRUE;
}

Edited 6 Years Ago by kallena: n/a

#
$sql="SELECT * FROM $table";
#
$result=@mysql_query($sql);
#
if (!$result)
#
{
#
echo "No table exists";

#
$sql="SELECT * FROM $table";
#
$result=@mysql_query($sql);
#
if (!$result)
#
{
#
echo "No table exists";

As i know that we use
"CREATE TABLE IF NOT EXISTS session_id
(
attribute data type(size) CONSTRAINTS Constraints_Name CONSTRAINTS TYPE,
attribute data type(size) CONSTRAINTS Constraints_Name CONSTRAINTS TYPE,
attribute data type(size) CONSTRAINTS Constraints_Name CONSTRAINTS TYPE
)";
Just Try with that SQL Query

function table_exists($ref, $base, $table) {
	$request = "SHOW TABLES WHERE Tables_in_{$base} = '{$table}'";
	$response = mysql_query($request, $ref);
	return (mysql_num_rows($response) > 0);
}

Edited 5 Years Ago by Vonzarovitzch: n/a

This article has been dead for over six months. Start a new discussion instead.