我使用 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/