对我上一篇文章感到抱歉。这是我的修订版,请帮助我。
<?php
//connect database
$sql = "SELECT * FROM user where user_id = 8320 AND password = 'admin' ";
$query = pg_query($sql);
var_dump($row = pg_fetch_array($query)); //dumps correctly.
?>
但问题就是这个......当我试着将它作为一个功能时:
function check($user_id, $password)
{
$sql = "SELECT * FROM user where user_id = $user_id AND password = '$password' ";
$query = pg_query($sql);
$row = pg_fetch_array($query);
return $row;
}
并在此处致电:
var_dump($data = check(8320, 'admin')); DUMPS NULL;
怎么会这样结束?
答案 0 :(得分:1)
它返回NULL
,因为您的SQL查询出错,并且没有返回任何结果。你应该在你的函数中做一些错误检查,试试这个版本:
function check($user_id, $password)
{
$dbconn = pg_connect("host=localhost dbname=test");
$sql = "SELECT * FROM user where user_id = $1 AND password = $2 ";
$result = pg_query_params($dbconn, $sql, array($user_id,$password));
$row = pg_fetch_array($result);
if (!$row) {
echo pg_last_error($dbconn);
} else {
return $row;
}
}
答案 1 :(得分:0)
尝试以下代码。它应该适合你。
$data = check(8320, 'admin');
var_dump($data);
答案 2 :(得分:0)
好像你的PostgreSQL资源在函数中缺失了。你有两个选择。
global
声明函数内的连接资源。这是第一个选择:
$conn = pg_connect('host','user','pass','db');
function check($user_id, $password)
{
global $conn;
$sql = "SELECT * FROM user where user_id = $user_id AND password = '$password' ";
$query = pg_query($conn, $sql);
$row = pg_fetch_array($query);
return $row;
}
这是第二个选择:
function check($user_id, $password)
{
$conn = pg_connect('host','user','pass','db');
$sql = "SELECT * FROM user where user_id = $user_id AND password = '$password' ";
$query = pg_query($conn, $sql);
$row = pg_fetch_array($query);
return $row;
}
根据PHP manual,您可以省略连接资源,但不建议这样做,因为它可能是难以在脚本中找到错误的原因。