我一直在尝试将pg_connect查询转换为PDO,因为pg_connect会给我错误。以下是我遇到的错误。
<?php
if (!empty($_GET)) {
$searchfilters = array(
"name" => "data.name || ' ' || data.lastname ILIKE " . $dbh->quote("%".getvar("name")."%"),
"room" => "data.room = " . $dbh->quote(getvar("room")),
"activity" => "data.activity = " . $dbh->quote(getvar("activity")),
"date1" => "data.dob > " . $dbh->quote(getvar("date1")),
"date2" => "data.dob < " . $dbh->quote(getvar("date2")),
"date3" => "data.joinDate > " . $dbh->quote(getvar("date3")),
"date4" => "data.joinDate < " . $dbh->quote(getvar("date4")),
"date5" => "data.lastSeen > " . $dbh->quote(getvar("date5")),
"date6" => "data.lastSeen < " . $dbh->quote(getvar("date6")),
);
$wherequery = array();
foreach ($searchfilters as $n => $q) {
$v = getvar($n);
if (!empty($v)) {
$wherequery[] = $q;
}
}
$query = "SELECT DISTINCT data.id, data.name, lastname, paging, room, activity
FROM data";
if (count($wherequery) > 0) {
$query .= " WHERE " . (getvar("invert") == "on" ? " NOT " : "") . "(" . implode(" and ", $wherequery) . ")";
}
$query .= " ORDER BY lastname;";
$result = pg_query($connection, $query) or
die(_("Error in query") . ": $query." . pg_last_error($connection));
if (pg_num_rows($result) == 0) {
echo '<div class="alert alert-error">
<a class="close" data-dismiss="alert" href="#">×</a>
<h4 class=\"alert-heading\">' . _('No results') . '</h4>
</div>';
} else {
echo '<table class="table">
<thead>
<tr>
<script language="JavaScript">
function toggle(source) {
checkboxes = document.getElementsByName(\'foo\');
for(var i in checkboxes)
checkboxes[i].checked = source.checked;
}
</script>
<th><input type="checkbox" onClick="toggle(this)"></th>
<th>' . _("Name") . '</th>
<th>' . _("Activity") . '</th>
<th>' . _("Room") . '</th>
<th>' . _("Paging") . '</th>
</tr>
</thead>
<tbody>';
while ($row = pg_fetch_assoc($result)) {
echo '<tr><td style="width:30px"><input type="checkbox" name="foo"></td>';
echo "<td><a href=\"details.php?id={$row["id"]}\">{$row["name"]} {$row["lastname"]}</a></td>";
echo '<td>' . $activities[$row["activity"]] . '</td>';
echo '<td>' . $rooms[$row["room"]] . '</td>';
echo '<td>' . $row["paging"] . '</td>';
echo '</tr>';
}
echo '</tbody></table>';
}
}
?>
我认为,$result = pg_query($connection, $query) or
die(_("Error in query") . ": $query." . pg_last_error($connection));
这一行是给我带来麻烦的部分。
我徒劳地试过以下当然不起作用的。
<?php
if (!empty($_GET)) {
$searchfilters = array(
"name" => "data.name || ' ' || data.lastname ILIKE " . $dbh->quote("%".getvar("name")."%"),
"room" => "data.room = " . $dbh->quote(getvar("room")),
"activity" => "data.activity = " . $dbh->quote(getvar("activity")),
"date1" => "data.dob > " . $dbh->quote(getvar("date1")),
"date2" => "data.dob < " . $dbh->quote(getvar("date2")),
"date3" => "data.joinDate > " . $dbh->quote(getvar("date3")),
"date4" => "data.joinDate < " . $dbh->quote(getvar("date4")),
"date5" => "data.lastSeen > " . $dbh->quote(getvar("date5")),
"date6" => "data.lastSeen < " . $dbh->quote(getvar("date6")),
);
$wherequery = array();
foreach ($searchfilters as $n => $q) {
$v = getvar($n);
if (!empty($v)) {
$wherequery[] = $q;
}
}
$query = "SELECT DISTINCT data.id, data.name, lastname, paging, room, activity
FROM data";
if (count($wherequery) > 0) {
$query .= " WHERE " . (getvar("invert") == "on" ? " NOT " : "") . "(" . implode(" and ", $wherequery) . ")";
}
$query .= " ORDER BY lastname;";
//$result = pg_query($connection, $query) or
// die(_("Error in query") . ": $query." . pg_last_error($connection));
$sth = $dbh->query('$query');
while ($result = $sth->fetch(PDO::FETCH_ASSOC)) {
if (pg_num_rows($result) == 0) {
echo '<div class="alert alert-error">
<a class="close" data-dismiss="alert" href="#">×</a>
<h4 class=\"alert-heading\">' . _('No results') . '</h4>
</div>';
} else {
echo '<table class="table">
<thead>
<tr>
<script language="JavaScript">
function toggle(source) {
checkboxes = document.getElementsByName(\'foo\');
for(var i in checkboxes)
checkboxes[i].checked = source.checked;
}
</script>
<th><input type="checkbox" onClick="toggle(this)"></th>
<th>' . _("Name") . '</th>
<th>' . _("Activity") . '</th>
<th>' . _("Room") . '</th>
<th>' . _("Paging") . '</th>
</tr>
</thead>
<tbody>';
while ($row = pg_fetch_assoc($result)) {
echo '<tr><td style="width:30px"><input type="checkbox" name="foo"></td>';
echo "<td><a href=\"details.php?id={$row["id"]}\">{$row["name"]} {$row["lastname"]}</a></td>";
echo '<td>' . $activities[$row["activity"]] . '</td>';
echo '<td>' . $rooms[$row["room"]] . '</td>';
echo '<td>' . $row["paging"] . '</td>';
echo '</tr>';
}
echo '</tbody></table>';
}}
}
?>
如果您还有其他需要,请告诉我。我不是非常流利的PHP,我正在尝试运行一个开源应用程序,并且有一些功能需要一些TLC才能工作。任何帮助将不胜感激。
编辑:这是整个页面。
原始查询是
$sth = $dbh->query('$query');
while ($data = $sth->fetch(PDO::FETCH_ASSOC))
echo "<option value=\"{$data[id]}\">
我尝试将其更改为:
<!DOCTYPE html>
<!-- vim: tabstop=2:softtabstop=2 -->
<?php
require_once "config.php";
require_once 'functions.php';
//internationalisation
$domain = "search";
require_once 'locale.php';
function getvar($vname) {
return array_key_exists($vname, $_POST) ? $_POST[$vname] : $_GET[$vname];
}
$dbh = db_connect();
$connection = pg_connect ("host=$dbhost dbname=$dbname user=$dbuser password=$dbpass");
$page_title = _("Advanced Search");
require_once "template/header.php";
?>
<!-- sidebar -->
<div class="span3">
<div class="well sidebar-nav">
<ul class="nav nav-list">
<li class="nav-header"><?php echo _("Search") ?></li>
<li><a href="search.php"><i class="icon-search"></i><?php echo _("Search") ?></a></li>
<li class="active"><a href="#"><i class="icon-filter"></i><?php echo _("Advanced") ?></a></li>
<li><a href="#"><i class="icon-bookmark"></i><?php echo _("Saved Searches") ?></a></li>
</ul>
<ul class="nav nav-list">
<li class="nav-header"><?php echo _("Actions") ?></li>
<li><a href="register.php"><i class="icon-plus-sign"></i><?php echo _("Register") ?></a></li>
<li><a href="#"><i class="icon-user"></i><?php echo _("Register Visitor") ?></a></li>
<li><a href="#"><i class="icon-print"></i><?php echo _("Print Results") ?></a></li>
<li><a href="#"><i class="icon-download-alt"></i><?php echo _("Download Results") ?></a></li>
</div>
</div>
<!-- /sidebar -->
<div class="span9">
<!-- Search form -->
<form class="well form-horizontal" method="get">
<fieldset>
<div class="control-group">
<label class="control-label" for="name"><?php echo _("Name contains") ?></label>
<div class="controls">
<input type="text" class="input" name="name" id="name" placeholder="<?php echo _("Name") ?>" value="<?php echo getvar("name"); ?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="room"><?php echo _("and room is") ?></label>
<div class="controls">
<select name="room" id="room">
<option value="" selected><?php echo _("Any Room") ?></option>
<?php
$sth = $dbh->query('SELECT id, name FROM rooms');
while ($data = $sth->fetch(PDO::FETCH_ASSOC))
echo "<option value=\"{$data[id]}\">{$data[name]}</option>\n";
?>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="room"><?php echo _("and class is") ?></label>
<div class="controls">
<select name="activity" id="activity">
<option value="" selected><?php echo _("Any Class") ?></option>
<?php
echo (is_null($edata["activity"]) ? "<option disabled selected>" .
_("Class") . "</option>\n" : "");
$sth = $dbh->query('SELECT id, name FROM activities');
while ($data = $sth->fetch(PDO::FETCH_ASSOC)) {
echo "<option value=\"{$data["id"]}\"" .
($data["id"] == $edata["activity"] ? " selected" : "") .
">{$data["name"]}</option>\n";
}
?>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="medical"><?php echo _("and was born") ?></label>
<div class="controls">
<?php echo _("after") ?> <input type="text" class="input-small" name="date1" id="date1" value="<?php echo getvar("date1"); ?>">
<?php echo _("and before") ?> <input type="text" class="input-small" name="date2" id="date2" value="<?php echo getvar("date2"); ?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="medical"><?php echo _("and joined") ?></label>
<div class="controls">
<?php echo _("after") ?> <input type="text" class="input-small" name="date3" id="date3" value="<?php echo getvar("date3"); ?>">
<?php echo _("and before") ?> <input type="text" class="input-small" name="date4" id="date4" value="<?php echo getvar("date4"); ?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="medical"><?php echo _("and last seen") ?></label>
<div class="controls">
<?php echo _("after") ?> <input type="text" class="input-small" name="date5" id="date5" value="<?php echo getvar("date5"); ?>">
<?php echo _("and before") ?> <input type="text" class="input-small" name="date6" id="date6" value="<?php echo getvar("date6"); ?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="medical"><?php echo _("Invert query") ?></label>
<div class="controls">
<input type="checkbox" name="invert" id="invert" <?php echo (getvar("invert") == "on" ? "checked" : ""); ?>>
</div>
</div>
<div class="form-actions">
<input type="submit" class="btn btn-primary" value="<?php echo _("Search") ?>" />
<input type="reset" class="btn" value="<?php echo _("Reset") ?>">
</div>
</fieldset>
</form>
<?php
if (!empty($_GET)) {
$searchfilters = array(
"name" => "data.name || ' ' || data.lastname ILIKE " . $dbh->quote("%".getvar("name")."%"),
"room" => "data.room = " . $dbh->quote(getvar("room")),
"activity" => "data.activity = " . $dbh->quote(getvar("activity")),
"date1" => "data.dob > " . $dbh->quote(getvar("date1")),
"date2" => "data.dob < " . $dbh->quote(getvar("date2")),
"date3" => "data.joinDate > " . $dbh->quote(getvar("date3")),
"date4" => "data.joinDate < " . $dbh->quote(getvar("date4")),
"date5" => "data.lastSeen > " . $dbh->quote(getvar("date5")),
"date6" => "data.lastSeen < " . $dbh->quote(getvar("date6")),
);
$wherequery = array();
foreach ($searchfilters as $n => $q) {
$v = getvar($n);
if (!empty($v)) {
$wherequery[] = $q;
}
}
$query = "SELECT DISTINCT data.id, data.name, data.lastname, data.paging, data.room, data.activity
FROM data";
if (count($wherequery) > 0) {
$query .= " WHERE " . (getvar("invert") == "on" ? " NOT " : "") . "(" . implode(" and ", $wherequery) . ")";
}
$query .= " ORDER BY data.lastname;";
// $sth = $dbh->query('$query');
// while ($data = $sth->fetch(PDO::FETCH_ASSOC))
// echo "<option value=\"{$data[id]}\">{$data[name]}</option>\n";
$result = pg_query($connection, $query) or
die(_("Error in query") . ": $query." . pg_last_error($connection));
if (pg_num_rows($result) == 0) {
echo '<div class="alert alert-error">
<a class="close" data-dismiss="alert" href="#">×</a>
<h4 class=\"alert-heading\">' . _('No results') . '</h4>
</div>';
} else {
echo '<table class="table">
<thead>
<tr>
<script language="JavaScript">
function toggle(source) {
checkboxes = document.getElementsByName(\'foo\');
for(var i in checkboxes)
checkboxes[i].checked = source.checked;
}
</script>
<th><input type="checkbox" onClick="toggle(this)"></th>
<th>' . _("Name") . '</th>
<th>' . _("Activity") . '</th>
<th>' . _("Room") . '</th>
<th>' . _("Paging") . '</th>
</tr>
</thead>
<tbody>';
while ($row = pg_fetch_assoc($result)) {
echo '<tr><td style="width:30px"><input type="checkbox" name="foo"></td>';
echo "<td><a href=\"details.php?id={$row["id"]}\">{$row["name"]} {$row["lastname"]}</a></td>";
echo '<td>' . $activities[$row["activity"]] . '</td>';
echo '<td>' . $rooms[$row["room"]] . '</td>';
echo '<td>' . $row["paging"] . '</td>';
echo '</tr>';
}
echo '</tbody></table>';
}
}
?>
</div>
</div>
<script>
window.onload = function(){
for(i = 1; i <= 6; i++) {
new JsDatePick({
useMode:2,
target:("date" + i),
dateFormat:"%Y-%m-%d",
imgPath:"resources/img/datepicker"
});
}
};
</script>
<?php require_once "template/footer.php" ; ?>
记录结果:
< 2015-06-21 17:48:10.712 CDT >LOG: database system is ready to accept connections
< 2015-06-21 17:48:10.712 CDT >LOG: autovacuum launcher started
配置文件:
#------------------------------------------------------------------------------
# ERROR REPORTING AND LOGGING
#------------------------------------------------------------------------------
# - Where to Log -
log_destination = 'stderr' # Valid values are combinations of
# stderr, csvlog, syslog, and eventlog,
# depending on platform. csvlog
# requires logging_collector to be on.
# This is used when logging to stderr:
logging_collector = on # Enable capturing of stderr and csvlog
# into log files. Required to be on for
# csvlogs.
# (change requires restart)
# These are only used if logging_collector is on:
log_directory = 'pg_log' # directory where log files are written,
# can be absolute or relative to PGDATA
log_filename = 'postgresql-%a.log' # log file name pattern,
# can include strftime() escapes
#log_file_mode = 0600 # creation mode for log files,
# begin with 0 to use octal notation
log_truncate_on_rotation = on # If on, an existing log file with the
# same name as the new log file will be
# truncated rather than appended to.
# But such truncation only occurs on
# time-driven rotation, not on restarts
# or size-driven rotation. Default is
# off, meaning append to existing files
# in all cases.
log_rotation_age = 1d # Automatic rotation of logfiles will
# happen after that time. 0 disables.
log_rotation_size = 0 # Automatic rotation of logfiles will
# happen after that much log output.
# 0 disables.
# These are relevant when logging to syslog:
#syslog_facility = 'LOCAL0'
#syslog_ident = 'postgres'
# This is only relevant when logging to eventlog (win32):
#event_source = 'PostgreSQL'
# - When to Log -
client_min_messages = notice # values in order of decreasing detail:
# debug5
# debug4
# debug3
# debug2
# debug1
# log
# notice
# warning
# error
log_min_messages = error # values in order of decreasing detail:
# debug5
# debug4
# debug3
# debug2
# debug1
# info
# notice
# warning
# error
# log
# fatal
# panic
log_min_error_statement = error # values in order of decreasing detail:
# debug5
# debug4
# debug3
# debug2
# debug1
# info
# notice
# warning
# error
# log
# fatal
# panic (effectively off)
#log_min_duration_statement = -1 # -1 is disabled, 0 logs all statements
# and their durations, > 0 logs only
# statements running at least this number
# of milliseconds
# - What to Log -
#debug_print_parse = off
#debug_print_rewritten = off
#debug_print_plan = off
#debug_pretty_print = on
#log_checkpoints = off
#log_connections = off
#log_disconnections = off
#log_duration = off
log_error_verbosity = default # terse, default, or verbose messages
#log_hostname = off
log_line_prefix = '< %m >' # special values:
# %a = application name
# %u = user name
# %d = database name
# %r = remote host and port
# %h = remote host
# %p = process ID
# %t = timestamp without milliseconds
# %m = timestamp with milliseconds
# %i = command tag
# %e = SQL state
# %c = session ID
# %l = session line number
# %s = session start timestamp
# %v = virtual transaction ID
# %x = transaction ID (0 if none)
# %q = stop here in non-session
# processes
# %% = '%'
# e.g. '<%u%%%d> '
#log_lock_waits = off # log lock waits >= deadlock_timeout
#log_statement = 'none' # none, ddl, mod, all
#log_temp_files = -1 # log temporary files equal or larger
# than the specified size in kilobytes;
# -1 disables, 0 logs all temp files
log_timezone = 'America/Indiana/Tell_City'
#------------------------------------------------------------------------------
# RUNTIME STATISTICS
#------------------------------------------------------------------------------
# - Query/Index Statistics Collector -
#track_activities = on
#track_counts = on
#track_io_timing = off
#track_functions = none # none, pl, all
#track_activity_query_size = 1024 # (change requires restart)
#update_process_title = on
#stats_temp_directory = 'pg_stat_tmp'
# - Statistics Monitoring -
#log_parser_stats = off
#log_planner_stats = off
#log_executor_stats = off
#log_statement_stats = off
#------------------------------------------------------------------------------
# AUTOVACUUM PARAMETERS
#------------------------------------------------------------------------------
#autovacuum = on # Enable autovacuum subprocess? 'on'
# requires track_counts to also be on.
#log_autovacuum_min_duration = -1 # -1 disables, 0 logs all actions and
# their durations, > 0 logs only
# actions running at least this number
# of milliseconds.
#autovacuum_max_workers = 3 # max number of autovacuum subprocesses
# (change requires restart)
#autovacuum_naptime = 1min # time between autovacuum runs
#autovacuum_vacuum_threshold = 50 # min number of row updates before
# vacuum
#autovacuum_analyze_threshold = 50 # min number of row updates before
# analyze
#autovacuum_vacuum_scale_factor = 0.2 # fraction of table size before vacuum
#autovacuum_analyze_scale_factor = 0.1 # fraction of table size before analyze
#autovacuum_freeze_max_age = 200000000 # maximum XID age before forced vacuum
# (change requires restart)
#autovacuum_multixact_freeze_max_age = 400000000 # maximum Multixact age
# before forced vacuum
# (change requires restart)
#autovacuum_vacuum_cost_delay = 20ms # default vacuum cost delay for
# autovacuum, in milliseconds;
# -1 means use vacuum_cost_delay
#autovacuum_vacuum_cost_limit = -1 # default vacuum cost limit for
# autovacuum, -1 means use
# vacuum_cost_limit
#------------------------------------------------------------------------------
# CLIENT CONNECTION DEFAULTS
#------------------------------------------------------------------------------
# - Statement Behavior -
#search_path = '"$user",public' # schema names
#default_tablespace = '' # a tablespace name, '' uses the default
#temp_tablespaces = '' # a list of tablespace names, '' uses
# only default tablespace
#check_function_bodies = on
#default_transaction_isolation = 'read committed'
#default_transaction_read_only = off
#default_transaction_deferrable = off
#session_replication_role = 'origin'
#statement_timeout = 0 # in milliseconds, 0 is disabled
#lock_timeout = 0 # in milliseconds, 0 is disabled
#vacuum_freeze_min_age = 50000000
#vacuum_freeze_table_age = 150000000
#vacuum_multixact_freeze_min_age = 5000000
#vacuum_multixact_freeze_table_age = 150000000
#bytea_output = 'hex' # hex, escape
#xmlbinary = 'base64'
#xmloption = 'content'
# - Locale and Formatting -
datestyle = 'iso, mdy'
#intervalstyle = 'postgres'
timezone = 'America/Indiana/Tell_City'
#timezone_abbreviations = 'Default' # Select the set of available time zone
# abbreviations. Currently, there are
# Default
# Australia (historical usage)
# India
# You can create your own file in
# share/timezonesets/.
#extra_float_digits = 0 # min -15, max 3
#client_encoding = sql_ascii # actually, defaults to database
# encoding
# These settings are initialized by initdb, but they can be changed.
lc_messages = 'en_US.UTF-8' # locale for system error message
# strings
lc_monetary = 'en_US.UTF-8' # locale for monetary formatting
lc_numeric = 'en_US.UTF-8' # locale for number formatting
lc_time = 'en_US.UTF-8' # locale for time formatting
# default configuration for text search
default_text_search_config = 'pg_catalog.english'
# - Other Defaults -
#dynamic_library_path = '$libdir'
#local_preload_libraries = ''
#------------------------------------------------------------------------------
# LOCK MANAGEMENT
#------------------------------------------------------------------------------
#deadlock_timeout = 1s
#max_locks_per_transaction = 64 # min 10
# (change requires restart)
# Note: Each lock table slot uses ~270 bytes of shared memory, and there are
# max_locks_per_transaction * (max_connections + max_prepared_transactions)
# lock table slots.
#max_pred_locks_per_transaction = 64 # min 10
# (change requires restart)
#------------------------------------------------------------------------------
# VERSION/PLATFORM COMPATIBILITY
#------------------------------------------------------------------------------
# - Previous PostgreSQL Versions -
#array_nulls = on
#backslash_quote = safe_encoding # on, off, or safe_encoding
#default_with_oids = off
#escape_string_warning = on
#lo_compat_privileges = off
#quote_all_identifiers = off
#sql_inheritance = on
#standard_conforming_strings = on
#synchronize_seqscans = on
# - Other Platforms and Clients -
#transform_null_equals = off
#------------------------------------------------------------------------------
# ERROR HANDLING
#------------------------------------------------------------------------------
#exit_on_error = off # terminate session on any error?
#restart_after_crash = on # reinitialize after backend crash?
#------------------------------------------------------------------------------
# CONFIG FILE INCLUDES
#------------------------------------------------------------------------------
# These options allow settings to be loaded from files other than the
# default postgresql.conf.
#include_dir = 'conf.d' # include files ending in '.conf' from
# directory 'conf.d'
#include_if_exists = 'exists.conf' # include file only if it exists
#include = 'special.conf' # include file
#------------------------------------------------------------------------------
# CUSTOMIZED OPTIONS
#------------------------------------------------------------------------------
# Add settings for extensions here