通过PHP将字典值保存到SQL数据库的BLOB值中

问题描述:

I have a dictionary of ratings (i.e.: ["volleyball":5, "soccer":4, "football":3]) that I want to upload to an already existing user database through my php script running on my app. In other words, I have a blob value called "ratings" in my sql database that is part of table User that I am trying to update. For some reason, I keep receiving the error message: "The data couldn’t be read because it isn’t in the correct format". I have been working on this for the past 6 hours or so and haven't gotten anywhere. Any help would be great! Thanks.

I have this function in my "MySQLDao.php" script.

public function addRatingsToUser($email, $ratings) {
    $serialized_data = serialize($ratings);
    $sql = "UPDATE User SET ratings=? WHERE email=?";
    $statement = $this->$conn->prepare($sql);

    if (!$statement) throw new Exception($statement->error);

    $statement->bind_param("ss", $serialized_data, $email);
    $returnValue = $statement->execute();

    return $returnValue;
}

And this is my main php script, "addUserRatings.php":

<?php

require 'Conn.php';
require 'MySQLDao.php';

$data = json_decode(file_get_contents('php://input'), true);
$returnValue = array();

$email = $data["email"];
$ratings = $data["ratings"];

$returnValue["status"]  = "empty";
$returnValue["message"] = "empty";

$dao = new MySQLDao();
$dao->openConnection();

$result = $dao->addRatingsToUser($email, $ratings);
if ($result) {
    $returnValue["status"] = "success";
    $returnValue["message"] = "Ratings have been added to the existing user.";

    echo json_encode($returnValue);
    return;
}

echo json_encode($returnValue);

$dao->closeConnection();

?>

And here is my swift code:

@IBAction func submitRatings(sender:UIButton!) {
        let userEmail = "scott.tkdmaster@mac.com"
        let ratingsDictionary:[String:Int] = ["volleyball":Int(self.volleyballRating.text!)!, "soccer":Int(self.soccerRating.text!)!, "football":Int(self.footballRating.text!)!]

        let myURL = NSURL(string: "http://155.246.193.177:8888/addUserRatings.php")
        let request = NSMutableURLRequest(URL: myURL!)
        request.HTTPMethod = "POST"

        let param = ["email":userEmail, "ratings":ratingsDictionary]
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        do {
            request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(param, options: NSJSONWritingOptions.PrettyPrinted)
        } catch _ {
            print("An error occurred with JSONSerialization.dataWithJSONObject")
        }


        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
            if error != nil {
                print("

Error, \(error?.localizedDescription)")
                return;
            }

            print("

Response = \(response)")

            do {
                let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
                if let parseJSON = json {
                    print("

Status = \(parseJSON["status"])")
                    print("

Message = \(parseJSON["message"])")
                    print("

Return Value = \(parseJSON["json"])")
                }
                else {
                    print("

The json object was nil, something went wrong. Maybe the server isn't running?")
                }
            } catch let err as NSError {
                print("

Error with do, \(err.localizedDescription)")
                print("

Data: \(data)")
            }
        }

        task.resume()
    }

So, classic syntax error... in my addRatingsToUser function, instead of

$statement = $this->$conn->prepare($sql);

It should be

$statement = $this->conn->prepare($sql);

There was a dollar sign before the conn.