What is wrong here? I get the table usertable fine. I've made sure that the column name uid is there. But when I try to get uids from a query, nothing comes back. That is fine as the table is empty. However, my INSERT INTO command is not working because after the INSERT INTO, I still don't have uids coming back. Using Postgres 9.1.5. Thanks!
$query = "SELECT * FROM information_schema.tables WHERE table_name = 'usertable';";
$result = pg_query($dbconn, $query);
if (pg_num_rows($result))
{
echo "Table exists<br>";
checkForUserRow();
}
else
{
echo "Error on query, attempting to create table<br>";
$sql = "CREATE TABLE usertable (uid integer PRIMARY KEY, sign varchar(255));";
pg_query($dbconn, $sql) or die(pg_errormessage());
$result = pg_query($dbconn,$query);
if (pg_num_rows($result)) {
echo "Table created<br>";
checkForUserRow();
}
}
pg_close($conn);
function checkForUserRow()
{
$query = "SELECT uid FROM usertable WHERE uid = '123'";
$result = pg_query($dbconn, $query);
if(pg_num_rows($result))
{
echo "User DB row exists<br>";
}
else
{
echo "User row does not exist - attempt to add user to table<br/>";
$sql = "INSERT INTO usertable (uid) VALUES('123')";
pg_query($dbconn, $sql);
$result = pg_query($dbconn, $query);
if (pg_num_rows($result))
{
echo "User successfully added!<br/>";
}
else
{
echo "User not added :(";
}
}
Inside your function, you need to get the global $dbconn
:
function checkForUserRow()
{
global $dbconn;
// everything else
}
This is because when you do pg_query($dbconn, $query);
inside of the function, it's using the local version of $dbconn, which doesn't exist.
You can also choose to pass in $dbconn as a parameter if you wish:
function checkForUserRow($dbconn)
{
// global $dbconn; // Don't need this anymore.
// everything else
}
If you start with an empty table, then this:
if (pg_num_rows($result))
will always evaluate as false. This means you will always try to create a new table (which will fail since table exists triggering die(pg_errormessage());
.
This means checkForUserRow()
will never be called.
Even if it was called, $dbconn
doesn't exist in the scope of your checkForUserRow()
function, meaning none of your queries will ever work in this function.
Rudimentary debugging and review of error messages on your part would show you how your execution path is not working properly.
Also this line of code:
pg_close($conn);
refers to a different variable name for the DB connection then used elsewhere.