/*
pdo属性介绍如下:
1.pdo连接mysql数据库
new pdo("mysql:host=localhost;dbname=db_demo","root","");
默认不是长连接,若要使用数据库长连接,需要在最后加如下参数:
new pdo("mysql:host=localhost;dbname=db_demo","root","","array(pdo::attr_persistent => true) ");
2.pdo常用方法及其应用
pdo::query() 主要是用于有记录结果返回的操作,特别是select操作
pdo::exec() 主要是针对没有结果集合返回的操作,如insert、update等操作
pdo::lastinsertid() 返回上次插入操作,主键列类型是自增的最后的自增id
pdostatement::fetch() 是用来获取一条记录
pdostatement::fetchall() 是获取所有记录集到一个中
*/
//pdo操作数据库插入操作
$pdo=new pdo("mysql:host=localhost;dbname=regi","root","qwert123");
var_dump($pdo);
if($pdo->exec("insert into username(id,member_user) values(4,'123456')")){
echo "插入成功";
echo $pdo->lastinsertid();
}else{
echo "插入失败";
}
//查询操作
$pdo = new pdo("mysql:host=localhost;dbname=regi","root","qwert123");
$rs = $pdo -> query("select * from num");
while($row = $rs -> fetch()){
print_r($row);
}
?>
object(pdo)#1 (0) { } 插入失败
fatal error: call to a member function fetch() on a non-object in e:\awangzhansheji\ilfol\reg\reg\1.php on line 29
$pdo=new PDO("mysql:host=localhost;dbname=regi","root","qwert123"); 这个错误提示并不是连不上数据库。
是查询结果为空,而你没做是否有结果到判断直接就用fetch()获取,导致报错。
这个错误提示并不是连不上数据库。
是查询结果为空,而你没做是否有结果到判断直接就用fetch()获取,导致报错。
插入失败是sql语句错误,有可能是没这个表,也可能没这个字段,也有可能是已经有ID为4的,插入不进去。
查询的应该是没有num表
这是我的数据库
pbo新手,谢谢大神回答
弄了很久都没弄明白
用这个吧~
class Pdo{
private $instance;
public function __construct()
{
$dns = 'mysql:host=localhost;dbname=数据库;charset=utf8';
$user = 'root';
$pwd = '123456';
$this->instance = new \PDO($dns, $user, $pwd,
array(\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8',
\PDO::ATTR_AUTOCOMMIT=>0));
}
public function __destruct()
{
// TODO: Implement __destruct() method.
$this->instance = null;
}
public function query($sql){
return $this->instance->query($sql)->fetchAll();
}
}
用这个吧~
class Pdo{
private $instance;
public function __construct()
{
$dns = 'mysql:host=localhost;dbname=数据库;charset=utf8';
$user = 'root';
$pwd = '123456';
$this->instance = new \PDO($dns, $user, $pwd,
array(\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8',
\PDO::ATTR_AUTOCOMMIT=>0));
}
public function __destruct()
{
// TODO: Implement __destruct() method.
$this->instance = null;
}
public function query($sql){
return $this->instance->query($sql)->fetchAll();
}
}
这是我的数据库
pbo新手,谢谢大神回答
弄了很久都没弄明白
Cannot redeclare class Pdo
重复类名了。
这是我的数据库
pbo新手,谢谢大神回答
弄了很久都没弄明白
问题已解决,感谢Novolee的答案,就是这个问题!!我新手
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号