I successfully created a table in my database, using PHP. Now, I'm trying to fill it with data. When I var_dump the data I'm trying to add, it correctly renders - it's not undefined.
I don't get any errors, but there are no entries in my SQL tables. What did I do wrong? Thanks.
Database layout here:
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++;
}
}
UPDATE, for Watcher:
Parse error: syntax error, unexpected '$entry' (T_VARIABLE) in C:\xampp\htdocs\ (... ) \PHPss\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++;
}
Just take off that connect and close outside that loop. And as per Dagon, combine them into a multiple insert instead. Example:
$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);
This case is pretty much what prepared statements were created for.
// 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();