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 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line