这部分用于通过API收集我的数据。
foreach($result['List'] as $feedback)
{
$date = date_create();
$date_entered = $feedback['DateEntered'];
$time = preg_replace('/[^0-9]/','',$date_entered);
//$comment = $feedback['Text'];
$ListingId = $feedback['ListingId'];
$BuyNowPrice = $feedback['BuyNowPrice'];
$max_bid = $feedback['MaximumBidAmount'];
$SellerId = $feedback['SellerId'];
echo '<div>' . "Seller ID: $SellerId" . " has sold one $ListingId for " . '$' . "$BuyNowPrice" . '</div>';
echo "<div>Feedback created at " . $time . "</div>";
echo '<br>';
}
这部分是我在检索它们之后直接插入到我的结果中的代码。
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'INSERT INTO tmfeedback '.
'(SellerId,ListingId,BuyNowPrice) '.
'VALUES ('.$SellerId.', '.$ListingId.', '.$BuyNowPrice.'))';
mysql_select_db('dctdb3');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
?>
只有一个数据被插入数据库,它是最后显示的数据。 我想知道如何更改我的代码,以便我可以同时插入所有数据而不重复? 谢谢你的帮助。
答案 0 :(得分:0)
确保您的第二个代码块位于第一个代码块内(将第二个块放在右大括号上方)。然后,它将在foreach循环的每次迭代(每个结果)中发生,并为每个迭代插入一条记录。
答案 1 :(得分:0)
您无法将数组插入数据库,因此将查询放在循环中。这个thread可能对您有所帮助。
答案 2 :(得分:0)
将插入放入循环内。否则,变量只具有在循环的最后一次迭代中设置的最后一个值。
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('dctdb3');
foreach($result['List'] as $feedback) {
$date = date_create();
$date_entered = $feedback['DateEntered'];
$time = preg_replace('/[^0-9]/','',$date_entered);
//$comment = $feedback['Text'];
$ListingId = $feedback['ListingId'];
$BuyNowPrice = $feedback['BuyNowPrice'];
$max_bid = $feedback['MaximumBidAmount'];
$SellerId = $feedback['SellerId'];
echo '<div>' . "Seller ID: $SellerId" . " has sold one $ListingId for " . '$' . "$BuyNowPrice" . '</div>';
echo "<div>Feedback created at " . $time . "</div>";
echo '<br>';
$sql = 'INSERT INTO tmfeedback '.
'(SellerId,ListingId,BuyNowPrice) '.
'VALUES ('.$SellerId.', '.$ListingId.', '.$BuyNowPrice.'))';
$retval = mysql_query($sql);
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
}
echo "Entered data successfully<br>";
mysql_close($conn);