SQL& PHP - 添加到表,失败

时间:2014-09-16 02:58:34

标签: 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++;

  }
}

更新,观察者:

  

解析错误:语法错误,第60行的C:\ xampp \ htdocs \(...)\ PHP \ rss \ index.php中的意外'$ entry'(T_VARIABLE)

if ($y < 8) {

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



  $y++;

}

2 个答案:

答案 0 :(得分:1)

取下连接并关闭该循环外部。而根据Dagon,将它们组合成多个插入物。例如:

$con = mysqli_connect("localhost","usernameremoved", "passwordremoved","databasenameremoved");
$stmt = 'INSERT INTO Entries (Link, Title) VALUES ';
$values = array();
$y = 0;
foreach ($x->channel->item as $entry) {
    if($y < 8) {
        $values[] = "('$entry->link', '$entry->title')";
    }
    $y++;
}
$values = implode(', ', $values);
$stmt .= $values;
mysqli_query($con, $stmt);
mysqli_close($con); 

答案 1 :(得分:1)

这个案例几乎就是为...创建预备语句。

// 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();