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...
Related
Messages I want to delete a receiver name and our messages or the entire receiver row in the database in the display page.I have 2 codes to show, 1st is the displaying page, next is the delete page. When I press the x image, it will not delete any receiver name and our messages. I wonder if the request id in the index.php I made is effective or not. Consider my codes below:
main page / index.php
$q = 'SELECT DISTINCT `receiver_name`,`sender_name`,`id`
FROM `messages` WHERE
`sender_name`="' . $_SESSION['username'] . '" OR
`receiver_name`="' . $_SESSION['username'] . '"
ORDER BY `date_time` DESC';
$r = mysqli_query($con, $q);
if ($r) {
if (mysqli_num_rows($r) > 0) {
$counter = 0;
$added_user = array();
while ($row = mysqli_fetch_assoc($r)) {
$sender_name = $row['sender_name'];
$receiver_name = $row['receiver_name'];
$id = $row['id'];
if ($_SESSION['username'] == $sender_name) {
//add the receiver_name but only once
//so to do that check the user in array
if (in_array($receiver_name, $added_user)) {
//dont add receiver_name because
//he is already added
} else {
//add the receiver_name
?>
<div class="grey-back">
<img src="images/profile_user.jpg" class="image"/>
<?php echo '' . $receiver_name . '';
echo '<img src="x.png" style="width:12px; height:12px; float:right;">';
?>
</div>
<?php
//as receiver_name added so
///add it to the array as well
$added_user = array($counter => $receiver_name);
//increment the counter
$counter++;
}
} elseif ($_SESSION['username'] == $receiver_name) {
//add the sender_name but only once
//so to do that check the user in array
if (in_array($sender_name, $added_user)) {
//dont add sender_name because
//he is already added
} else {
//add the sender_name
?>
<div class="grey-back">
<img src="images/profile_user.jpg" class="image"/>
<?php echo '' . $sender_name . ''; ?>
</div>
<?php
//as sender_name added so
///add it to the array as well
$added_user = array($counter => $sender_name);
//increment the counter
$counter++;
}
}
}
} else {
//no message sent
echo '<div style="float:left; padding: 70px 0 0 150px;">';
echo 'no user';
echo '</div>';
}
} else {
//query problem
echo $q;
}
delete page
require_once "connection.php";
$id = $_REQUEST['id'];
mysqli_query($con, "DELETE FROM messages WHERE id=$id");
header("location: index.php");
I see one problem:
echo '<img src="x.png" style="width:12px; height:12px; float:right;">';
will output
<img src="x.png" style="width:12px; height:12px; float:right;">
but if $id=76, I'd guess you want it to be:
To do that try:
echo '';
And if $id is something more complex, with symbols & whatnot, then id='.$id.' becomes id='.urlencode($id).'.
That might be your problem. If it still doesn't work, let me know what output & error messages you are getting
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";
I have multiple text boxes displaying a string corresponding to a row in the mysql database. I want to be able to change each string in the database by typing in the textbox and clicking submit.
So I create my text boxes with a while loop after connecting to the DB.
<form action="<?php $self ?>" form method="post">
<?php
$query = "SELECT * FROM `table` ORDER BY table.ID DESC";
$result = #mysql_query($query) or die('
ERR: The database returned an unexpected error.
');
$num=mysql_numrows($result);
$change="";
$i=0;
while ($i < $num) {
$post=mysql_result($result,$i,"post");
$id=mysql_result($result,$i,"ID");
$ts=mysql_result($result,$i,"timeStamp");
$page = html_entity_decode($post);
$output = stripslashes($page);
if ($output != "") {
echo '<textarea name="' . $id . '" rows="4" cols="70">' . $output . '</textarea><div class="time"><font face="monospace">' . $ts . '</font></div>';
} //creates tables for each filled entry with a name corrsponing to its auto-increment id.
$i++;
}
?>
<input name="send" type="hidden" />
<div class="mod">
<p><input class="master" type="submit" value="Mod" /></p></div><!--submit button is called "Mod"-->
</form>
</body>
</html>
Everything displays properly. If the database has 4 rows with text in them than it will display those 4, each in a separate text box.
Now I want to replace the text in the database with whatever the user enters in the text boxes. This is the code I tried. It does nothing.
<?php
$i=0;
while ($i < $num) {
$id=mysql_result($result,$i,"ID");
$post=mysql_result($result,$i,"post");
if (!isset($_POST[$id])) {
$_POST[$id] = "";
}
$change = $_POST[$id];
mysql_query("UPDATE 'database'.'table' SET 'post' = '$change' WHERE 'table'.'ID' ='$id';");
$i++;
}
Basically the loop will run once for every row in the table. For every text box, it should UPDATE 'database'.'table' with $_POST[1] for 'post' with ID '1', $_POST[2] for 'post' with ID '2', etc...
Instead nothing happens.
Any help would be appreciated.
As Prowla mentioned , you should use PDO instead of mysql_ functions.
Anyway, I improved your code and it suppose to work now:
<form action="<?php $self ?>" form method="post">
<?php
$query = "SELECT * FROM `table` ORDER BY table.ID DESC";
$result = #mysql_query($query) or die('Query error:'.mysql_error());
$num=mysql_num_rows($result);
$change="";
while($post = mysql_fetch_array($result))
{
/*
$post = array(
'post' => '....',
'ID' => '...',
'timeStamp' => '...'
);
*/
$page = html_entity_decode($post['post']);
$output = stripslashes($page);
if ($output != "") {
echo '<textarea name="posts['.$post['ID'].']" rows="4" cols="70">' . $output . '</textarea><div class="time"><font face="monospace">' . $post['timeStamp'] . '</font></div>';
} //creates tables for each filled entry with a name corrsponing to its auto-increment id.
}
?>
<input name="send" type="hidden" />
<div class="mod">
<p><input class="master" type="submit" value="Mod" /></p></div><!--submit button is called "Mod"-->
</form>
</body>
</html>
The php update file:
$query = "SELECT * FROM `table` ORDER BY table.ID DESC";
$result = #mysql_query($query) or die('Query error:'.mysql_error());
while($update_post = mysql_fetch_array($result))
{
$update = (isset($_POST[$update_post['ID']])) ? $_POST[$update_post['ID']] : "";
if($update != "")
{
mysql_query("UPDATE 'database'.'table' SET 'post' = '$update' WHERE 'table'.'ID' ='".$update_post['ID']."';");
echo "<!--POST ID ".$update_post['ID']." been updated-->\n";
}
}
I added an html comment (<!-- -->) so you can check if the update actually takes place.
This way you can debug your code. (you should also read about print_r , var_dump)
I am dynamically generating a set of radio buttons from MySQL. The buttons are creating and the variables assigned to them are populating as I did an echo print_r and it shows the array for the variable. I now want to compare the values generated from this and if the vale is "0" I want to insert a score and present a green check graphic and the word correct. If the value is "1" I want it to input different values for the score and present Incorrect and a red X graphic. Here is what I have so far (Everything populates dynamically both the question and the answers as radio buttons):
<?php
echo '<form id="frmQuestion" name="frmQuestion" method="post" action="QuizQuestion1.php">';
// Connect to the Database
require_once('mysqli_connect.php');
//create the query for the question
$q = "SELECT `Question` FROM tbl_Question WHERE QuestionID = 1";
//Create the query for the Answers
$q2 = "SELECT `Answer`,`AnswerStatusID`,`AnswerResponse` FROM tbl_Answer WHERE QuestionID = 1";
//Run the query
$r = mysqli_query($conn,$q);
//run the answer query
$r2 = mysqli_query($conn,$q2);
while($row = mysqli_fetch_array($r,MYSQLI_ASSOC)){
echo '<div id="Question1"><p> ' . $row['Question'] . '</div></p>';
}
//Declare the variables as a array
$AnswerResponse = array();
$AnswerStatusID = array();
while($row2 = mysqli_fetch_array($r2,MYSQLI_ASSOC)){
echo '<div id="Question1"><input name="q1" type="radio" value="'.$AnswerStatusID.'"/>' . $row2['Answer'] . '</div><br/>';
//Assign the AnswerStatusID to a var
$AnswerStatusID[] = $row2['AnswerStatusID'];
//Assign the AnswerResponse to a var
$AnswerResponse[] = $row2['AnswerResponse'];
}
//Create the submit button
echo '<input type="submit" value="Submit Answer" name="submit"/>';
echo '</form>';
//Logic for correct or incorrect answers
if (isset($_POST['q1']) && ($_POST['q1'] == '0'))
{
//create the query for the score
$q3 = "INSERT INTO tbl_Score (`Score`,`QuestionID`) VALUES ('100%','1')";
//Run the query
$r = #mysqli_query ($conn,$q3);
if($r){
//Confirm message data was entered with a correct response and a graphic
echo '<h1>Correct!!</h1><img src="/images/green_Check_Low.jpg" alt="Green Check"/>';
echo 'Click here for the next question';
}
else
{
//there was an error
echo'<h1>System error</h1>';
//Debugging message
echo'<p>' . mysqli_error($conn) . '<br/><br/>Query:' . $q3 . '</p>';
}//End of nested IF
}
else{
//create the query for the score
$q4 = "INSERT INTO tbl_Score (`Score`,`QuestionID`) VALUES ('0%','1')";
//Run the query
$r2 = #mysqli_query ($conn,$q3);
if($r2){
//Confirm message data was entered with a correct response and a graphic
echo '<h1>Incorrect!!</h1><img src="/images/red_X_Low.jpg" alt="Red X"/>';
echo 'Click here for the next question';
}
else
{
//there was an error
echo'<h1>System error</h1>';
//Debugging message
echo'<p>' . mysqli_error($conn) . '<br/><br/>Query:' . $q3 . '</p>';
}//End of nested IF
}
//Free up the results for the Question query
mysqli_free_result($r);
//Free up the results from the Answer query
mysqli_free_result($r2);
//close the DB connection
mysqli_close($conn);
?>
This is the answer and work as intended. Thanks for everyones input.
//Declare the variables as a array
$AnswerResponse = array();
$AnswerStatusID = array();
while($row2 = mysqli_fetch_array($r2,MYSQLI_ASSOC)){
echo '<div id="Question1"><input name="q1" type="radio" value="'.$row2['AnswerStatusID'].'"/>' . $row2['Answer'] . '</div><br/>';
//Assign the AnswerStatusID to a var
$AnswerStatusID[] = $row2['AnswerStatusID'];
//Assign the AnswerResponse to a var
$AnswerResponse[] = $row2['AnswerResponse'];
}
//Create the submit button
echo '<input type="submit" value="Submit Answer" name="submit"/>';
echo '<input type="hidden"name="submitted"value="TRUE"/>';
echo '</form>';
if($_POST['submitted']) {
//Logic for correct or incorrect answers
if (isset($_POST['q1']) && ($_POST['q1'] == '0'))
{
//create the query for the score
$q3 = "INSERT INTO tbl_Score (`Score`,`QuestionID`) VALUES ('100%','1')";
//Run the query
$r3 = #mysqli_query ($conn,$q3);
//Confirm message data was entered with a correct response and a graphic
echo '<h1>Correct!!</h1><img src="/images/green_Check_Low.jpg" alt="Green Check"/>';
echo 'Click here for the next question';
}
else{
//create the query for the score
$q4 = "INSERT INTO tbl_Score (`Score`,`QuestionID`) VALUES ('0%','1')";
//Run the query
$r4 = #mysqli_query ($conn,$q4);
//Confirm message data was entered with a correct response and a graphic
echo '<h1>Incorrect!!</h1><img src="/images/red_X_Low.jpg" alt="Red X"/><br/>';
echo 'Click here to try again';
}
}
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.