Fields inserting blank data into database - php

I've checked my code compared with code elsewhere on my site and I can't see any inconsistencies, but for some reason the records are entering my database with blank data, here is my code.
<?php
include '../includes/connect.php';
include '../header.php';
echo '<h2>Create a Sub category</h2>';
if($_SESSION['signed_in'] == false | $_SESSION['user_level'] != 1 )
{
//the user is not an admin
echo 'Sorry, you do not have sufficient rights to access this page.';
}
else
{
//the user has admin rights
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
//the form hasn't been posted yet, display it
echo '<form method="post" action="">
Category name: ';
$sql = "SELECT cat_id, cat_name, cat_description FROM categories";
$result = mysql_query($sql);
echo '<select name="topic_cat">';
while($row = mysql_fetch_assoc($result))
{
echo '<option value="' . $row['cat_id'] . '">' . $row['cat_name'] . '</option>';
}
echo '</select><br />';
echo 'Sub category name: <input type="text" name="sub_cat_name" /><br />
Sub category description:<br /> <textarea name="sub_desc" /></textarea><br /><br />
<input type="submit" value="Add Sub Category" />
</form>';
}
else
{
//the form has been posted, so save it
$sql = "INSERT INTO subcategories(c_id, sub_cat_name, sub_desc)
VALUES('" . $_POST['categories.cat_id'] . "', '" . $_POST['sub_cat_name'] . "', '" . $_POST['sub_desc'] . "')";
$result = mysql_query($sql) or die (mysql_error());
echo 'The sub category <b>' . $row['sub_cat_name'] . '</b> has been added under the main category <b>' . $row['cat_name'] . '</b>';
if(!$result)
{
//something went wrong, display the error
echo 'Error' . mysql_error();
}
}
}
; ?>
My categories table is structured like so..
cat_id
cat_desc
My subcategories table is structured like so..
id(AI)
c_id
sub_cat_name
sub_desc
If I haven't provided enough information please let me know.

You don't appear to be reading the $POST variables into the variables you're using in your query. You probably want something like this:
$sub_cat_name = mysql_real_escape_string($_POST['sub_cat_name']);
// repeat for other variables.

It seems to me that $cat_id $sub_cat_name and $sub_desc are not defined anywhere.
Also, you're missing a pipe here:
if($_SESSION['signed_in'] == false || $_SESSION['user_level'] != 1 )
// --------------------------------^
Lastly, I should note that the mysql_* functions are deprecated. You should really be using mysqli or PDO.

if($_SESSION['signed_in'] == false || $_SESSION['user_level'] != 1 )
------------------------------------^ (OR)
I also don't see where you set the variables. ('" . $cat_id . "' and etc...)
You should store them into a variable like so:
$cat_id = mysql_real_escape_string($_POST['name_of_the_input']); //and etc..
Or in your insert query do this: (Depending on the values whether or not you need to escape it like above)
'".$_POST['name_of_input']."',

Related

PHP produces blank screen with submit button click

Below I have code that is supposed to update an entry in the database. When I click the submit button the form goes away but it is not replaced with anything and more importantly it doesn't update the database. I cannot seem to find where the error is and any help would be greatly appreciated.
<?php
define('TITLE', 'Quotes Entry!');
// Include the header:
include('header.php');
include('mysqli_connect.php');
// Leave the PHP section to display lots of HTML:
?>
<?php //
mysqli_set_charset($dbc, 'utf8');
if (isset($_GET['id']) && is_numeric($_GET['id']) ) { // Display the entry in a form:
// Define the query:
$query = "SELECT title, entry FROM Salinger WHERE entry_id={$_GET['id']}";
if ($r = mysqli_query($dbc, $query)) { // Run the query.
$row = mysqli_fetch_array($r); // Retrieve the information.
//make the form
print '<form action = "edit_entry.php" method = "post">
<p> Entry Titles <input type= "text" name = "title" size = "40" maxsize = "100" value = "' . htmlentities($row['title']) . '" /></p>
<p>Entry Text <textarea name = "entry" cols = "40" rows = "5">'. htmlentities($row['entry']).'</textarea></p>
<input type = "hidden" name = "id" value = "'.$_GET['id'] .'" />
<input type = "submit" name = "submit" value = "Update This Entry!" />
</form>';
} else { // Couldn't get the information.
print '<p style="color: red;">Could not retrieve the blog entry because:<br />' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>';
}
} elseif (isset($_POST['id']) && is_numeric($_POST['id'])) { // Handle the form.
$problem = "false";
if(!empty($_POST['title']) && !empty($_POST['entry'])){
$title = mysqli_real_escape_string($dbc, trim(strip_tags($_POST['title'])));
$entry = mysqli_real_escape_string($dbc, trim(strip_tags($_POST['entry'])));
} else{
print '<p style="color: red;">Could not retrieve the blog entry because:<br />' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>';
$problem = true;
}
if(!problem){
$query = "UPDATE Salinger SET title = '$title', entry = '$entry' WHERE entry_id = {$_POST['id']}";
$r = mysqli_query($dbc, $query); //execute the query
if(mysqli_affected_rows($dbc) == 1){
print'<p> The blog entry has been updated.</p>';
// Report on the result:
} else {
print '<p style="color: red;">Could not retrieve the blog entry because:<br />' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>';
}
}
} else{
print '<p style="color: red;">Could not retrieve the blog entry because:<br />' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>';
}
mysqli_close($dbc); // Close the database connection.
include('footer.php'); // Need the footer.
?>
Because you set $problem = "false"; you need to set it to $problem= false;
"false" is not false
And !problem should be !$problem
You have a problem with GET[id].
It's getting blank cause of POST event on screen, due to which your SQL is not finding the record.
To test assign hard coded value in your select statement.
Example
$query = "SELECT title, entry FROM Salinger WHERE entry_id=10";

How do I get php to 'remember' the conducted search after selecting to sort results?

I have the following code:
<?php
include "include.php";
session_start();
// Defining variables from home.php if set
if(isset($_POST['title'])){
$title = mysql_real_escape_string($_POST['title']);
}
if(isset($_POST['author'])){
$author = mysql_real_escape_string($_POST['author']);
}
if(isset($_POST['isbn'])){
$isbn = mysql_real_escape_string($_POST['isbn']);
}
if(isset($_POST['keyword'])){
$keyword = mysql_real_escape_string($_POST['keyword']);
}
if(isset($_POST['sort'])){
$sort=#$_POST['sort'];}
// Determine the WHEREs to use
$where = array();
if ( ! empty($title))
$where[] = "booktitle LIKE '%" . $title . "%'";
if ( ! empty($author))
$where[] = "author LIKE '%" . $author . "%'";
if ( ! empty($isbn))
$where[] = "isbn LIKE '%" . $isbn . "%'";
if ( ! empty($keyword))
$where[] = "description LIKE '%" . $keyword . "%'";
//Determine the ORDERs to use
$order = array();
if ((isset($sort)) && ($sort=='lowhigh'))
$order[] = "price ASC";
if ((isset($sort)) && ($sort=='highlow'))
$order[] = "price DESC";
// Build the query
$query = 'SELECT * FROM book';
if ( ! empty($where))
$query .= ' WHERE ' . implode(' AND ', $where);
if(! empty($sort))
$query .= ' ORDER BY ' . implode($order);
//Display results
$result = mysqli_query($con, $query) or die("Error in query $query: " . mysqli_error());
while ($row = mysqli_fetch_array($result)) {
?><a id="1" href="book.php" border="0"><img src="<?php echo $row[12]; ?>" width="112px" height="150px" /></a>
<b><?php echo $row[1] . ", (" . $row[5] . ")";?></b><br><?php
echo $row[2];
echo "<br><div style='text-align:right'> <b>£" . $row[9] . "</b></div>";
echo "<b>Book description:</b> " . substr($row[3],0,300) . "...<br /><hr>";
}
mysqli_close($con); //closes the connection
?>
It passes inputs from four text fields on a front end page and displays the results. This all works fine. It's when I come to sorting the displayed results. If I selected Price: low to high for example, it arranges all the results in my database and displays everything, not just the results from the conducted search. Does anyone now how I can get it to remember the original search?
This is my form:
<form id="rform" name="formsort" action="" method="post">
<select name="sort" id="sort" onChange="document.forms['formsort'].submit()">
<option value="default">Sort Results</option>
<option value="lowhigh">Price: Low to High</option>
<option value="highlow">Price: High to Low</option>
</select>
</form>
How do I get php to 'remember' the conducted search
It is not actually PHP but rather general idea of HTTP protocol. So, to solve your problem you have to just follow the standard:
GET method should be used for searches instead of POST. That's defined by HTTP standard and being the very purpose of GET method. While POST shouldn't be used for search.
So, as long as you are using GET method, your data being preserved automatically.
The only issue could be with pagination links. To add current query string to them http_build_query() function have to be used.
You could actually reduce the amount of conditions on your page. Instead of using 2 separate ones
if(isset($_GET['title'])){
$title = mysql_real_escape_string($_POST['title']);
}
if ( ! empty($title))
$where[] = "booktitle LIKE '%" . $title . "%'";
one have to be used
if(isset($_GET['title'])){
$title = mysql_real_escape_string($_POST['title']);
$where[] = "booktitle LIKE '%" . $title . "%'";
}
Sorry i have checked your code again and found that it is clear and the solution is also clear :)
Ad 3 hidden element into the form of sorting each one named by (title,book,author) successively and store the values posted from the search action so when you will sort the results you will also applying these constraints because are posted again :)
I mean you must add the following code after the inside the sorting form you are using :
<?php
if(isset($_POST['title']))
{
echo '<input type="hidden" name="title" value="'.$_POST['title'].'" />';
}
if(isset($_POST['author']))
{
echo '<input type="hidden" name="author" value="'.$_POST['author'].'" />';
}
if(isset($_POST['isbn']))
{
echo '<input type="hidden" name="isbn" value="'.$_POST['isbn'].'" />';
}
if(isset($_POST['keyword']))
{
echo '<input type="hidden" name="keyword" value="'.$_POST['keyword'].'" />';
}
if(isset($_POST['sort']))
{
echo '<input type="hidden" name="sort" value="'.$_POST['sort'].'" />';
}
?>
Hope this will help you :) Let me know if any additional help needed :)
at my point of view ,
why are you going for such a drastic sorting ?
you can simply display the result in a table via php, use jquery to sort the table in any way
http://tablesorter.com/docs/
http://joequery.github.com/Stupid-Table-Plugin/
When you use "ORDER BY" you are sorting the result set, not the database itself. If you would like to grab a fresh copy of the results just do so without the ORDER BY.
Also, PHP's ternary if structure is much better suited here. Instead of :
if(isset($_POST['title'])){
$title = mysql_real_escape_string($_POST['title']);
}
You can say:
$title = (isset($_POST['title']) ? mysql_real_escape_string($_POST['title']) : "");

Database query php MySQL - no search results displayed

(PROBLEM IS VERY DETAILED FOR TOO LONG DIDN'T READ: "My guess is that i'm using the MYSQL_FETCH_ARRAY wrong.")
Hello! The following codes purpose is to do a basic search in the database. The data is passed by a form. The tutorial I was using was written by: 'Frost of Slunked.com' and it was a basic register/login php MySQL tutorial, which worked perfectly. I managed to write a woking table-updater function and form-submit to add new data to the selected (so that's working as intended.
config.php - conncets to the MySQL server, selects the database, starts the session, requires the functions.php (with authors comments included)
<?php
/*****************************
File: includes/config.php
Written by: Frost of Slunked.com
Tutorial: User Registration and Login System
******************************/
// start the session before any output.
session_start();
// Set the folder for our includes
$sFolder = '';
/***************
Database Connection
You will need to change the user (user)
and password (password) to what your database information uses.
Same with the database name if you used something else.
****************/
mysql_connect('localhost', 'myusername', 'mypassword') or trigger_error("Unable to connect to the database: " . mysql_error());
mysql_select_db('tormex') or trigger_error("Unable to switch to the database: " . mysql_error());
/***************
password salts are used to ensure a secure password
hash and make your passwords much harder to be broken into
Change these to be whatever you want, just try and limit them to
10-20 characters each to avoid collisions.
****************/
define('SALT1', '24859f##$##$');
define('SALT2', '^&##_-=+Afda$#%');
// require the function file
require_once 'functions.php';
// default the error variable to empty.
$_SESSION['error'] = "";
// declare $sOutput so we do not have to do this on each page.
$sOutput="";
?>
functions.php - has multiple functions (login, createRide, Register etc.). Most of the functions purpose is to get the values from the submitted HTML forms and then maintain the required actions - I will only mentioned my searchRide function (which in my guess has the error or atleast, has to do something with it) and the createRide function, which is working properly.
<?php ...
unction searchRide($pWhen_min, $pWhen_max, $pFrom, $pTo){
if (!empty($pWhen_min) && !empty($pWhen_max) && !empty($pFrom) && !empty($pTo)) {
global $sql2, $query2;
$sql2 = "SELECT * FROM ride WHERE `from` ='$pFrom' AND `to` = '$pTo' AND `when` >= '$pWhen_min' AND `when` <= '$pWhen_max' ";
$query2 = mysql_query($sql2) or trigger_error("Query Failed: " . mysql_error());
}
}
function createRide($pFrom, $pTo, $pWhen, $pSeats, $pPrice, $pCar){
if (!empty($pFrom) && !empty($pTo) && !empty($pWhen) && !empty($pSeats) && !empty($pPrice) && !empty($pCar)){
$sql = "SELECT id FROM users WHERE username= '" . $username . "' LIMIT 1";
$result = mysql_query($sql);
if(!$result) {
trigger_error("ELKURTAD " . mysql_error());
}
$row = mysql_fetch_array($result);
$sql = "INSERT INTO ride (`from`, `to`, `when`, `seats`, `price`, `car`, `u_id`)
VALUES ('" . $pFrom . "', '" . $pTo . "', '" . $pWhen . "',
'" . $pSeats . "', '" . $pPrice . "', '" . $pCar . "', '" . $result . "');";
$query = mysql_query($sql) or trigger_error("Query Failed: " . mysql_error());
if ($query) {
return TRUE;
}
}
return FALSE;
}
...?>
searchRide.php - checks if the variables which are dedicated to get the search filter values have any values; (in the else statement) if there are no values, the form wasn't submitted and displays the searchRide form and after result passes the variables for the searchRide.php ( $_SERVER['PHP_SELF'] )
<?php
require_once 'config.php';
$sOutput .= '<div id="searchRide-body">';
if (isset($_GET['action'])) {
switch (strtolower($_GET['action'])) {
case 'searchride':
if (isset($_POST['when_min']) && isset($_POST['when_max']) && isset($_POST['from']) && isset($_POST['to'])) {
if (searchRide($_POST['when_min'], $_POST['when_max'], $_POST['from'], $_POST['to'])) {
while($row = mysql_fetch_array($query2)){
$sOutput .= "' ID: '" .$row['id'] . "' <br />
When: '" . $row['when'] . "' <br />
From: '" . $row['from'] . "' <br />
To: '" . $row['to'] . "' <br />
Seats left: '" . $row['seats'];
}
}
}
}
}else{
if (isset($_SESSION['error'])) {
$sError = '<span id="error">' . $_SESSION['error'] . '</span><br />';
}
$sOutput .= '<h2>Search for rides</h2>
' . $sError . '
<form name="searchride" method="post" action="' . $_SERVER['PHP_SELF'] . '?action=searchride">
From: <input type="text" name="from" value=* /><br />
To: <input type="text" name="to" value=* />
When_min: <input type="text" name="when_min" value=* />
When_max: <input type="text" name="when_max" value=* />
<br /><br />
<input type="submit" name="submit" value="Search" />
</form>
<br />
<h4>Would you like to Go back?</h4>';
}
echo $sOutput . "<br />";
echo "TEST string" . "<br />";
echo $query2 . " query2<br /> ";
echo $sql2 . " sql2<br />";
echo $row . "<br />";
?>
At the end of this code You can see some printed variables, which are used to check their values after searRide form is submitted.
I updated my database with the following data and checked with phpMyAdmin for the exact values so I can test the search with existing data:
From: TEST01
To: TEST02
When: 500
Seats: 5
Price: 7
Car: volvo
Test data submitted with the searchRide form:
From: TEST01
To: Test02
When_min: 1
Whn_max: 3000
After is press Search button on the searchRide form these are the following results (what the browser shows):
(sOutput variable
TEST WRITE TEXT
Resource id #5 (query2 variable
SELECT * FROM ride WHERE from ='TEST01' AND to = 'TEST02' AND when >= '1' AND when <= '5000' (sql2 variable
(row variable
After this I inserted the SQL query in the phpMyAdmin SQL command line and resulted the data I was searching for.
Was trying many times to figure out what could be the problem, with my own knowledge and varius searches on google, php.net and w3chools.com.
My guess is that i'm using the MYSQL_FETCH_ARRAY wrong.
following condition will not work
if (searchRide($_POST['when_min'], $_POST['when_max'], $_POST['from'], $_POST['to'])) {
as you have not return any value from searchRide function you need to return true to go into the condition.

PHP mysql while not assigning variables in correspondence to the database key

so this was working perfect up until an hour ago and since then i have racked my brain to fix it and got nothing, maybe im missing the obvious (thats usually the case).
The code prints out a list of users and a button to ban them in a table, however the problem is if you click ban on say.. the 34th user it bans the first, then if you click ban on the 56th user it bans the second user. If you see my code you should see that that shouldn't be the case (note all other details are perfectly right except for the uID):
$query = mysql_query("SELECT id, full_name, banned, username from `tblUsers`");
while($row = mysql_fetch_array($query)){
$uID = $row['id'];
if($row['banned'] == '0'){
$banBool = '<form id="ban" method="post" action="ban.php?uid='.$uID.'">
<input type="hidden" name="ban" value="" />
<a onclick="document.getElementById(\'ban\').submit();">Ban</a>
</form>'; }else{
$banBool = '<form id="unban" method="post" action="unban.php?uid='.$uID.'">
<input type="hidden" name="name" value="" />
<a onclick="document.getElementById(\'unban\').submit();">UnBan</a>
</form>' ;
}
if($row['banned'] == '1'){
$status = 'Banned';
}else{
$status = 'Active';
}
echo "<tr><td>" . $row['username'] . " " . $uID . "</td><td>" . $banBool . "</td><td>" . $status . "</td><td>" . $row['full_name'] . "</td></tr>";
}
The issue is in the action="unban.php?uid='.$uID.' as when i trace the path the id is always the lowest number (top result)
ban.php
<?php
include '../../includes/dataBase.class.php';
sql::connect();
if(!sql::checkAdmin() == 1){
header("Location: ../myaccount.php");
}
if(!isset($_GET['uid'])){
header("Location: users.php?action=1");
}
$uid = $_GET['uid'];
$ip = $_SERVER['REMOTE_ADDR'];
mysql_query("INSERT INTO `uipBan` (`ip`) VALUES ('$ip')")or die(mysql_error());
mysql_query("UPDATE tblUsers SET banned = '1' WHERE id = '$uid'")or die(mysql_error());
//header("Location: users.php?action=1");
echo $uid;
?>
You provide a form for each user which bans/unbans that user. The problem is in your form id because they're not unique. When you click on any Ban/UnBan link, JavaScript searches for the ban/unban element, finds the first one and submits that one.
The solution is very easy:
$query = mysql_query("SELECT id, full_name, banned, username from `tblUsers`");
while($row = mysql_fetch_array($query)){
$uID = $row['id'];
if($row['banned'] == '0'){
$banBool = '<form id="ban' . $uID . '" method="post" action="ban.php?uid='.$uID.'">
<input type="hidden" name="ban" value="" />
<a onclick="document.getElementById(\'ban' . $uID . '\').submit();">Ban</a>
</form>'; }else{
$banBool = '<form id="unban' . $uID . '" method="post" action="unban.php?uid='.$uID.'">
<input type="hidden" name="unban" value="" />
<a onclick="document.getElementById(\'unban' . $uID . '\').submit();">UnBan</a>
</form>' ;
}
if($row['banned'] == '1'){
$status = 'Banned';
}else{
$status = 'Active';
}
echo "<tr><td>" . $row['username'] . " " . $uID . "</td><td>" . $banBool . "</td><td>" . $status . "</td><td>" . $row['full_name'] . "</td></tr>";
}
I just included the User ID on every form and JS call so that they are unique. (Also, your second hidden field had the name as name)
Yes, #MrFusion nailed it (+1). But I still don't see why you aren't simply doing something like this:
<?php
$query = mysql_query("SELECT id, full_name, banned, username from `tblUsers`");
while($row = mysql_fetch_array($query)) {
echo "<tr><td>{$row['username']}</td><td>{$row['id']}</td>";
if($row['banned'] == '0') {
echo "<td>Ban</td>";
}
elseif($row['banned'] == '1') {
echo "<td>Banned (Unban)</td>";
}
else {
echo "<td>Active</td>"; # Not sure what this is for in your original code
}
echo "<td>{$row['full_name']}</td></tr>";
}
?>
Then just make admin.php
<?php
include "../../includes/dataBase.class.php";
sql::connect();
if(!sql::checkAdmin() == 1){
header("Location: ../myaccount.php");
}
if(!isset($_GET['ban']) AND !isset($_GET['unban'])){
header("Location: users.php?action=1");
}
if(isset($_GET['ban'])) {
$uid = mysql_real_escape_string($_GET['ban']);
mysql_query("UPDATE tblUsers SET banned = '1' WHERE id = '{$uid}'") or die(mysql_error());
//I don't know what the following two lines are for
//but they seem to IP-ban the admin himself: you're banning the IP address
//of the user doing the ban, not the IP address of the user you are banning.
$ip = $_SERVER['REMOTE_ADDR'];
mysql_query("INSERT INTO `uipBan` (`ip`) VALUES ('{$ip}')") or die(mysql_error());
}
elseif(isset($_GET['unban'])) {
$uid = mysql_real_escape_string($_GET['unban']);
mysql_query("UPDATE tblUsers SET banned = '0' WHERE id = '{$uid}'") or die(mysql_error());
}
header("Location: users.php?action=1");
?>
Note the importance of escaping your user input using mysql_real_escape_string, even if it's coming from a trusted user: this prevents SQL injection which could result in you losing your entire database :)

What is wrong with my SQL Insert code?

I'm struggling with trying to find out why this code isn't working for me. I have tables: albums (albumid, albumname), composers (composerid, composername) and tracks (trackid, tracktitle, albumid, composerid).
When I use my form to add a track and link it to a composer and an album from this:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p>Enter the new track:<br />
<textarea name="tracktitle" rows="1" cols="20"></textarea></p>
<p>Composer: <select name="cid" size="1">
<option selected value="">Select One</option>
<option value="">---------</option>
<?php while ($composer= mysql_fetch_array($composers)) {
$cid = $composer['composerid'];
$cname = htmlspecialchars($composer['composername']);
echo "<option value='$cid'>$cname</option>\n";} ?>
</select></p>
<p>Place in albums:<br />
<?php while ($alb = mysql_fetch_array($albs)) {
$aid = $alb['albumid'];
$aname = htmlspecialchars($alb['albumname']);
echo "<label><input type='checkbox' name='albs[]'
value='$aid' />$aname</label><br />\n";
} ?>
</p>
<input type="submit" value="SUBMIT" />
</form>
<?php endif; ?>
I get this message:
New track added
Error inserting track into album 2:
Track was added to 0 albums.
The php code that precedes the form is:
if (isset($_POST['tracktitle'])):
// A new track has been entered
// using the form.
$tracktitle = mysql_real_escape_string($tracktitle);
$cid= $_POST['cid'];
$tracktitle = $_POST['tracktitle'];
$albs = $_POST['albs'];
if ($cid == '') {
exit('<p>You must choose an composer for this track. Click
"Back" and try again.');}
$sql = "INSERT INTO tracks (tracktitle)
VALUES ('$tracktitle')" ;
if (#mysql_query($sql)) {
echo '<p>New track added</p>';
} else {
exit('<p>Error adding new track' . mysql_error() . '</p>
echo mysql_error() ');}
$trackid = mysql_insert_id();
if (isset($_POST['albs'])) {
$albs = $_POST['albs'];
} else {
$albs = array();
}
$numAlbs = 0;
foreach ($albs as $albID) {
$sql = "INSERT IGNORE INTO tracks (trackid, albumid,
composerid) VALUES " .
"($trackid, $albs, $cid)";
if ($ok) {
$numAlbs = $numAlbs + 1;
} else {
echo "<p>Error inserting track into album $albID: " .
mysql_error() . '</p>'; }}?>
<p>Track was added to <?php echo $numAlbs; ?> albums.</p>
<?php
else: // Allow the user to enter a new track
$composers = #mysql_query('SELECT composerid, composername
FROM composers');
if (!$composers) {
exit('<p>Unable to obtain composer list from the database.</p>');
}
$albs = #mysql_query('SELECT albumid, albumname FROM albums');
if (!$albs) {
exit('<p>Unable to obtain album list from the database.</p>');}?>
I keep searching for why this is failing and I keep hitting brick walls. I also know that at present it's not very secure which will be the next thing I sort out. I just want to get the actual function working first.
#paj: Change
if ($ok) {
to
if (mysql_query($sql)) {
-
I also suggest you update your SQL statements to
$sql = "INSERT INTO tracks (tracktitle) VALUES ('" . $tracktitle . "')";
$sql = "INSERT IGNORE INTO tracks (trackid, albumid, composerid) VALUES (" . $trackid . ", " . $albID . ", " . $cid . ")";
Looks to me like $ok doesn't exist except in the if ($ok) {
line. It needs to be defined somewhere prior, otherwise it will always read false because it doesn't exist.
Actually you can skip the $ok which doesn't exist and put in if (#mysql_query($sql)) { for that line like you have above. I do have to agree with the comments that the code needs some love, but if you want to know why it's breaking down, it appears this is why.

Categories