我试图在一个查询中插入大量的post meta,但如果我在其中使用变量,它将不会插入数据。
这是我目前的代码。我补充道comments 在…上which codes work &;which does not.
(请忽略无消毒/准备,这是一个本地主机测试项目):
$imdbid = $_GET[\'id\'];
$string = file_get_contents("http://www.omdbapi.com/?i=".$imdbid."&apikey=9a187152");
$json = json_decode($string, true);
if( $json[\'Response\'] === "True" ){
$dataID = $json[\'imdbID\'];
$dataTitle = $json[\'Title\'];
$dataYear = $json[\'Year\'];
$dbdata = array(
\'post_title\' => $dataID,
\'post_status\' => \'publish\',
\'post_type\' => \'datadb\',
\'post_author\' => 1
);
if( $dbid = wp_insert_post( $dbdata ) ){
//ECHO TEST TO MAKING SURE THE VARIABLES ARE WORKING
echo $dataID;
echo $dataTitle;
echo $dataYear;
(VARIABLES ARE WORKING)
//#1 THIS DOES NOT WORK
$wpdb->query("INSERT INTO wp_postmeta
(post_id, meta_key, meta_value)
VALUES
($dbid, \'datadb_imdb_id\', $dataID),
($dbid, \'datadb_title\', $dataTitle),
($dbid, \'datadb_year\', $dataYear);");
//#2 BUT THIS WORK
$wpdb->query("INSERT INTO wp_postmeta
(post_id, meta_key, meta_value)
VALUES
($dbid, \'datadb_imdb_id\', \'tt6334354\'),
($dbid, \'datadb_title\', \'The Suicide Squad\'),
($dbid, \'datadb_year\', \'2021\');");
}
}
为什么当我使用变量作为自定义sql查询的值时,没有插入任何内容?
(Refer to #1)但当我直接进入它时,它会。(Refer to #2)
最合适的回答,由SO网友:Amenadiel 整理而成
Huge thanks to @kero !!
我最终能够创建一个解决方案,首先将sql语句设置为变量(正如kero所建议的),然后在
wpdb->query();
Here\'s my updated and fully working codes now:
$imdbid = $_GET[\'id\'];
$string = file_get_contents("http://www.omdbapi.com/?i=".$imdbid."&apikey=9a187152");
$json = json_decode($string, true);
if( $json[\'Response\'] === "True" ){
$dataID = $json[\'imdbID\'];
$dataTitle = $json[\'Title\'];
$dataYear = $json[\'Year\'];
$dbdata = array(
\'post_title\' => $dataID,
\'post_status\' => \'publish\',
\'post_type\' => \'datadb\',
\'post_author\' => 1
);
if( $dbid = wp_insert_post( $dbdata ) ){
$statement = "INSERT INTO wp_postmeta (post_id, meta_key, meta_value) VALUES (\'".$dbID."\', \'datadb_imdb_id\', \'%s\'), (\'".$dbID."\', \'datadb_title\', \'%s\');";
$sql = $wpdb->prepare($statement, $dataID, $dataTitle);
$wpdb->query($sql);
}
}