我正在使用以下代码查询数据库。
mysql_query ("SELECT * FROM _$symbol ORDER BY date DESC;");
$_10day = mysql_query ("SELECT AVG(close) FROM _$symbol limit 10;");
$_21day = mysql_query ("SELECT AVG(close) FROM _$symbol limit 21;");
$_50day = mysql_query ("SELECT AVG(close) FROM _$symbol limit 50;");
echo "$_10day\n";
echo "$_21day\n";
echo "$_50day\n";
mysql_query ("INSERT INTO _$symbol(_10day) VALUE ('$_10day');");
echo mysql_errno($sql) . ": " . mysql_error($sql). "\n";
我需要从数据库中获取close
的平均值,并且我正在使用AVG()
函数,然后将返回值插入数据库。查询在mysql中工作,但它们不能通过脚本工作。它确实在数据库中输入了一个值,但始终输入0
。我做错了什么?
编辑 - 找到解决方案
$get10 = mysql_query ("SELECT AVG( close ) AS CloseAverage from ( SELECT close FROM _$symbol ORDER BY date DESC limit 10 ) sub1 ;");
$row = mysql_fetch_assoc($get10);
$_10day = $row['CloseAverage'];
if (!mysql_query ("UPDATE _$symbol SET _10day = $_10day, _21day = $_21day, _50day = $_50day, _100day = $_100day, _120day = $_120day, _150day = $_150day, _200day = $_200day, _240day = $_240day, _20dayVol = $_20dayVol, _50dayVol = $_50dayVol where date = '$date';"))
{
echo "Update query failed";
}
我错误地查询它显然需要选择它作为子查询,解决方案在上面,它现在正在工作。
答案 0 :(得分:0)
$_10day
是一个mysql结果,而不是值。您不能只将结果放入查询字符串中并期望它能够正常工作。
您需要先获取结果数据,例如;
while($row = mysql_fetch_assoc($_10day)) {
$10day = $row['AVG(close)'];
}
然后你可以执行插入查询;
mysql_query ("INSERT INTO _$symbol (_10day) VALUES ('$10day')");
希望这有帮助。
答案 1 :(得分:0)
以下是有关如何管理多个结果行的示例:
function connect()
{
$db = mysql_connect("localhost","username","password") or die("your error msg");
mysql_select_db("database_name");
return $db;
}
$db = connect();
$query = "SELECT value1 FROM my_table";
$result = mysql_query($query, $db);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
// This one will loop through the data in your output//
$outputValue = $row['value1'];
}
用于插入数据:
// Continued from the state above //
$query = "INSERT INTO table_name (column1) VALUES (value1)";
$result = mysql_query($query, $db) or die(mysql_error());