2012-04-14 21 views
1

IM從RSS數據拉,我想補充的標題和描述到同一行(不同領域)在MySQL數據庫進入陣列的成表PHP

$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 

我加載信息到變量,但不明白我可以如何插入到一個稱爲數據的MySQL表?

這聽起來很容易,但即時通訊作爲一個數組掙扎。

+0

什麼是數組? – 2012-04-14 01:41:53

+0

您正在閱讀的RSS文件的結構是什麼?你在使用SimpleXML嗎? – nnichols 2012-04-14 02:04:40

回答

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); 
?> 
+0

@Amadan我更新了我的帖子,雖然你真的讓我想知道爲什麼答案是downvoted;說實話,我所嘗試的不是混淆OP(因爲他只是很困惑這個問題,已經......) – 2012-04-14 01:46:43

+1

因爲PHP不像現在這樣不安全,所以沒有人應該在沒有清楚理解的情況下觸摸SQL鮑比表的東西。教某人如何做MySQL,甚至沒有提到SQL注入是一件壞事(tm)。 – Amadan 2012-04-14 01:48:40

+0

@Amadan儘管如此,我的確同意你的觀點...... – 2012-04-14 01:49:27

0

假設你的表設置了列,其被命名爲「標題」和「說明」你嘗試過這樣的事情?

$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

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)); 
}