在函数 php 中使用 if 语句和 pdo 查询获取记录
get record using if statment & pdo query in function php
我的 pdo 函数有问题,当它从数据库中获取 1 条记录时,结果为空;
connect.php
<?php
class dbConn{
protected static $db;
private function __construct() {
try {
self::$db = new PDO( 'mysql:host=localhost;dbname=item', 'root', '' );
self::$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch (PDOException $e) {
echo "Connection Error " . $e->getMessage();
}
}
public static function getConnection() {
if (!self::$db) {
new dbConn();
}
return self::$db;
}
}
?>
function.php
<?php
include 'connect.php';
class ajax_table {
function detailitem($table){
$db = dbConn::getConnection();
$sql = "select * from ".$table."" or die(mysql_error());
$q = $db->query($sql) or die("failed!");
$res = $q->fetch(PDO::FETCH_ASSOC);
return $res;
//else echo "No records found";
}
}
?>
并显示
displayitem.php
<?php
$url = $_GET['url'];
$url=$url.'.html';
include 'connect.php';
include 'function.php';
$db = dbConn::getConnection();
$obj = new ajax_table();
$records = $obj->detailitem('product WHERE url = "$url"');
if($records){
echo $records['name'];
echo '<br>';
echo $records['type'];
}else{
echo 'no result';
} ?>
数据库不为空,有结果显示
没有错误,也不显示任何东西
如果你看对了下面一行:
$records = $obj->detailitem('product WHERE url = "$url"');
它将字符串作为 "$url" 传递,而不是 $url
变量的值。
因此将其更改为:
$records = $obj->detailitem('product WHERE url = \''.$url.'\'');
我的 pdo 函数有问题,当它从数据库中获取 1 条记录时,结果为空;
connect.php
<?php
class dbConn{
protected static $db;
private function __construct() {
try {
self::$db = new PDO( 'mysql:host=localhost;dbname=item', 'root', '' );
self::$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch (PDOException $e) {
echo "Connection Error " . $e->getMessage();
}
}
public static function getConnection() {
if (!self::$db) {
new dbConn();
}
return self::$db;
}
}
?>
function.php
<?php
include 'connect.php';
class ajax_table {
function detailitem($table){
$db = dbConn::getConnection();
$sql = "select * from ".$table."" or die(mysql_error());
$q = $db->query($sql) or die("failed!");
$res = $q->fetch(PDO::FETCH_ASSOC);
return $res;
//else echo "No records found";
}
}
?>
并显示
displayitem.php
<?php
$url = $_GET['url'];
$url=$url.'.html';
include 'connect.php';
include 'function.php';
$db = dbConn::getConnection();
$obj = new ajax_table();
$records = $obj->detailitem('product WHERE url = "$url"');
if($records){
echo $records['name'];
echo '<br>';
echo $records['type'];
}else{
echo 'no result';
} ?>
数据库不为空,有结果显示 没有错误,也不显示任何东西
如果你看对了下面一行:
$records = $obj->detailitem('product WHERE url = "$url"');
它将字符串作为 "$url" 传递,而不是 $url
变量的值。
因此将其更改为:
$records = $obj->detailitem('product WHERE url = \''.$url.'\'');