简体   繁体   中英

Data won't save into MySQL database

I can connect to my DB, but nothing saves into it. In the section where it is suppose to save it into the DB, it echos "New User" and the $sql line with the data that should be saved. Can anyone see why this shouldn't be saving my data?

$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 Schema: http://gyazo.com/ef9badc3ae72b73557ed80efe2413ea3

You didn't execute the INSERT sql statement. You can use the following statement after $sql :

$result = mysqli_query($sql);

Make sure you read the $result and do appropriate things, eg:

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

There it goes.

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

As in your codes the $sql has not been executed, it will print only the variable. Execute it first.

Execute insert query. Try this snippet in your code.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM