dongtu1789 2012-12-05 00:06
浏览 54
已采纳

Postgresql INSERT INTO使用PHP无法正常工作

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 :(";
    }
}
  • 写回答

2条回答 默认 最新

  • dongmen9517 2012-12-05 00:14
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等