我刚刚使用 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 不是很有经验。
最佳答案
这是一个如何向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();
?>
关于php - 如何在数据库中插入由 preg_match_all 获得的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46378769/