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

标签 php mysql

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

相关文章:

PHP在子文件夹中执行脚本

mysql - 如何从多个表中选择两列并在 MySQL 中将它们并排放置(没有关系或条件)?

mysql - 如何将两列合并为具有最高 ID 的一列?

PHP:遍历所有对象方法(调用对象中的所有方法)

php - 如何修改 WooCommerce 购物车、结帐页面(主题部分)

php - 将 PHP mongodb findOne 结果转换为旧的关联数组?

javascript - 使用PHP将JSON插入MySQL表

mysql - 在 mySQL 中创建动态表

mysql - 在 COUNT(*) 条件 MySQL 中添加一个 WHERE

mysql - 加入管道列数据