用Flash通过PHP解析变量

用Flash通过PHP解析变量,php,mysql,actionscript-3,flash,chat,Php,Mysql,Actionscript 3,Flash,Chat,我正在用flash as3与php和mysql数据库聊天。 然而,我对php一无所知,在更新消息时遇到了问题。 目前,我的php文件如下所示: $caster = $_POST['caster']; $msgText = $_POST['msgText']; $sendTime = $_POST['sendTime']; $query = "INSERT INTO chat VALUES ('','$sendTime','$caster','$msgText')" mysql_query($q

我正在用flash as3与php和mysql数据库聊天。 然而,我对php一无所知,在更新消息时遇到了问题。 目前,我的php文件如下所示:

$caster = $_POST['caster'];
$msgText = $_POST['msgText'];
$sendTime = $_POST['sendTime'];

$query = "INSERT INTO chat VALUES ('','$sendTime','$caster','$msgText')"
mysql_query($query);
$query="SELECT * FROM chat";
$result=mysql_query($query);
$cast=mysql_result($result,1,"caster");
mysql_close();

$returnVars = array();
$returnVars['success'] = $success;
$returnVars['caster'] = $cast;
$returnString = http_build_query($returnVars);
echo $returnString;
我的问题是如何循环所有已经发送的聊天信息,将它们发送到flash。 我只能用一个来做,但我需要一整堆来装


谢谢

您要找的是“fetchAll”。请注意,您的代码对SQL注入开放,通过向PHP脚本传递恶意值,很容易删除数据库。因此,我将代码从不推荐使用的Mysql扩展更改为PDO。PDO将为您提供值的转义。 阅读PHP手册中关于PDO的更多内容(那里有很多示例)

还要注意,您必须修改以下代码,因为我猜不出数据库中聊天表的字段名是如何命名的。因此,您必须修改下面的insert语句

// database config parameters
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "";


try {

    // try to set up a db connection
    $db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);

    // insert the data using PDO's prepared statements
    // you have to adapt this line to the field names of your chat table!!
    $sql = "INSERT INTO chat (sendtime,caster,msg) VALUES (:sendtime,:caster,:msg)";
    $sth = $db->prepare($sql);
    $sth->execute(array(
         ':caster' => $_POST['caster'],
         ':sendtime' => $_POST['sendTime'],
         ':msg' => $_POST['msgText']
    ));


    // Get everything
    $sth = $db->prepare("SELECT * FROM chat");
    $sth->execute();
    $result = $sth->fetchAll(PDO::FETCH_ASSOC);
    // your code to format and return the data goes here 
    print json_encode($result);
}
catch (PDOException $e) {
    // if anything related to the database goes wrong, catch the exceptions
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

$db = null;
正如您所看到的,JSON没有特定的变量名,就像问题中使用的GET-used版本一样(问题中使用的方法不适用于大型结果列表)

那么,如何在Actionscript中使用JSON文档呢?我不是actionscript程序员,但这篇Stackoverflow文章似乎是这个问题的合理答案:


好的。但是我现在应该如何得到变量呢?我不知道他们的名字。请检查“print json_encode($result);”而不是print_r($result)是否适合与Actionscript结合使用。这将把关联数组转换为JSON,使用Actionscirpt.sooo遍历数组元素应该很容易,我将在as中得到名为result的数组?看看这里的示例:-结构如图所示。请注意,您可以对fetchAll使用不同的选项,这将影响数组的外观)。检查哪一个最适合您的用例。好的。谢谢但你能给我描述一下数组的名称吗?我真的不明白我应该指什么
[

   {

      "sendtime":"2013-04-14",

      "caster":"person1",

      "msg":"Message 1"

   },

   {

      "sendtime":"2013-04-15",

      "caster":"person2",

      "msg":"Message 2"

   }
]