Mitch8910
Mitch8910

Reputation: 183

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

Upvotes: 1

Views: 2097

Answers (4)

C4d
C4d

Reputation: 3282

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

Upvotes: 1

Abhishek M
Abhishek M

Reputation: 88

Execute insert query. Try this snippet in your code.

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

Upvotes: 0

Raptor
Raptor

Reputation: 54212

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, e.g.:

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

Upvotes: 1

lakshman
lakshman

Reputation: 656

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

Upvotes: 0

Related Questions