将数组输入PHP表

时间:2012-04-14 01:37:02

标签: php mysql arrays insert

我从rss feed中提取数据,我想将标题和描述添加到mysql数据库的同一行(不同的字段)

$result = $xml->xpath('//title');  //finding the title tags in the xml document and loading into variable
$result1 = $xml->xpath('//description');  //finding the title tags in the xml document and loading into variable

我正在将信息加载到变量中,但不明白我如何将其插入到名为data的mysql表中?

这听起来很容易,但我正在挣扎作为一个阵列。

3 个答案:

答案 0 :(得分:2)

尝试以下几点:(更新)

<?php
    $con = mysql_connect("localhost","yourdbusername","yourdbpassword");
    if (!$con)
    {
        die('Could not connect: ' . mysql_error());
    }

    mysql_select_db("yourdbname", $con);

    $query = sprintf("INSERT INTO `data` (`title`, `description`) VALUES ('%s','%s');",
                         mysql_real_escape_string($result),
                         mysql_real_escape_string($result1));

    mysql_query($query);

    mysql_close($con);
?>

答案 1 :(得分:1)

您需要更改节点名称,但应该这样做 -

<?php
$db = new PDO('mysql:dbname=test;host=127.0.0.1', 'user', 'pass');

$sql = "INSERT INTO tbl (title, description) VALUES (?, ?)";
$stmt = $db->prepare($sql);

$rss = simplexml_load_file('path_to_rss_feed');

foreach ($rss->articles as $article) {
    $stmt->execute(array($article->title, $article->description));
}

答案 2 :(得分:0)

假设您的表设置了名为“title”和“description”的列,您是否尝试过类似的内容?

$rows=array();

foreach($result as $title){
  $rows[]="('".mysql_real_escape_string($title)."','".mysql_real_escape_string(array_shift($result1))."')");
}
mysql_query("INSERT INTO data (title, description) VALUES ".implode(',',$rows);

编辑:足够公平;)添加了mysql_real_escape_string