使用PDO进行连接 [英] Connection using PDO

查看:70
本文介绍了使用PDO进行连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚开始使用PDO.请向我解释连接中的错误.它始终显示您已连接".

Just started working with PDO.Please explain me the error in my connectivity.It always shows "You are connected".

    <?php

       define('user','root');
       define('pass','');
       define('db','login_db');

       try
          {
       $dbh = new PDO("mysql:host = localhost; dbname = db",user,pass);
       echo "You are connected";
          }
       catch(PDOException $e)
          {
       echo $e -> getMessage(); 
          }
    ?>

还提供了一些您了解的PDO教程或电子书.预先感谢.

Also provide with some tutorial or ebook for PDO you aware with. Thanks in advance.

推荐答案

此问题是由数据源名称(DSN)(PDO连接字符串中的第一个参数)中的2个语法错误引起的.

The problem is caused by 2 syntax errors in your Data Source Name (DSN) (the first argument in the PDO connection string).

  1. 您不能将db常量作为"...dbname = db"传递到连接字符串中.由于db用双引号引起来,将被解释为字符串而不是常量.
  2. DSN中不能有空格.应该是:

  1. You cannot pass your db constant into the connection string as "...dbname = db". Since db is wrapped in double quotes and will be interpretted as a string instead of a constant.
  2. You cannot have spaces in your DSN. It should be:

"mysql:host=localhost;dbname=login_db" //no spaces.

我已经测试过了,它表现出一些奇怪的行为:

I've tested this and it exhibits some strange behaviour:

  • 具体来说,似乎host和第一个=符号之间的空格导致了此问题.如果有空格,即使"localhost"拼写错误,它也会回显"You are connected".
  • 类似地,如果dbname及其=符号之间有空格,即使指定的数据库名称不正确,它也将似乎已连接.
  • Specifically, it seems that the space between host and the first = sign causes the problem. If there is a space, it will echo "You are connected" even if "localhost" is misspelled.
  • Similarly, if there is a space between dbname and its = sign, it will appear to connect even if the specified database name is incorrect.

我的猜测是,这与PDO类如何解析DSN有关.

My guess is that this is some quirk of how the PDO class parses the DSN.

从DSN中删除所有空格.

Remove all the spaces from the DSN.

您还需要以其他方式传递数据库名称.有多种解决方法.为了避免出现更多奇怪的调试错误,我建议您使用变量而不是常量定义:

You also need to pass in your database name in a different way. There are different ways to fix this. I would recommend, for the sake of not getting any more weird-to-debug-errors, that you use variables instead of constant definitions:

$host = 'localhost';
$user = 'root';
$pass = '';
$db   = 'login_db';

try{
    $dbh = new PDO("mysql:host=$host;dbname=$db",$user,$pass);
    echo "You are connected";
}
catch(PDOException $e){
    echo $e -> getMessage(); 
}


关于好的教程,您可以查看以下内容:


As for good tutorials, you can look at these:

Net.tuts +:PHP数据库访问

净.tuts +:为什么要使用PDO

当然,不要忘记php.net文档.

And of course the don't forget the php.net docs.

php.net:PDO

这篇关于使用PDO进行连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆