MySql连接

时间:2015-12-30 21:31:58

标签: php mysql

    <?php
// connect to MySQL
 $connect = new PDO ("localhost", "username", "")
 or die ( "Hey loser, check your server connection");

 // make sure we`re using the right database 
 mysql_select_db ( "moviesite");

 // insert data into "movie" table
 $insert= "INSERT INTO movie (movie_id, movie_name, movie_type,
    movie_year, movie leadactor, movie_director)".
"VALUES (1, 'Bruce Almighty', 5 , 2003, 1, 2), " .
"(2, 'Office Space', 5, 1999, 5, 6),".
"(3, 'Grand Canyon', 2, 1991, 4, 3)";
$results = mysql_query($insert)
or die (mysql_error());

// insert data into "movietype" table
$type = "INSERT INTO movietype (movietype_id, movietype_label) ".
"VALUES (1, 'Sci Fi'), " .
"(2, 'Drama'), " . 
"(3, 'Adventure'),".
"(4, 'War'),".
"(5,'Comedy'),".
"(6, 'Horror'),".
"(7,'Action'),".
"(8,'Kids')";
$results = mysql_query($type)
or die (mysql_error());
// insert data into "people" table
$people = "INSERT INTO people (people_id, people_fullname, " .
    "people_isactor, people_isdirector) " . 
"VALUES (1, 'Jim Carrey', 1, 0), " . 
"(2, 'Tom Shadyac', 0, 1), " .
"(3, 'Lawrence Kasdan', 0, 1) , " .
"(4, 'Kevin Kline', 1, 0), " .
"(5, 'Ron Livingston', 1, 0), " .
"(6, 'Mike Judge', 0, 1)"; 
$results = mysql_query($people)
or die (mysql_error());
echo "Data inserted succsesfully!";
?> 
嘿伙计们。我有个问题。当我运行此代码时,我收到此错误:

( ! ) Fatal error: Uncaught exception 'PDOException'

带有消息

'invalid data source name' in C:\wamp\www\moviedata.php on line 3 ( ! ) PDOException: invalid data source name in C:\wamp\www\moviedata.php on line 3

如果有人可以帮我解决这个问题,我会很感激。

2 个答案:

答案 0 :(得分:2)

您正在致电

mysql_select_db ( "moviesite");

但这不是PDO的一部分,它是MySQL的一部分。

你应该这样做:

$DB_HOST = "";
$DB_NAME = "";
$DB_PASS = "";
$DB_PORT = 3306;
$DB_USER = "";

$dsn = "mysql:host=" . $DB_HOST . ";port=" . $DB_PORT . ";dbname=" . $DB_NAME . ";charset=utf8";

$db_connection = new PDO($dsn, $DB_USER, $DB_PASS);

答案 1 :(得分:2)

不要混合使用mysql_ *函数和PDO 检查PDO_MySQL DSN

的语法
<?php
$pdo = new PDO('mysql:host=localhost;dbname=moviesite;charset=utf8', 'username', '', array(
    PDO::ATTR_EMULATE_PREPARES=>false,
    PDO::MYSQL_ATTR_DIRECT_QUERY=>false,
    PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));

$pdo->exec("
    INSERT INTO movie
        (movie_id, movie_name, movie_type, movie_year, movie leadactor, movie_director)
    VALUES
        (1, 'Bruce Almighty', 5 , 2003, 1, 2),
        (2, 'Office Space', 5, 1999, 5, 6),
        (3, 'Grand Canyon', 2, 1991, 4, 3)
");
// and so on and on