DIM3NSION
DIM3NSION

Reputation: 1761

Entering Array's into table PHP

im pulling in data from an rss feed, i want to add the title and description into the same row (different fields) in a mysql database

$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

I'm loading the information into variables but don't understand how i can insert this into a mysql table called data?

It sounds easy but im struggling as its an array.

Upvotes: 1

Views: 98

Answers (3)

user1191247
user1191247

Reputation: 12998

You will need to change the node names but this should do it -

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

Upvotes: 1

Trey
Trey

Reputation: 5520

Assuming your table is set up with columns that are named "title" and "description" have you tried something like this?

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

EDIT: fair enough;) added mysql_real_escape_string

Upvotes: 0

Dr.Kameleon
Dr.Kameleon

Reputation: 22810

Try something along these lines : (UPDATED)

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

Upvotes: 2

Related Questions