gpt4 book ai didi

php - SQL 和 PHP - 添加到表,失败

转载 作者:行者123 更新时间:2023-11-29 02:24:17 25 4
gpt4 key购买 nike

我使用 PHP 在我的数据库中成功创建了一个表。现在,我正在尝试用数据填充它。当我对要添加的数据进行 var_dump 时,它会正确呈现 - 它不是未定义的。

我没有收到任何错误,但我的 SQL 表中没有任何条目。我做错了什么?谢谢。

这里的数据库布局:

foreach($x->channel->item as $entry) {

if ($y < 8) {

$con=mysqli_connect("localhost","usernameremoved",
"passwordremoved","databasenameremoved");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO Entries (Link, Title)
VALUES ($entry->link, $entry->title)");
echo "Tables updated successfully.";
mysqli_close($con);


$y++;

}
}

更新,对于观察者:

Parse error: syntax error, unexpected '$entry' (T_VARIABLE) in C:\xampp\htdocs\ (... ) \PHP\rss\index.php on line 60

if ($y < 8) {

mysqli_query($con,"INSERT INTO Entries (Link, Title)
VALUES ("$entry->link", "$entry->title")");
echo "Tables updated successfully.";



$y++;

}

最佳答案

这种情况几乎就是为准备好的语句而创建的。

// Database connection
$db = new MySQLi("localhost","usernameremoved", "passwordremoved","databasenameremoved");
if ($db->error) {
echo "Failed to connect to MySQL: ".$db->error;
}
// Prepared statement
$stmt = $db->prepare('INSERT INTO entries (Link, Title) VALUES (?, ?)');
if ($stmt === false) {
die('Could not prepare SQL: '.$db->error);
}
// Bind variables $link and $title to prepared statement
if ( ! $stmt->bind_param('ss', $link, $title)) {
die('Could not bind params: '.$stmt->error);
}
$y = 0;
foreach ($x->channel->item as $entry) {
if ($y >= 8) {
break;
}
// Set values on bound variables
$link = $entry->link;
$title = $entry->title;

// Execute
if ($stmt->execute() === false) {
die('Could not execute query: '.$stmt->error);
}
$y++;
}
$stmt->close();
$db->close();

关于php - SQL 和 PHP - 添加到表,失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25859998/

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