数据不会保存到 MySQL 数据库中

Data won't save into MySQL database

我可以连接到我的数据库,但没有任何内容保存到其中。在假设将其保存到数据库的部分中,它回显 "New User" 和 $sql 行以及应保存的数据。谁能看出为什么这不应该保存我的数据?

$dbh = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
//$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

if($dbh){
echo "Connected successfully";
}else{
    die("Connection failed: " . mysqli_connect_error());
}
if(isset($_SESSION['steamid'])) {
include ('steamauth/userInfo.php');
        if (!empty($steamprofile['steamid'])) {
             $stmt = $dbh->prepare("SELECT count(*) from user WHERE steam_id = :steam_id");
            $stmt->bindValue(':steam_id', $steamprofile['steamid']);
            $stmt->execute();
            $count = $stmt->fetchColumn();
        }
//Row will return false if there was no value
        if ($count == 0) {
            //insert new data
            echo "New user";
            $sql = "INSERT INTO user (display_name, user_url, steam_id, profile_image)
    VALUES ('$steamprofile[personaname]', '$steamprofile[profileurl]', $steamprofile[steamid], '$steamprofile[avatar]')";
            echo($sql);
        //  die();
        } else {
            //User exist
            echo "User exists";
        }

}else{
echo "no user signed in";
}

Table 架构:http://gyazo.com/ef9badc3ae72b73557ed80efe2413ea3

因为在你的代码中 $sql 没有被执行,它只会打印变量。先执行一下。

您没有执行 INSERT sql 语句。可以在$sql后使用如下语句:

$result = mysqli_query($sql);

确保您已阅读 $result 并采取适当的措施,例如:

if($result === true) {
   // success
} else {
   // failed
}

执行插入查询。在您的代码中试试这个片段。

try {
        $stmt = $db->prepare($query);
        $result = $stmt->execute($query_params);
    } catch (PDOException $ex) {
      }

到此为止。

if ($count == 0) {
            echo "New user";
            $sql = "INSERT INTO user (display_name, user_url, steam_id, profile_image)
    VALUES ('$steamprofile[personaname]', '$steamprofile[profileurl]', $steamprofile[steamid], '$steamprofile[avatar]')";
            $dbh->query($sql); // You missed that line of code.
            echo($sql); // This will only echo out your query, not the result.
        } else {
            //User exist
            echo "User exists";
        }