I built a song request form for my wedding website and would like to check if the variables I am storing the form input in is empty before POST'ing to the database. My goal is simple prevent blank rows from being added to mysql db when the for is fired off.
<?php
// extract data from form; store in variable
$artist = $_POST["artist"];
$song = $_POST["song"];
// connect to server
$conn = mysql_connect('host', 'user', 'pass');
// check if you can connect; if not then die
if (!$conn) {
echo "<center>";
die('Could Not Connect: ' . mysql_error());
echo "</center>";
}
// check if you can select table; in not then die
$db = mysql_select_db('database', $conn);
if (!$db) {
echo "<center>";
die('Database Not Selected: ' . mysql_error());
echo "</center>";
}
// Define the query to inser the song request
$insert = mysql_query("INSERT INTO Songs (Artist, Song) VALUES ('$artist', '$song')");
// check if above variables are empty
if (!empty($artist) and !empty($song)) {
echo "<center>";
echo "Insert was succesful<br>";
echo "<a href='index.html' target='_self' >Back</a>";
echo "</center>";
}
else {
echo "<center>";
die("Please fill in at least the artist name");
echo "</center>";
}
// close the connection to the server
mysql_close($conn);
?>
I have the above in a file called insert.php which is fired off when form on the index page is submitted. Form is submitting using POST and works just fine, however I would like to prevent blank submissions from happening.
Very new to programming and want to learn how to do this right.
Thanks for your patience.