数据存储在数据库中,如图所示。该表格为products
。
http://i.stack.imgur.com/YCQwu.jpg
文本格式数据,例如:test.txt
products_model products_price
LB2117 19.49
LB2381 25.99
LB2307
LB2380 35.99
LB2468 10.99
LB2139
LB2223 12.99
LB2027 15.99
LB2126 12.99
LB2308 9.99
LB2124 13.99
...........
现在,我想要使用txt文件更新products_price
,products_model
是唯一的,如果'test.txt is empty. using
0`中的products_price要填充。
php代码:
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'pwd';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('products');
$sql = 'UPDATE products
SET products_price="..."
WHERE products_model=...';
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
?>
如果更新一行,我知道该怎么做?但如何使用txt或csv文件更新价格?
答案 0 :(得分:2)
test.txt
0
转换为PHP代码(无错误检查):
$file = fopen("test.txt","r");
while($line = fgets($file)) {
$line = trim($line);
list($model,$price) = preg_split('/\s+/',$line);
if(empty($price)) {
$price = 0;
}
$sql = "UPDATE products
SET products_price=$price
WHERE products_model='$model'";
// run the sql query.
}
fclose($file);
此外,您还必须跳过第一条记录。