-1

I have a script that checks if a table exists and if it does not then it creates one. The table gets create fine and the data goes in correctly. Once a table has been created and encounters the script I use the test again. However it always returns true and runs the create table script.Can anyone explain why.

<?php
include 'config.php';
$scriptot = ($_POST["ohyeah"]);
$scriptname = ($_POST["scriptname"]);
$y = 1;
$scriptnamed = "".$scriptname."equip";
$r= 1;
$scriptot = $scriptot + 1;

echo $scriptnamed;


$val = mysql_query("select 1 from specifics");
echo $val;
if($val !== FALSE)
{
    echo 'its there';
}
else
{
   echo 'No table Found';//always runs this even if exists
// sql to create table
$sql1 = "CREATE TABLE specifics (
ID int NOT NULL AUTO_INCREMENT,
 equiplist varchar(255),
 stage varchar(255),

PRIMARY KEY (ID)
)";
}
Fintan Creaven
  • 250
  • 2
  • 17

2 Answers2

1

You are never actually executing the CREATE query, at least not in this code snippet. This should mean that your SELECT query is always running on a non-existent table.

mysql_query($sql1);

Furthermore, if all you want to do with your SELECT is to check if a table exists or not, have a look at this answer for a cleaner way: https://stackoverflow.com/a/1525801/4652136

Community
  • 1
  • 1
Erik Johansson
  • 1,646
  • 1
  • 14
  • 19
0

In your IF statement, your query returns 1. Then so $val=1. So by substitution in your IF statement 1!==FALSE which is definitely true. Thus it will always run echo 'its there';.

$val = mysql_query("select 1 from specifics");
echo $val;
if($val !== FALSE)
{
    echo 'its there';
}
else
{
   echo 'No table Found';

Try this:

$val = mysql_query("SELECT COUNT(*)
                    FROM information_schema.tables
                    WHERE table_schema = 'YOUR_DATABASE_NAME_HERE' 
                    AND table_name = 'specifics';");
echo $val;
if($val == 1)
{
    echo 'its there';
}
else
{
   echo 'No table Found';
Rigel1121
  • 2,022
  • 1
  • 17
  • 24