由于新项目的服务器要求,我离开mysqli_query()后,我是PDO的新手(如小时)。但是我在更新一些查询时遇到了问题。
连接文件
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'nj2kfa3j_sublift');
define('DB_USER', 'nj2kfa3j_web');
define('DB_PASS', 'prum9wR4');
define('DB_CHAR', 'utf8');
class DB
{
protected static $instance = null;
protected function __construct() {}
protected function __clone() {}
public static function instance()
{
if (self::$instance === null)
{
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => FALSE,
);
$dsn = 'mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset='.DB_CHAR;
self::$instance = new PDO($dsn, DB_USER, DB_PASS, $opt);
}
return self::$instance;
}
public static function __callStatic($method, $args)
{
return call_user_func_array(array(self::instance(), $method), $args);
}
public static function run($sql, $args = [])
{
if (!$args)
{
return self::instance()->query($sql);
}
$stmt = self::instance()->prepare($sql);
$stmt->execute($args);
return $stmt;
}
}
?>
问题查询声明:
$stmt = DB::run("SELECT * FROM admin WHERE username='$manager' AND password='$password' LIMIT 1");
$existCount = $stmt->fetchColumn();
if ($existCount == 1){
$id;
$full_name;
var_dump($stmt);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$id = $row["id"];
$full_name = $row["full_name"];
echo 'test';
}
}
我已经或多或少地以相同的方式完成了其他查询,并且他们正在工作,如下所示:
$stmt = DB::run("SELECT * FROM categories");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
就像我说的,我是新手,所以不确定这里发生了什么,在var_dump()上面的查询中返回:
object(PDOStatement)#2 (1) { ["queryString"]=> string(81) "SELECT * FROM admin WHERE username='********' AND password='********' LIMIT 1" }
但是它没有进入while循环并且点击了回声&#39;测试&#39 ;;
对此的任何帮助将不胜感激。
答案 0 :(得分:1)
请使用预备语句,您的功能旨在接受预先准备好的语句,也不要将您的密码存储为纯文本,请使用password_hash()
和password_verify()
您可以使用fetchall()
将数据作为数组获取,然后计算数组元素。
<?php
$params = [$manager,$password];
$sql = "SELECT * FROM admin WHERE username= ? AND password= ? LIMIT 1";
$stmt = DB::run($sql,$params);
$results = $stmt->fetchall(PDO::FETCH_ASSOC); //returns an array
if (count($results) > 0){
$id;
$full_name;
foreach($results as $key=>$row){
$id = $row["id"];
$full_name = $row["full_name"];
echo 'test';
}
}
?>
答案 1 :(得分:-1)
正如评论中所讨论的,我一直在寻找mysqli_num_rows()的替代方案,并找到了rowCount()。
以下内容现在对我有用:
$stmt = DB::run("SELECT * FROM admin WHERE username='$manager' AND password='$password' LIMIT 1");
$existCount = $stmt->rowCount();
if ($existCount == 1){