I have the following array of data that is dumped on my site from Twitter.
array(4) {
["oauth_token"]=> string(50) "19497918-McrcAAd1qrZwWaHljVPNbWVTSSrjolsybKwSXvtQ2"
["oauth_token_secret"]=> string(39) "Mixl5gYZjxQqzGhs1q0GoP9DDBwxVDWfBRgldJE"
["user_id"]=> string(8) "19497958"
["screen_name"]=> string(6) "Liam"
}
I want to somehow store this inside my table. My table structure is:
id | oauth_token | oauth_token_secret | user_id | screen_name
I am currently trying to insert my data with the following statement
$qry = $conn->prepare('INSERT INTO users (access_token) VALUES (?)');
$qry->execute(array($access_token));
However, this throws a page error and my page will no longer load. How can I correct this?
Given your variable already is an array and is perfect for a prepare()
statement, do this:
$qry = $conn->prepare('INSERT INTO users
(oauth_token, oauth_token_secret, user_id, screen_name)
VALUES (:oauth_token, :oauth_token_secret, :user_id, :screen_name)');
$qry->execute($access_token);
It's exactly like doing this, which is how we usually see prepared statements in PDO
:
$qry = $conn->prepare('INSERT INTO users SET (oauth_token, oauth_token_secret, user_id, screen_name) VALUES (:oauth_token, :oauth_token_secret, :user_id, :screen_name)');
$qry->execute(array(
'oauth_token' => "19497918-McrcAAd1qrZwWaHljVPNbWVTSSrjolsybKwSXvtQ2",
'oauth_token_secret' => "Mixl5gYZjxQqzGhs1q0GoP9DDBwxVDWfBRgldJE",
'user_id' => "19497958",
'screen_name' => "Liam"
));
Assuming the name of your array is: $access_token and it has values(not empty).
$qry = $conn->prepare('INSERT INTO users (access_token)
VALUES ($access_token["oauth_token"], $access_token["oauth_token_secret"],
$access_token["user_id"], $access_token["screen_name"])');
$qry->execute($access_token);
First off, the user_id
should probably be an integer since it's only numbers.
Your code should probably look something like this to work the way you want it to.
$userarray = array(4) {
["oauth_token"]=> string(50) "19497918-McrcAAd1qrZwWaHljVPNbWVTSSrjolsybKwSXvtQ2"
["oauth_token_secret"]=> string(39) "Mixl5gYZjxQqzGhs1q0GoP9DDBwxVDWfBRgldJE"
["user_id"]=> int(8) "19497958"
["screen_name"]=> string(6) "Liam"
}
$qry = $conn->prepare('INSERT INTO users (oauth_token, oauth_token_secret, user_id, screen_name) VALUES (:oauth_token, :oauth_token_secret, :user_id, :screen_name)');
$qry->execute($userarray);