我对PHP PDO和MariaDB有一个奇怪的问题。 如果我使用用户“root”(默认用户)创建一个View:
-- Create the first table
CREATE TABLE `tableA` (
`id` TINYINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(10) NOT NULL
);
INSERT INTO `tableA` (`name`) VALUES ('a');
-- Create the second table
CREATE TABLE `tableB` (
`id` TINYINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`id_A` TINYINT UNSIGNED NOT NULL,
`data` VARCHAR(10) NOT NULL
);
INSERT INTO `tableB` (`id_A`, `data`) VALUES ('1', '...');
-- The view...
CREATE OR REPLACE VIEW `table_view` AS SELECT a.id, a.name, b.data FROM tableA a, tableB b WHERE a.id=b.id_a;
然后我更改“root”名称:
RENAME USER 'root'@'localhost' TO 'uroot'@'localhost';
RENAME USER 'root'@'127.0.0.1' TO 'uroot'@'127.0.0.1';
RENAME USER 'root'@'::1' TO 'uroot'@'::1';
然后当我尝试选择视图时出现错误的登录错误:
Error: SQLSTATE[HY000]: General error: 1449 The user specified as a definer ('root'@'localhost') does not exist.
我可以访问tableA和tableB但我无法访问table_view。为什么?要纠正错误,我必须重新创建视图:
CREATE OR REPLACE VIEW `table_view` AS SELECT a.id, a.name, b.data FROM tableA a, tableB b WHERE a.id=b.id_a;
完整示例:
<?php
define('DB_USER', 'uroot');
define('DB_PASSWRD', 'root');
define('DB_DBNAME', 'test');
// SQL Script.
/*
-- Create the first table
CREATE TABLE `tableA` (
`id` TINYINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(10) NOT NULL
);
INSERT INTO `tableA` (`name`) VALUES ('a');
-- Create the second table
CREATE TABLE `tableB` (
`id` TINYINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`id_A` TINYINT UNSIGNED NOT NULL,
`data` VARCHAR(10) NOT NULL
);
INSERT INTO `tableB` (`id_A`, `data`) VALUES ('1', '...');
-- The view...
CREATE OR REPLACE VIEW `table_view` AS SELECT a.id, a.name, b.data FROM tableA a, tableB b WHERE a.id=b.id_a;
-- Rename "root"
RENAME USER 'root'@'localhost' TO 'uroot'@'localhost';
RENAME USER 'root'@'127.0.0.1' TO 'uroot'@'127.0.0.1';
RENAME USER 'root'@'::1' TO 'uroot'@'::1';
-- Now you can execute the PHP script
*/
$_db = null;
// Connection
try {
$_db = new PDO('mysql:host=localhost;dbname='.DB_DBNAME, DB_USER, DB_PASSWRD, array(PDO::ATTR_PERSISTENT => false));
$_db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}catch( PDOException $e ){
echo 'Error : ',$e->getMessage(),'<br />',"\n"
,'N° : ',$e->getCode(),"\n";
exit();
}
// Make a SQL Query
$sql = 'SELECT * FROM table_view;';
try {
$res = $_db->prepare($sql);
$res->execute();
$res->setFetchMode(PDO::FETCH_ASSOC);
echo '<pre>';
while( ($row=$res->fetch()) !== false )
{
var_export($row);
}
echo '</pre>';
}catch( PDOException $e ){
echo 'Error: ',$e->getMessage(),'<br />',"\n"
,'N°: ',$e->getCode(),"\n"
,'REQ SQL: ',$sql,'<br />',"\n";
exit;
}
?>