我正在将一个 php 应用程序移动到一个新的网络服务器上。 在原始服务器中,以下代码可以正常工作,但它不在新服务器中。
$request=$connexion->prepare("SELECT * FROM access_control ");
$request->execute();
$request2=$connexion->prepare("SELECT * FROM tplmail ");
$request2->execute();`
第一个请求总是有效的。我试图反转这两个请求,但脚本总是在第二个 execute
处停止。在其他脚本中,存在同样的问题,我无法在同一页面中执行两次execute
。
最佳答案
您的问题 #1 是缺少错误报告。如果看不到错误消息,您将无法执行任何操作
为了能够看到数据库错误,必须设置PDO errmode异常(exception)。异常在很多方面都优于常规错误:它们总是包含堆栈跟踪,它们可以使用 try..catch 捕获或使用专用错误处理程序处理。即使未处理,它们也会作为常规 PHP 错误提供所有重要信息,遵循站点范围的错误报告设置。
请注意,将此模式设置为连接选项也会让 PDO 在连接错误时抛出异常,这一点非常重要。
因此,这是一个以正确方式创建 PDO 连接的示例:
$dsn = "mysql:host=$host;dbname=$db;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
// other options
);
$pdo = new PDO($dsn, $user, $pass, $opt);
以这种方式连接,您将始终收到查询执行期间发生的所有数据库错误的通知。请注意,您必须能够看到一般的 PHP 错误。在实时站点上,您必须查看错误日志,因此必须进行设置
error_reporting(E_ALL);
ini_set('display_errors',0);
ini_set('log_errors',1);
在本地开发服务器上,在屏幕上出现错误是可以的:
error_reporting(E_ALL);
ini_set('display_errors',1);
当然,您永远不应该在 PDO 语句前使用错误抑制运算符 (@
)。
此外,由于许多糟糕的示例告诉您将每个 PDO 语句包装到 try..catch
block 中,因此我必须明确说明:
DO NOT use try..catch operator just to echo an error message. Uncaught exception is already excellent for this purpose, as it will act just the same way as other PHP errors - so, you can define the behavior using site-wide settings - so, you will have your error message without this useless code. While unconditionally echoed error message may reveal some sensitive information to a potential attacker, yet confuse a honest visitor.
- A custom exception handler could be added later, but not required. Especially for new users, it is recommended to use unhandled exceptions, as they are extremely informative, helpful and secure.
- Use
try..catch
only if you are going to handle the error itself - say, to rollback a transaction.
您的问题 #2 是 buffering state这会阻止执行第二个查询。
添加
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE,
初始化数组应该可以解决问题
或者您可以在触发第二个查询之前从第一个查询中获取所有数据
关于PHP-PDO-Mysql : Can't execute two requests in the same page,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17834392/