简体   繁体   English

从数组中检索值以存储在表中

[英]Retrieve values from an array to store inside a table

I have the following array of data that is dumped on my site from Twitter. 我有以下数据从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: 鉴于您的变量已经是一个数组,并且非常适合prepare()语句,请执行以下操作:

$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 : 这就像这样做,这就是我们通常在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). 假设您的数组的名称是:$ access_token,它具有值(非空)。

$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. 首先, user_id应该是一个整数,因为它只是数字。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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