2017-09-23 84 views
1

我剛剛拿到了使用preg_match_all陣列插入我試圖使用此代碼將其插入到表:如何在數據庫中的陣列得到通過preg_match_all

$casturl = "https://www.themoviedb.org/movie/353491-the-dark-tower/cast"; 
$cast = file_get_contents($casturl); 
preg_match_all('#<img class="profile lazyload fade" data-sizes="auto" data-src="(.*?)" data-srcset="#' , $cast , $castimg);  
print_r($castimg[1]); 

$escaped_values = array_map('mysql_real_escape_string', array_values($castimg)); 
$values = implode(", ", $escaped_values); 
$sql = "INSERT INTO test (content) VALUES ('$values')"; 

但我在得到什麼我的數據庫,我想這可能是因爲它不是一個普通的數組,我不知道,我不是很有經驗的PHP。

+0

你不應該使用正則表達式解析HTML DOM文檔使用的HTML解析器。 –

回答

0

下面是一個例子,如何將數據在mysql中添加表:

<?php 
session_start(); 
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING); 


// mysql settings change here !!! 
$mdatabase = 'sun'; 
$muser = 'root'; 
$mpass = 'toor'; 
$mhost = 'localhost'; 
$mport = 3306; 


$casturl = "https://www.themoviedb.org/movie/353491-the-dark-tower/cast"; 
$cast = file_get_contents($casturl); 
preg_match_all('#<img class="profile lazyload fade" data-sizes="auto" data-src="(.*?)" data-srcset="#' , $cast , $castimg);  
echo "<pre>"; 
print_r($castimg[1]); 

try{ 
    // Connect to database 
    $db = Conn(); 

    // Add all links 
    foreach ($castimg[1] as $key => $val) { 
     // save to db 
     saveLink($val); 
    } 
}catch(Exception $e){ 
    print_r($e); 
} 

// Add link function 
function saveLink($link){ 
    global $db; 
    if (!empty($link)) { 
     $link = htmlentities($link,ENT_QUOTES,'UTF-8'); 
     $r = $db->query("INSERT INTO test(content) VALUES('$link')"); 
     // last inserted id if you had auto increment primary key id (int or bigint) 
     $id = $db->lastInsertId(); 
     return $id; 
    }else{ 
     return 0; 
    } 
} 

// connect to mysql with PDO function 
function Conn(){ 
    global $mhost,$mport,$muser,$mpass,$mdatabase; 
    $connection = new PDO('mysql:host='.$mhost.';port='.$mport.';dbname='.$mdatabase.';charset=utf8', $muser, $mpass); 
    // don't cache query 
    $connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); 
    // show warning text 
    $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); 
    // throw error exception 
    $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    // don't colose connecion on script end 
    $connection->setAttribute(PDO::ATTR_PERSISTENT, false); 
    // set utf for connection utf8_general_ci or utf8_unicode_ci 
    $connection->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8' COLLATE 'utf8_general_ci'"); 
    return $connection; 
} 

// end script 
die(); 
?> 

見PHP的信息擴展:

<?php 
    phpinfo(); 
?> 
+0

你需要在php.ini中擴展PDO(我不知道它是默認取消註釋)嘗試使用phpinfo();並看到它在php:pdo_mysql中啓用 – 2017-09-23 11:40:41