【问题标题】:Data won't save into MySQL database数据不会保存到 MySQL 数据库中
【发布时间】:2015-04-17 08:25:58
【问题描述】:

我可以连接到我的数据库,但没有保存任何内容。在假设将其保存到数据库中的部分中,它会回显“新用户”和 $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";
}

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

【问题讨论】:

  • 你没有执行插入查询
  • 你只是回显$sql,但不执行它。
  • 你只显示变量$sql,你忘了放查询执行命令

标签: php mysql database pdo


【解决方案1】:

到此为止。

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";
        }

【讨论】:

    【解决方案2】:

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

    $result = mysqli_query($sql);
    

    确保您阅读$result 并做适当的事情,例如:

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

    【讨论】:

      【解决方案3】:

      在您的代码中 $sql 尚未执行,它只会打印变量。先执行吧。

      【讨论】:

        【解决方案4】:

        执行插入查询。在你的代码中试试这个 sn-p。

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

        【讨论】:

          猜你喜欢
          • 2011-01-19
          • 2011-02-04
          • 1970-01-01
          • 2019-01-22
          • 1970-01-01
          • 2016-08-01
          • 2011-09-17
          • 1970-01-01
          • 2020-07-15
          相关资源
          最近更新 更多