I have a form handler (I believe that is the correct terminology) called insert.php, this is used to post form data to a MySQL database on localhost. I have different tables each containing a single record and would like to choose which table the data goes to. I could duplicate the insert.php file for each table but that seems messy. How do I choose which table the data goes to via post?
current insert.php:
<?php
require_once 'login.php';
$con=mysqli_connect($hh,$un,$pw,$db);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo 'Connected successfully';
$sql = "UPDATE PiBQ_Temp SET reqdTemp = '$_POST[setTemp]' WHERE tempKey = 1";
mysqli_query($con,$sql);
echo "1 record added";
header ('location: index.php');
mysql_close($con)
?>
What I think is needed for the $sql = variable:
$sql = "UPDATE '$_POST[myTable]' SET '$_POST[myField]' = '$_POST[myValue]' WHERE tableKey = 1"
My html is this:
<form action="insert.php" method="post">
<input type="text" name="myField" value="<?= $myValue ?>"/>
<input type="submit" value="Submit" />
what html should I be using to feed my revised insert.php file above, if that is correct? Thanks.
try this format
$sql = "UPDATE `".$_POST['myTable']."` SET `".$_POST['myField']."` = '".$_POST['myValue']."' WHERE `tableKey` = 1";
or
$mysqli = new mysqli("host", "user", "password", "db");
$stmt = $mysqli->prepare("UPDATE `".$mysqli->real_escape_string(str_replace(" ", "", strtolower($_POST['myTable'])))."` SET `".$mysqli->real_escape_string(str_replace(" ", "", strtolower($_POST['myField'])))."` = ? WHERE `tableKey` = 1");
$stmt->bind_param("s",$_POST['myValue']);
$stmt->execute();
You should use prepared statement instead
There's some wider practices that could be improve, but based on your current code/structure, I would use something like this:
<?php
require_once 'login.php';
try {
$con = new mysqli("host", "user", "password", "db");
} catch (mysqli_sql_exception $e) {
echo "Failed to connect to MySQL: ".$e;
}
$table = (isset($_POST['myTable'])) ? $_POST['myTable'] : null;
$reqdTemp = (isset($_POST['setTemp'])) ? $_POST['setTemp'] : null;
$tempKey = (isset($_POST['setKey'])) ? $_POST['setKey'] : null;
switch($table) {
case "thisTable":
$qry = "UPDATE `thisTable` SET thisField = ? WHERE thisKey = ?";
break;
case "thatTable":
$qry = "UPDATE `thatTable` SET thisField = ? WHERE thisKey = ?";
break;
case "anotherTable":
$qry = "UPDATE `anotherTable` SET thisField = ? WHERE thisKey = ?";
break;
default:
// do something?
break;
}
$stmt = $conn->prepare($qry);
$stmt->bind_param("si", $reqdTemp, $tempKey);
$stmt->execute();
if(!$stmt->execute()) {
echo $stmt->error;
}
else {
echo "1 record added";
}
header ('location: index.php');
mysql_close($con)
?>
Two things to note: The switch statement allows you to provide a different query based on the table name, but it assumes that the same structure is in place (i.e. update String Where Integer).
I've also assumed the thisKey is posted too, as 'setKey'.
Secondly, prepared statements.
This is more of a hint, rather than a whole solution, and you probably need to tidy it up and make it work for you outside of my assumptions
Related
How to update a status from database if status is empty in using php? I have this condition in php. I have this if condition that decides if $getstatus is empty it will update from database to Avail. I tried refreshing the page after querying the database. But it will not update in database. Is there anyway to update this without using form submit in php?
<?php
session_start();
include "includes/connection.php";
// Display all parking slots
$sql = $connection->prepare('SELECT * FROM parkingslot where parkingslotid = 1');
$sql->execute(); // execute query
$result = $sql->get_result(); // fetch result
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$getstatus = $row["status"];
echo $getstatus;
}
}
if (empty($getstatus)) {
$sql = $connection->prepare("UPDATE parkingslot SET status = 'Avail' where parkingslotid = 1 ");
}
?>
Codes in connection for connecting to database
connection.php
<?php
$server = "localhost";
$username = "root";
$password = "";
// create connection
$connection = mysqli_connect($server,$username,$password);
// check connection
if(!$connection)
{
die("No connection found." . mysqli_connect_error());
}
else {
// select a database
$select_db = mysqli_select_db($connection,'smartparkingsystem');
if(!$select_db)
{
$sql = 'CREATE DATABASE sample';
// create database if no db found
if(mysqli_query($connection,$sql)) {
echo "Database Created";
}
else {
echo "Database not found" . mysqli_connect_error() . '\n';
}
}
else {
// Database already existed
// do nothing...
}
}
?>
If I understand your goal of: For row(s) whereparkingslotid=1 - Update status to 'Avail' but only if status is not currently set, this might help:
<?php
session_start();
include "includes/connection.php";
$connection->prepare("UPDATE `parkingslot` SET `status`=? WHERE `parkingslotid`=? AND (`status` IS NULL OR `status`=?)");
$connection->bind_param("sis", $status, $parkingslotid, $empty_str);
$status = 'Avail';
$parkingslotid = 1;
$empty_str = '';
$connection->execute();
echo $connection->affected_rows.' rows affected';
$connection->close();
?>
This saves a bit of processing by not checking with PHP first.
You can use this query:
"UPDATE parkingslot SET status = 'Avail' where status IS NULL OR status = '' "
Edited:
#lumonald gave the right anwser in the comment. You're not executing your second SQL statement.
I'm working on a very basic PHP programme. I'm very new to PHP and am aware that I'm using the older versions i.e not PDO. I've been working on this for a while and can't figure out why it isn't working.
I'm simply trying to delete an item from my table which matches the user input.
((also if anyone has any easy recommendations I can use to have a safer delete function as I am aware if the user input is 'r' for example, a huge chunk of the table will be deleted))
Here is my code:
<?php
//delete from table
if(isset($_POST['delete1']))
{
$deletevalue = $_POST['deletevalue'];
$deletequery = "DELETE FROM users WHERE deletevalue = $deletevalue";
$deleteresult = deleteTable($deletevalue);
}
function deleteTable ($deletevalue)
{
$connect = mysqli_connect("localhost", "root", "", "test_db");
$delete_fromTable = mysqli_query($connect, $deletevalue);
print mysqli_error($connect);
}
?>
<!DOCTYPE html>
<html>
<body>
<form action="zzz.php" method="post" />
<p> Remove Item: <input type="text" name="deletevalue" placeholder="Item
Name" /> </p>
<input type="submit" name ="delete1" value="submit" />
</form>
</body>
</html>
regarding all comments, and completely OK with security statements, you should really consider using PPS : Prepared Parameterized Statements. This will help Preventing SQL injection. Plus : use error_reporting(E_ALL); ini_set('display_errors', 1); on top of your pages will help PHP give you hint about errors :)
This is a way (not the only one) to handle your query.
Please read carefully and adapt names according to your DB structure and column names.
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$host = ""; /* your credentials here */
$user = ""; /* your credentials here */
$pwd = ""; /* your credentials here */
$db = ""; /* your credentials here */
/* store in PHP variable */
$deletevalue = $_POST['deletevalue'];
echo"[ is my var ok ? -> $deletevalue ]"; /* just checking value */
// connexion to db
$mysqli = mysqli_connect("$host", "$user", "$pwd", "$db");
if (mysqli_connect_errno()) { echo "Error: no connexion allowed : " . mysqli_connect_error($mysqli); }
$query = " DELETE FROM `users` WHERE deletevalue = ? ";
$stmt = $mysqli->prepare($query); /* prepare query */
$stmt->bind_param("s", $deletevalue); /* bind param will sanitize -> 's' is for a string */
print_r($stmt->error_list); /* any error ? */
print_r($stmt->get_warnings()); /* any error ? */
print_r($stmt->error); /* any error ? */
/* another ways of checking for errors :
if (!($stmt = $mysqli->prepare(" DELETE FROM `users` WHERE deletevalue = ? "))) {
echo "Error attempting to prepare : (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$stmt->bind_param("s", $deletevalue)) {
echo "Error attempting to bind params : (" . $stmt->errno . ") " . $stmt->error;
}
*/
if (!$stmt->execute()) { echo"false"; echo "Error attempting to execute : (" . $stmt->errno . ") " . $stmt->error; } else { echo"true"; }
?>
Here your code will be looks like (Except security issue)
In this code you are deleting your record on the basis of firstName of the user thats why in where clause WHERE firstName = '$deletevalue' firtName there.
if(isset($_POST['delete1']))
{
$deletevalue = $_POST['deletevalue'];
//here put your table column in where clause
$deletequery = "DELETE FROM users WHERE firstName = '$deletevalue'"; //if your form enters name of the users
$deleteresult = deleteTable($deletequery);
}
function deleteTable ($deletequery)
{
$connect = mysqli_connect("localhost", "root", "", "test_db");
$delete_fromTable = mysqli_query($connect, $deletequery);
print mysqli_error($connect);
}
See in your where clause WHERE name = if you are deleting on the basis of name of the user.
and also see deleteTable($deletequery); you need to pass your query not the value.
Note:
Yes, I know you are learning basic things but my recomendations are
1) Use Prepared statements, explore little bit about it
2) Delete records based on ID (unique field) not name, name (firstName) might be same for multiple users in users table
Still very new to mysqli / php and am building a form for data entry. When I post the data and then go back to view it, anytime there was a single quote (') or double-quote ("), it down displays with a slash in front of it.
For example, if I insert Hadrian's Wall, it comes back and displays as Hadrian\'s Wall. How would one have it display as it was originally intended.
Also, each time I update it, it adds more slashes. So the first time I updated Hadrian's Wall, it became Hadrian\'s Wall. The second time it became Hadrian\'s Wall, the third time it became Hadrian\\'s Wall and so on.
My post.php file code is:
<?php
define('DB_SERVER', "*****");
define('DB_USER', "*****");
define('DB_PASSWORD', "*****");
define('DB_TABLE', "*****");
// The procedural way
$mysqli = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_TABLE);
$mysqli->set_charset("utf8");
$mysqli->query("SET NAMES 'utf8'");
if (mysqli_connect_errno($mysqli)) {
trigger_error('Database connection failed: ' . mysqli_connect_error(), E_USER_ERROR);
}
$lvmID = $_POST['lvmID'];
$toestelID = $_POST['toestelID'];
$toestel = $_POST['toestel'];
$erlr = $_POST['erlr'];
$inschrijvingnmr = $_POST['inschrijvingnmr'];
$status = $_POST['status'];
$cn = $_POST['cn'];
$ln = $_POST['ln'];
$delivered = $_POST['delivered'];
$vliegtuignaam = $_POST['vliegtuignaam'];
$became = $_POST['became'];
$vorigeLVMID = $_POST['vorigeLVMID'];
$vorigeInschrijv = $_POST['vorigeInschrijv'];
$firstflight = $_POST['firstflight'];
$engines = $_POST['engines'];
$configuratie = $_POST['configuratie'];
$remark = $_POST['remark'];
$specialekleuren = $_POST['specialekleuren'];
$fleetnmr = $_POST['fleetnmr'];
$inactive = $_POST['inactive'];
$exitdate = $_POST['exitdate'];
$beeld = $_POST['beeld'];
$beeld_linkje = $_POST['beeld_linkje'];
$beeld_copyright = $_POST['beeld_copyright'];
$photouse_approve = $_POST['photouse_approve'];
$photouse_approve_date = $_POST['photouse_approve_date'];
$beeld_comment = $_POST['beeld_comment'];
$seatmap = $_POST['seatmap'];
$id = $_POST['id'];
$sql = "
UPDATE tbl_vliegtuiggegevens SET lvmID=?, toestelID=?, toestel=?, erlr=?, inschrijvingnmr=?, status=?, cn=?, ln=?, delivered=?, vliegtuignaam=?, became=?, vorigeLVMID=?, vorigeInschrijv=?, firstflight=?, engines=?, configuratie=?, remark=?, specialekleuren=?, fleetnmr=?, inactive=?, exitdate=?, beeld=?, beeld_linkje=?, beeld_copyright=?, photouse_approve=?, photouse_approve_date=?, beeld_comment=?, seatmap=? WHERE vliegtuiggegevenID=?";
if(!($stmt = $mysqli->prepare($sql)))
{
die("Unable to prepare statement");
}
else
{
$stmt->bind_param("iisssssssssisssssssissssssssi", $lvmID, $toestelID, $toestel, $erlr, $inschrijvingnmr, $status, $cn, $ln, $delivered, $vliegtuignaam, $became, $vorigeLVMID, $vorigeInschrijv, $firstflight, $engines, $configuratie, $remark, $specialekleuren, $fleetnmr, $inactive, $exitdate, $beeld, $beeld_linkje, $beeld_copyright, $photouse_approve, $photouse_approve_date, $beeld_comment, $seatmap, $id);
if($stmt->execute())
{
echo "Successfully updated";
}
else
{
die("Update failed");
}
}
mysqli_close($mysqli);
?>
On the form page that I use to enter the data, my code for one of the forms fields is:
<input type="text" name="vliegtuignaam" size="40" value="<? echo
"$row[vliegtuignaam]"?>">
On the display page, this same field for display would be:
<td><strong>Vliegtuignaam: </strong></td>
<td><? echo "$row[vliegtuignaam]"?></td>
When I try something like it just outputs stripslashes(Hadrian\'s Wall) instead of Hadrian's Wall.
"When I try something like it just outputs stripslashes(Hadrian\'s Wall)"
What you probably tried to do was <td><? echo "stripslashes($row[vliegtuignaam])"?></td> which is incorrect.
That is why it's showing you the function name because the function is set inside quotes.
What you need to use is:
<td><? echo stripslashes($row['vliegtuignaam']);?></td>
or
<td><? echo stripslashes($row[vliegtuignaam]);?></td>
if the quotes inside the array gives you a hard time.
As per an example in the manual http://php.net/manual/en/function.stripslashes.php
echo stripslashes($str);
Full example:
<?php
$str = "Is your name O\'reilly?";
// Outputs: Is your name O'reilly?
echo stripslashes($str);
?>
What you could do and as another option, would be to use stripslashes() on the variable(s) before it gets to the query.
$str = "Is your name O\'reilly?";
$newstring = stripslashes($str);
then go ahead with the insert.
I'm busy coding a website for a local business that does Milkshakes. Naturally, they wanted to show their flavours on the site and have a management page where they could edit them. I have gotten the flavours to show up on the main page, but I am having a problem with the management page.
I have a database set up that contains a list of the flavours. The 3 main things that I am trying to allow them to do is edit, delete and add new entries. Currently, I am calling out each row (or each flavour and its id) as separate forms with 2 submit buttons: one to save changes, and one to remove it.
Code is below:
for the management page:
<?php
$con = new PDO('mysql:host=host;dbname=dbname', "user", "password");
$con -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT * FROM FlavourShakes";
$data = $con->query($query);
$rows = $data->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$id = $row['id'];
$flavour = $row['Flavour'];
print "<form action=\"saveFlavorShakes.php\" method=\"post\"> \n
<fieldset> \n
<input name=\"id\" value=\"$id\" readonly/> \n
<input name=\"Flavour\" value=\"$flavour\" /> \n
<input type=\"submit\" name=\"edit\" value=\"Save\"> \n
<input type=\"submit\" name=\"edit\" value=\"Remove\"> \n
</fieldset> \n
</form> \n";
}
?>
<form action="saveFlavorShakes.php" method="post">
<fieldset>
<input name="Flavour" />
<input type="submit" name="edit" value="Add">
</fieldset>
</form>
and on my processing page:
<?php
$flavour = $_POST['Flavour'];
$id = $_POST['id'];
$btnType = $_POST['edit'];
$con = new PDO('mysql:host=hostname;dbname=dbname', "user", "password");
$con -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "";
try
{
switch($_POST['edit']){
case'Save':
$query = "UPDATE FlavorShakes
SET Flavour= :name,
WHERE id = :id;";
$notice = "saveOK";
$_POST['notice'] = $notice;
break;
case'Add':
$query = "INSERT INTO FlavourShakes(Flavour) VALUES (:name);";
$notice = "addOK";
$_POST['notice'] = $notice;
break;
}
//I know I haven't added a case for the remove button yet.
$statement = $con->prepare($query);
$statement->bindValue(":id", $id);
$statement->bindValue(":name", $flavour);
$count = $statement->execute();
header('Location: EditFlavorShakes.php');
}
catch(PDOException $e) {
if ($btnType = "save"){
$notice = "saveBad";
$error = $e->getMessage();
$_POST['notice'] = $notice;
$_POST['error'] = $error;
} elseif($btnType = "delete"){
$notice = "delBad";
$error = $e->getMessage();
$_POST['notice'] = $notice;
$_POST['error'] = $error;
}elseif($btnType = "add"){
$notice = "addBad";
$error = $e->getMessage();
$_POST['notice'] = $notice;
$_POST['error'] = $error;
}else{
$notice = "otherBad";
$error = $e->getMessage();
$_POST['notice'] = $notice;
$_POST['error'] = $error;
}
echo $notice;
echo $e->getMessage();
//header('Location: EditFlavorShakes.php');
}
?>
Currently, I don't have any entries in the database. However, when I try to add Chocolate and click the Add button, I get this error:
saveBadSQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
What I don't understand is why it $_POST['edit'] set to save instead of add? I feel like I am overlooking some stupidly simple mistake in my code. If anyone can help me I would appreciate it.
Thanks in advance.
You need to move the right $statement calls into each case -
switch($_POST['edit']){
case'Save':
$query = "UPDATE FlavorShakes
SET Flavour= :name,
WHERE id = :id;";
$notice = "saveOK";
$_POST['notice'] = $notice;
$statement = $con->prepare($query);
// this query needs multiple values bound
$statement->bindValue(":id", $id);
$statement->bindValue(":name", $flavour);
break;
case'Add':
$query = "INSERT INTO FlavourShakes(Flavour) VALUES (:name);";
$notice = "addOK";
$_POST['notice'] = $notice;
$statement = $con->prepare($query);
// this one needs one value bound
$statement->bindValue(":name", $flavour);
break;
}
//I know I haven't added a case for the remove button yet.
$count = $statement->execute();
You're also missing several tests (you're assigning) in your if statement. Replace = with == -
if ($btnType == "save"){
...
} elseif($btnType == "delete"){
...
}elseif($btnType == "add"){
...
}else{
...
}
This error message:
saveBadSQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
is because you try this line when there is no :id
$statement->bindValue(":id", $id);
And you always get saveBad cause you assign in your control:
if ($btnType = "save"){
Fix to:
if ($btnType === "save"){
Can anyone tell me why I am getting an Undefined Index error on my code here.
I have used this setup using the if(isset) condition in other parts of my project after
researching my original Undefined Index errors and ISSET fixed my problems. But it is not working here for some reason and I cannot see why.
This form is POSTING the input:
<form action="addAlbum_Processed.php" method="POST">
<p>Enter artistID of Artist<input type="number" name="artist_id" maxlength="2" size="2"></p>
<p>Enter name of Album to be created<input type="text" name="album_name" size="20"></p>
<input type="submit" name="submit" value="submit"></form>
and this page is processing the form input and updating the albums table in my database:
<?php
$connection = mysql_connect('localhost','root','')
or die(mysql_error());
echo "Connected to php Server <br>";
or die("Could not select assi2 database");
echo "Connected to assi2 database <br>";
if(isset($_POST['submit']))
{
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
}
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
$sqlQuery = "SELECT * FROM albums WHERE album = '{$album_name}'";
$result = mysql_query($sqlQuery, $connection) or die("Selection Query Failed !!!");
if (mysql_num_rows($result) != 0)
{
header ("Location: Album_Exists.html");
}
else
{
$sqlInsert = "INSERT INTO albums (ArtistID, Album, delete_marker)
VALUES ('{$artist_id}','{$album_name}','delete_marker = 0')";
$result = mysql_query($sqlInsert, $connection) or die("Selection Query Failed !!!");
header ("Location: addAlbum_Processed.php");
}
mysql_close($connection);
?>
I cannot see where I am going wrong. Regards, TW
This is a tiny example of your problem:
if(isset($_POST['submit']))
{
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
}
You check whether a submit form field was posted before using the other fields. So far, so good. (I would check for the fields that were going to be used, but at least you're checking something.)
But then:
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
You use the fields anyway.
What's more...you don't keep from trying to insert stuff if a form isn't being posted. So any time some rogue spider visits your page, you end up with a blank album in your database.
And that's not even mentioning the fact that you're still using mysql_query.
if(isset($_POST['submit']))
{
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
}
|__________________________| first
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
|_________________________| Repeated
you are fetching variables twice.only one that is if condition is enough.Also use isset for both the variables.
if(isset($_POST['submit']))
{
if isset($_POST['album_name'])
$album_name = $_POST['album_name'];
if isset($_POST['artist_id'])
$artist_id = $_POST['artist_id'];
}
Try something like in addalbam_process.php
<?php
$connection = mysql_connect('localhost','root','')
or die(mysql_error());
echo "Connected to php Server <br>";
or die("Could not select assi2 database");
echo "Connected to assi2 database <br>";
if(isset($_POST['submit']))
{
if(isset($_POST['albam_name']){$album_name = $_POST['album_name']};
if(isset($_POST['artist_id']){$artist_id = $_POST['artist_id']};
}
$sqlQuery = "SELECT * FROM albums WHERE album = '{$album_name}'";
$result = mysql_query($sqlQuery, $connection) or die("Selection Query Failed !!!");
if (mysql_num_rows($result) != 0)
{
header ("Location: Album_Exists.html");
}
else
{
$sqlInsert = "INSERT INTO albums (ArtistID, Album, delete_marker)
VALUES ('{$artist_id}','{$album_name}','delete_marker = 0')";
$result = mysql_query($sqlInsert, $connection) or die("Selection Query Failed !!!");
header ("Location: addAlbum_Processed.php");
}
mysql_close($connection);
Please, use MYSQLI or PDO to Prevent SQL INJECTION
here </form> is missing
and try something like this
if(isset($_POST['submit']))
{
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
}
A few things.
This line 'delete_marker = 0' should most probably read as
VALUES ('{$artist_id}','{$album_name}','0')
or VALUES ('{$artist_id}','{$album_name}',0)
As I read it 'delete_marker = 0' you are attempting to actually write this value inside the delete_marker column (ArtistID, Album, delete_marker)
Or, you're attempting to use a WHERE delete_marker = 0 clause, which can't be used in an INSERT INTO, but an UPDATE or SELECT rather.
And your if(isset($_POST['submit'])) conditional statement should be wrapping your entire code, instead of just your 2 form variables, because it's basically saying "Ok, assign these 2 variables, then ignore the rest if it's NOT set."
Plus, you're repeating those 2 input variables.
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
(I wrapped your entire code inside the if(isset($_POST['submit'])) conditional statement, btw.
Side note: If you're having a DB connection issue, use this instead:
$connection = mysql_connect('localhost', 'root', '');
if (!$connection) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
PHP Give this a try:
Sidenote: If this line fails VALUES ('{$artist_id}','{$album_name}', 0) put quotes around the 0 as in '0'
<?php
$connection = mysql_connect('localhost','root','')
or die(mysql_error());
echo "Connected to php Server <br>";
or die("Could not select assi2 database");
echo "Connected to assi2 database <br>";
if(isset($_POST['submit']))
{
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
$sqlQuery = "SELECT * FROM albums WHERE album = '{$album_name}'";
$result = mysql_query($sqlQuery, $connection) or die("Selection Query Failed !!!");
if (mysql_num_rows($result) != 0)
{
header ("Location: Album_Exists.html");
}
else
{
$sqlInsert = "INSERT INTO albums (ArtistID, Album, delete_marker)
VALUES ('{$artist_id}','{$album_name}', 0)"; // or add quotes around the zero
$result = mysql_query($sqlInsert, $connection) or die("Selection Query Failed !!!");
header ("Location: addAlbum_Processed.php");
}
} // closing brace for if(isset($_POST['submit']))
mysql_close($connection);
?>