2015-11-03 126 views
1

我有两个脚本的结果/输出。如何将简单的PHP数组插入到MySQL表中?

脚本1结果:

print_r($unit); 

OUTPUT = 

Array ([0] => http://one.com, [1] => http://two.com, [2] => http://three.com/,) 

脚本2结果:

echo $item."<br>"; 

OUTPUT = 

http://one.com, 
http://two.com, 
http://three.com, 

我尴尬未能未能导入任何一个到MySQL表,只有两个字段:ID和URL 。

//Connect to MySQL... 

// Attempt insert query execution 

    $list=implode($unit); 

    $sql = "INSERT INTO urls (url) VALUES ('$list')"; 
    if(mysqli_query($conn, $sql)){ 
     echo "Records added successfully."; 
    } else{ 
     echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn); 
    } 

    // Close connection 
    mysqli_close($conn); 

插入件工作,但该代码插入所有3个网址为单个字段:

两个脚本1和2
id url 
1 http://one.com,http://two.com,http://three.com, 

DESIRED MySQL表的结果:

id url 
1 http://one.com 
2 http://two.com 
3 http://three.com 

感谢对于你的想法!

+0

'$名单=破灭(“,”,$单位);'试试看。 –

+0

使用“for each”循环 – c4pricorn

+0

@ Fred-ii-:我认为他希望每条记录都有一行。 –

回答

3

你在这里做了一些错误,你需要explode$unit的基础上 '' 而不是implode

这里是

if(is_array($unit)) $unit = implode(',', $unit); // check if array, convert to string 
$list=explode(',', $unit); 
foreach($list as $url){ 
    $url = mysqli_escape_string($conn, $url); 
    if($url == '' || empty($url)) continue; 
    $stmt = mysqli_prepare($conn, "INSERT INTO urls(url) VALUES (?)"); 
    mysqli_stmt_bind_param($stmt, 's', $url); 

    if(mysqli_stmt_execute($stmt)){ 
     echo "Records added successfully."; 
     mysqli_stmt_close($stmt); 
    } else{ 
     echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn); 
    } 
} 
+0

['$ list = implode(“, “,$ unit);'](http://stackoverflow.com/questions/33509158/how-to-insert-simple-php-array-into-mysql-table#comment54801939_33509158)我想我的意思是”爆炸“; *我的错*。 –

+0

你并没有净化你的价值观。这是非常危险的。 – Terry

+0

是的,但OP目前只想插入(这也可以是本地项目)@Terry – Mubin