gpt4 book ai didi

php - 数组值存入mysql

转载 作者:行者123 更新时间:2023-11-29 07:33:13 25 4
gpt4 key购买 nike

我有一个看起来像这样的数组:

Array ( [0]  => 'overview' 
[53] => 'PUBLIC'
[54] => '-friendsD'
[55] => 'XHTML'
[56] => '1.0'
[57] => 'Transitional'
[77] => 'People' );

如何获取这些值并使用 INSERT 将它们放入 MySQL?例如INSERT INTO array_value VALUES ('$arrayvalues')。对于每个数组值都是 MySQL 中的一个新帖子。

我尝试过这个:

  <?php
$homepage = file_get_contents('http://www.mysiteexample.com/');
$array = explode(" ",$homepage);
foreach($array as $val) {
$servername = "localhost";
$username = "111";
$password = "111";
$dbname = "111";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
if ($val != " "){
$val = $val. " ";
$query = "INSERT INTO `111` (word) VALUES ('$val')";

$executeQuery = $conn->query($query) === TRUE;

}

if ($executeQuery === TRUE) {
//echo "New record created successfully";
echo $val;
} else {
//echo "Error: " . $query . "<br>" . $conn->error;
echo $val. " ";
}}
$conn->close();
}
?>

这在一定程度上是有效的。它会产生许多空结果,如何将其过滤为没有空帖子。我尝试了 $val != ""但这不起作用。

最佳答案

您可以循环遍历数组并构建查询。然后执行它。

<?php
$homepage = file_get_contents('http://www.mywebsite.com/');
$array = explode(" ",$homepage);

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
$executeQuery;

for ($i = 0; $i < count($array); $i++) {
if (!empty($array[$i])) {
$executeQuery = $conn->query("INSERT INTO `yourTable` (yourField) VALUES ('" . $array[$i] . "')");
}
}

if ($executeQuery === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $query . "<br>" . $conn->error;
}
$conn->close();
}
?>

关于php - 数组值存入mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31866959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com