我在解决一些简单的PHP代码以在MySQL表中插入记录时遇到困难.
直接输入WAMP的代码工作正常:
INSERT INTO `users` (`userName`,`userEmail`) VALUES ('orange','orange@gmail.com')
Run Code Online (Sandbox Code Playgroud)
这个PHP代码不起作用:
<?php
    $dbHost="localhost";
    $dbName="project";
    $dbUser="admin";
    $dbPassword="abcd";
    $dbh=new PDO("mysql:host=$dbHost;dbName=$dbName", $dbUser, $dbPassword);
    print_r($dbh);
    echo "</br>";
    print_r($dbh->errorInfo());
    $query=$dbh->prepare("INSERT INTO users (userName, userEmail) VALUES (?,?)");
    echo "</br>";
    print_r(var_dump($query->errorInfo()));
    echo "</br>";
    print_r($query->errorCode());
    echo "</br>";
    print_r($dbh->errorInfo());
    $query->bindValue(1, 'apple');
    echo "</br>";
    print_r(var_dump($query->errorInfo()));
    echo "</br>";
    print_r($query->errorCode());
    echo "</br>";
    print_r($dbh->errorInfo());
    $query->bindValue(2, 'apple@gmail.com');
    echo "</br>";
    print_r(var_dump($query->errorInfo()));
    echo "</br>";
    print_r($query->errorCode());
    echo "</br>";
    print_r($dbh->errorInfo());
    $inserted=$query->execute(); //True if succesful, False if not.
    echo "</br>";
    print_r(var_dump($query->errorInfo()));
    echo "</br>";
    print_r($query->errorCode());
    echo "</br>";
    print_r($dbh->errorInfo());
    echo "</br>";
    if ($inserted){print_r("true");}else{print_r("false");};
?>
Run Code Online (Sandbox Code Playgroud)
我执行页面时得到的是以下打印输出:
PDO Object ( )
Array ( [0] => [1] => [2] => )
array(3) { [0]=> string(0) "" [1]=> NULL [2]=> NULL }
Array ( [0] => 00000 [1] => [2] => )
array(3) { [0]=> string(0) "" [1]=> NULL [2]=> NULL }
Array ( [0] => 00000 [1] => [2] => )
array(3) { [0]=> string(0) "" [1]=> NULL [2]=> NULL }
Array ( [0] => 00000 [1] => [2] => )
array(3) { [0]=> string(5) "3D000" [1]=> int(1046) [2]=> string(20) "No database selected" }
3D000
Array ( [0] => 00000 [1] => [2] => )
false
Run Code Online (Sandbox Code Playgroud)
该记录未插入数据库中.我做错了什么?我不确定我应该在print_r中看到什么,我将它们作为响应者的帮助.
谢谢,
JDelage
编辑 - 我在评论中添加了print_r.
这是我在WAMP中看到的:
该错误消息似乎表明您已正常连接到数据库,但尚未选择项目数据库。
为了确保它尝试使用正确的 DSN 进行纠正,我会尝试更改连接字符串以直接包含值,而不是变量,即:
'mysql:host=localhost;dbname=project'
Run Code Online (Sandbox Code Playgroud)
这应该没有什么区别,但值得检查。
如果这不起作用,并且由于您似乎能够连接到 MySQL,因此解决方法可能是将数据库名称作为查询的一部分包含在内。所以你上面的查询将变成:
$query=$dbh->prepare("INSERT INTO project.users (userName, userEmail) VALUES (?,?)");
Run Code Online (Sandbox Code Playgroud)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           3624 次  |  
        
|   最近记录:  |