What is wrong with my SQL Insert code? - php

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.

Related

Saving a value from select option to database

So i am trying to insert some data in my database, unfortunatly it doesn't work as i hoped.
This is my index.php file here i made a little piece of php code to get the select options from my database(this works fine). But now i want people to select from the options in my database and store the selected option in another db table.
<?php
$query = "SELECT event_naam FROM events";
$result2 = mysqli_query($dbconn, $query);
$options = "";
while($row2 = mysqli_fetch_array($result2))
{
$options = $options."<option>$row2[0]</option>";
}
?>
<form class="inschrijven" method="POST" action="includes/inscscript.php">
<select name="iselect">
<?php echo $options;?>
</select><br><br>
<span>Uw Naam: </span><input type="text" name="inaam" placeholder="Naam"><br>
<span>Leeftijd: </span><input type="number" name="leeftijd"><br>
<span>Aantal Personen:</span><input type="number" name="personen"><br>
<input type="submit" name="inschrijven" value="Inschrijven!">
</form>
I have tried this, but it doesn't do anything it also doesn't give an error.
require_once 'connectie.php'; //Connection to Database File
$sql = "INSERT INTO inschrijven (inschrijf_event, inschrijf_naam, inschrijf_leeftijd, inschrijf_personen) VALUES
('".$_POST['iselect']."','".$_POST['inaam']."','".$_POST['leeftijd']."','".$_POST['personen']."')";
if ($dbconn->query($sql) === TRUE) {
header( "Location: ../index.php" );
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $dbconn->error."');</script>";
}
$dbconn->close();
This is my inscscript.php file
I tried searching for similair qeustions but couldn't find anything like this.
$query = "SELECT event_naam FROM events";
$result=mysqli_query($con,$query)
{
// Return the number of rows in result set
while($rowcount=mysqli_num_rows($result)){
echo "<option value='".$rowcount['event_naam']."'>".$rowcount['event_naam']."</option>
}
Include this php file to your html between select opend and closing tags

UPDATE table with checkboxes

I have the facility to update what I call 'documents' (ver similar to creating a post) on my cms which works fine but I have introduced categories where the documents are associated to them. Now I have managed to bind them when creating the doc from new but when trying update them I am getting a bit stuck. I am using checkboxes to show the list of categories and when selected it updates a join table which uses the doc_id and the cat_id.
Here is the script for updating the doc:
<?php
include ('includes/header.php');
require ('../../db_con.php');
echo '<h1>Document Edit</h1>';
// Check for a valid document ID, through GET or POST:
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) ) { // From view_docs.php
$id = $_GET['id'];
} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) ) { // Form submission.
$id = $_POST['id'];
} else { // No valid ID, kill the script.
echo '<p class="error">This page has been accessed in error.</p>';
exit();
}
// Check if the form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array();
// Check for a document name:
if (empty($_POST['doc_name'])) {
$errors[] = 'You forgot to enter your document name.';
} else {
$dn = mysqli_real_escape_string($dbc, trim($_POST['doc_name']));
}
// Check for a document content:
if (empty($_POST['doc_content'])) {
$errors[] = 'You forgot to enter your last name.';
} else {
$dc = mysqli_real_escape_string($dbc, trim($_POST['doc_content']));
}
if (empty($errors)) { // If everything's OK.
// Test for unique doc title:
$q = "SELECT doc_id FROM docs WHERE doc_name='$dn' AND doc_id != $id";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) == 0) {
// Make the query:
$q = "UPDATE docs SET doc_name='$dn', doc_content='$dc', doc_name='$dn' WHERE doc_id=$id LIMIT 1";
$r = mysqli_query ($dbc, $q);
if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.
$doc_id = mysqli_insert_id($dbc);
$query = "UPDATE doc_cat_join (cat_id,doc_id) VALUES ";
$cat_ids = $_POST['cat_id'];
$length = count($cat_ids);
for ($i = 0; $i < count($cat_ids); $i++) {
$query.='(' . $cat_ids[$i] . ',' . $doc_id . ')';
if ($i < $length - 1)
$query.=',';
}
// Print a message:
echo '<p>The document has been edited.</p>';
} else { // If it did not run OK.
echo '<p class="error">The document could not be edited due to a system error. We apologize for any inconvenience.</p>'; // Public message.
echo '<p>' . mysqli_error($dbc) . '<br />Query: ' . $q . '</p>'; // Debugging message.
}
} else { // Already used.
echo '<p class="error">The document name has already been used.</p>';
}
} else { // Report the errors.
echo '<p class="error">The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo " - $msg<br />\n";
}
echo '</p><p>Please try again.</p>';
} // End of if (empty($errors)) IF.
} // End of submit conditional.
// Always show the form...
// Retrieve the document's information:
$q = "SELECT * FROM docs WHERE doc_id=$id";
$r = mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) == 1) { // Valid document ID, show the form.
// Get the document's information:
$row = mysqli_fetch_array ($r, MYSQLI_NUM);
// Create the form:
echo '<form action="edit_doc.php" method="post">
<p>Document Name: <input type="text" name="doc_name" size="15" maxlength="15" value="' . $row[1] . '" /></p>
<textarea name="doc_content" id="doc_content" placeholder="Document Content" style="display: none;"></textarea>
<iframe name="editor" id="editor" ></iframe>'
?>
<div class="row">
<div class="col-group-1">
<?php
$q = "SELECT * FROM cats";
$r = mysqli_query ($dbc, $q); // Run the query.
echo '<div class="view_body">';
// FETCH AND PRINT ALL THE RECORDS
while ($row = mysqli_fetch_array($r)) {
echo '<br><label><input type="checkbox" name="cat_id[]" value="' . $row['cat_id'] . '">' . $row["cat_name"] . '</label>';
}
echo '</div>';
?>
</div>
</div>
<br><br>
<input onclick="formsubmit()" type="submit" value="Update Document" name="submit"/>
<?php echo'
<input type="hidden" name="id" value="' . $id . '" />
</form>
<br><br>Back to docs list';
} else { // Not a valid document ID.
echo '<p class="error">This page has been accessed in error.</p>';
}
?>
<?php
mysqli_close($dbc);
?>
So I have three tables:
docs
doc_id
doc_name
doc_content
cats
cat_id
cat_name
doc_cat_join
doc_id
cat_id
the join table related the doc_id and cat_id which then associates them together. I am guessing in my script when I update a doc it will need to delete the rows and then re-insert them? I just need to know a way or the easiest way of updating the join table as I am a tad stuck...
In case of checkbox update you need to delete previous stored checkbox of with appropriate id and insert new one you can't update checkbox as we can't predict how many checkbox will be selected by user....
Case:
It may happen that user remove one checkbox at update time so you will never know which one to be deleted.......
In your code...
docs
doc_id
doc_name
doc_content
cats
cat_id
cat_name
doc_cat_join
id
doc_id
cat_id
here you have to delete old checkbox of updation doc,
DELETE FROM doc_cat_join WHERE cat_id = some_id
next you can insert selected checkbox as you are inserting first time...

Possible To Use Insert Query In Fetch Array

I am not sure why this hasn't been answered yet will not that I know of, I am wondering if it's possible to add a insert query with in a while loop I have tried,
but it keeps inserting the comment more then it should (say if it finds 4 status updates it will post the comment in the database 4 times)
I know I have the insert query twice this is not the problem as I had the query where it submits a comment to the database the current query is there for testing purposes.
<?php
require_once ("core/connection.php");
require_once ("core/group_functions.php");
//We need to post the message update in to the database
if(isset($mybb->input['post_message_submit'])) {
$post_message_submit = $mybb->input['post_message_submit'];
$post_message = $mybb->input['post_message'];
$comment_post = $mybb->input['comment_post'];
if(($post_message_submit) && ($post_message)) {
$insert_query = $db->query("INSERT INTO " . TABLE_PREFIX . "groups_posts" . "(posted_by, group_name, post_body)
VALUES ('$mybb_username', '$get_group_url' ,'$post_message')");
} else {
echo "<text style='color:red;'> You Must Specify A Message</a></text>";
}
}
echo "
<form action='' method='POST'>
<textarea name='post_message' id='post_message' placeholder='Whats Going On?'></textarea><br>
<input type='submit' name='post_message_submit' value='Post'>
</form>
";
$fetch_index_query = $db->query("SELECT post_id,posted_by,post_body,post_active,group_name FROM " . TABLE_PREFIX . "groups_posts WHERE group_name='$get_group_url'");
while($fetch_index_groups_array = $db->fetch_array($fetch_index_query)) {
$post_id_row = $fetch_index_groups_array['post_id'];
$posted_by = $fetch_index_groups_array['posted_by'];
$g_name = $_fetch_index_groups_array['g_name'];
$g_body = $fetch_index_groups_array['post_body'];
echo"<br>" . "<a href=''> $posted_by </a>" . "<br>" . $gname
. "<br>____________";
$fetch_comments_query = $db->query("SELECT g_name,post_body,comment_by FROM spud_groups_comments WHERE post_id='$post_id_row'");
while($fetch_groups_comments = $db->fetch_array($fetch_comments_query)) {
$post_body = $fetch_groups_comments['post_body'];
echo ("<br>" . $post_body);
}
$insert_query2 = $db->query("INSERT INTO " . TABLE_PREFIX . "groups_comments" . "(comment_by, post_id, post_body)
VALUES ('$mybb_username', '$post_id_row' ,'$comment_post')");
echo "<br>
<form action='' method='POST'>
<input type='text' name='comment_post' placeholder='Comment then Hit Enter'>
</form>
";
}
//We have done everything we need to do we can now exit and not execute anything beyond this point
exit();
?>
Try to instantiate other $DB object for the insert query. i.e. do not use the same one you are using to fetch the array, as the next use will overwrite the result of the first query that you are looping through.

Fields inserting blank data into database

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']."',

PHP/Mysql Create thread then redirect to forum category

Basically I have edited the "new_topic" page in my generic forum so that the user can select the category of the post from a drop down list, rather than goto the category first and going to new topic, what I am trying to do now is when the thread is created, rather than jumping to the standard "your new thread was created here" it redirect to the category the topic was made under.
I tried using
header( "Location: category.php?id='. $topic_cat . '" );
But header was already being used elsewhere.
So I found a meta refresh that works to an extent..
echo "<META HTTP-EQUIV='Refresh' Content='0; URL=/category.php?id='. $topic_cat .'>";
But it redirects to "category.phpid=" and outputs the following message..
The category could not be displayed, please try again later.You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 8
Is there anyway I can make the page jump to the category that is only being defined in the submit function itself? Thanks for any help.
EDIT: would using "if" functions work to define the redirect? ie. if topic_cat 2 is selected in the form redirect to category.phpid=2??
Sorry I am very new to PHP and still trying to get my head around it all :(
Here is the topic creation page in it's entirety
<?php
//create_topic.php
include 'connect.php';
if($_SESSION['signed_in'] == false)
{
//the user is not signed in
echo 'Sorry, you have to be signed in to create a topic.';
}
else
{
//the user is signed in
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
//the form hasn't been posted yet, display it
//retrieve the categories from the database for use in the dropdown
$sql = "SELECT
cat_id,
cat_name,
cat_description
FROM
categories";
$result = mysql_query($sql);
if(!$result)
{
//the query failed, uh-oh :-(
echo 'Error while selecting from database. Please try again later.';
}
else
{
if(mysql_num_rows($result) == 0)
{
//there are no categories, so a topic can't be posted
if($_SESSION['user_level'] == 1)
{
echo 'You have not created categories yet.';
}
else
{
echo 'Before you can post a topic, you must wait for an admin to create some categories.';
}
}
else
{
echo '<form method="post" action="">';
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 '<textarea name="post_content" /></textarea><br /><br />
<input type="submit" value="Create topic" />
</form>';
}
}
}
else
{
//start the transaction
$query = "BEGIN WORK;";
$result = mysql_query($query);
if(!$result)
{
//Damn! the query failed, quit
echo 'An error occured while creating your topic. Please try again later.';
}
else
{
//the form has been posted, so save it
//insert the topic into the topics table first, then we'll save the post into the posts table
$sql = "INSERT INTO
topics(topic_subject,
topic_date,
topic_cat,
topic_by)
VALUES('" . mysql_real_escape_string($_POST['post_content']) . "',
NOW(),
" . mysql_real_escape_string($_POST['topic_cat']) . ",
" . $_SESSION['user_id'] . "
)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'An error occured while inserting your data. Please try again later.<br /><br />' . mysql_error();
$sql = "ROLLBACK;";
$result = mysql_query($sql);
}
else
{
//the first query worked, now start the second, posts query
//retrieve the id of the freshly created topic for usage in the posts query
$topicid = mysql_insert_id();
$sql = "INSERT INTO
posts(post_content,
post_date,
post_topic,
post_by)
VALUES
('" . mysql_real_escape_string($_POST['post_content']) . "',
NOW(),
" . $topicid . ",
" . $_SESSION['user_id'] . "
)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'An error occured while inserting your post. Please try again later.<br /><br />' . mysql_error();
$sql = "ROLLBACK;";
$result = mysql_query($sql);
}
else
{
$sql = "COMMIT;";
$result = mysql_query($sql);
echo "<META HTTP-EQUIV='Refresh' Content='0; URL=/category.php?id=". $topic_cat ."'>";
}
}
}
}
}
; ?>
echo "<META HTTP-EQUIV='Refresh' Content='0; URL=/category.php?id=" . $topic_cat . "'>";
That should work. You needed to put double quotation-marks outside the . $topic_cat . variable like so; " . $topic_cat . "

Categories