I am currently in the process of creating a Quiz Builder, I am having a slight issue with some DB inserts. What I am trying to do within the code is insert a Quiz Title and Description to the Quiz table which will in turn create a Quiz ID. I want to insert this Quiz ID along with Class ID values from the checkbox. Any suggestions/advice would be greatly appreciated.
Note: I know I should be using prepare statements compared to what I am currently using. I am planning on fixing this issue once I get my main functionalities working.
<form method="post" action="#">
<p>
<label>Quiz Title: </label>
<input type="text" placeholder="Insert Quiz Title here" name="quizTitle" class="form-control" />
</p>
<p>
<label>Quiz Description: </label>
<input type="text" placeholder="Insert Quiz Description here" name="description" class="form-control" />
</p>
<?php
$showAllClasses = "SELECT * FROM class";
mysqli_query($mysqli, $showAllClasses) or die ('Error finding Classes');
$showClassesResult = mysqli_query($mysqli, $showAllClasses);
echo"<table border='1' cellpadding='10' align='center'>";
echo "<tr><th></th><th>Class ID</th><th>Class Name</th><th>Class
Description</th></tr>";
//while ($row = mysqli_fetch_assoc($result)){
while ($row = $showClassesResult->fetch_object()){
echo "<tr>";
echo "<td><input type='checkbox' id='" .$row->classID . "' name='check_box[]' value='" .$row->classID . "'></td>";
echo "<td>" .$row->classID . "</td>";
echo "<td>" .$row->className . "</td>";
echo "<td>" .$row->classDesc . "</td>";
//echo "<td><button type='button' name='add' id='add' data-toggle='modal' data-target='#questionType' class='btn btn-success'>Edit Students</button></td>";
echo "</tr>";
}
if (isset($_POST['submit'])) {
//Get POST variables
$quizTitle = '"' . $mysqli->real_escape_string($_POST['quizTitle']) . '"';
$description = '"' . $mysqli->real_escape_string($_POST['description']) . '"';
//echo $quizTitle;
//echo $description;
$getQuizIDQuery = "SELECT quizID FROM quiz ORDER BY quizID DESC LIMIT 1";
mysqli_query($mysqli, $getQuizIDQuery) or die ('Error getting Quiz ID');
$result = mysqli_query($mysqli, $getQuizIDQuery);
//$insertedQuizId = $mysqli->insert_id;
//Question query
$quizCreationQuery = "INSERT INTO quiz (quizTitle, description) VALUES($quizTitle, $description)";
foreach ($_POST['check_box'] as $classID) {
$ClassQuizQuery = "INSERT INTO quiz_class(classID, quizID) VALUES ('$classID', '$result')";
//$insert_ClassQuiz = $mysqli->query($ClassQuizQuery) or die($mysqli->error . __LINE__);
//Run Query
$insert_row = $mysqli->query($quizCreationQuery) or die($mysqli->error . __LINE__);
}
}
?>
</table>
<div align="center">
<input type="submit" name="submit" value="Submit"
class="btn btn-info"/>
</div>
</form>
Here's how a working example of your code could look like (with some of the suggested changes from the comments). I kept you original code mostly as is, but changed the placement and order within your script.
Serparating HTML and PHP is one of the things you should always aim for. Once you have all the PHP code closer together, remove duplicates or unnecessary stuff (including the superflous SELECT query for the last inserted id).
I added some comments for extra explanation. The rest ist mostly untouched =)
<?php
// first - all code that should always be executed,
// this will later be used in the html output.
$showAllClasses = "SELECT * FROM class";
$showClassesResult = $mysqli->query($showAllClasses) or die ('Error finding Classes');
// now the code that should only be executed on POST request
if (isset($_POST['submit'])) {
// we only want things to happen if all queries are successful,
// otherwise we end up with quizzes without class connections.
$mysqli->begin_transaction();
//Get POST variables
$quizTitle = '"' . $mysqli->real_escape_string($_POST['quizTitle']) . '"';
$description = '"' . $mysqli->real_escape_string($_POST['description']) . '"';
//Question query
$quizCreationQuery = "INSERT INTO quiz (quizTitle, description) VALUES($quizTitle, $description)";
$mysqli->query($quizCreationQuery) or die($mysqli->error . __LINE__);
// The $mysqli instance knows the last inserted id, so we can just use that.
$insertedQuizId = $mysqli->insert_id;
foreach ($_POST['check_box'] as $classID) {
$ClassQuizQuery = "INSERT INTO quiz_class(classID, quizID) VALUES ('$classID', $insertedQuizId)";
$mysqli->query($ClassQuizQuery) or die($mysqli->error . __LINE__);
}
// Everything should have worked so we can now commit the transaction
$mysqli->commit();
}
// now that we are done with everything, we start with the html output.
// since we have done all the complicated stuff above, all we have to care
// about, is the html output and iterating over our classes to create the html table.
?>
<form method="post" action="#">
<p>
<label>Quiz Title: </label>
<input type="text" placeholder="Insert Quiz Title here" name="quizTitle" class="form-control"/>
</p>
<p>
<label>Quiz Description: </label>
<input type="text" placeholder="Insert Quiz Description here" name="description" class="form-control"/>
</p>
<table border='1' cellpadding='10' align='center'>
<tr><th></th><th>Class ID</th><th>Class Name</th><th>Class Description</th></tr>
<?php while ($row = $showClassesResult->fetch_object()): ?>
<tr>
<td><input type='checkbox' id='<?= $row->classID ?>' name='check_box[]' value='<?= $row->classID ?>'></td>
<td><?= $row->classID ?></td>
<td><?= $row->className ?></td>
<td><?= $row->classDesc ?></td>
<td><button type='button' name='add' id='add' data-toggle='modal' data-target='#questionType' class='btn btn-success'>Edit Students</button></td>
</tr>
<?php endwhile ?>
</table>
<div align="center">
<input type="submit" name="submit" value="Submit" class="btn btn-info"/>
</div>
</form>
Related
I have this table in with some rows and values in it, i get those values in my php page and user selects them and submits the same to insert the selected into another page.
So, here the main catch,
I wrote a sql query with 3 input boxes in which one takes input number from user and multiplies it with other default number in input box 2(which get the value from table1) and prints it out in input box 3.
I wrote JS code for it and it works fine. now i added php to it, in a way that input box 1 takes value directly from php table row and multiplies it with user inserted value in box2 and prints it in box 3
It still works fine even with multiple queries, cause i have made the id value of each box dynamic.
But the problem rises as when i try to submit the three input box values, it works fine for one query/when one row in table1 but when there are multiple queries, it only inserts the first query (3 input box values) and skips the rest of the queries.
My Php , Js, Html code goes as:
<?php
$sql2 = "SELECT * FROM table1 WHERE value= '$value'";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()) {
?>
<input type="number" name="input1" form="checkout" class="input1" id="input1_<?php echo $row2['id']; ?>" value="<?php echo $row2['price']; ?>">
<input type="text" name="input2" class="input2" id="input2_<?php echo $row2['id']; ?>" value="0" >
<input type="text" name="output" class="output" form="checkout" id="output_<?php echo $row2['id']; ?>" value="">
<form method="post" action="submit.php" id="checkout">
<input type="hidden" value="<?php echo $row2["id"]; ?>" name="id"/>
<button type="submit" class="btn btn-primary btn-sm btn-block">
<h4>Submit</h4>
</button>
</form>
The submit page looks like this..
$input1 = $_POST['input1'];
$output = $_POST['output'];
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO table2 (input1, output)
VALUES ('$input1', '$output')";
if ($conn->query($sql) === TRUE) {
}
else {
echo "ERROR" . $sql . "<br>" . $conn->error;
}
Now the problem is , it works fine inserting data from input1 and output boxes into tabll2 when there is only one query in table 1,
but when there are multiple queries in table 1, it only inserts the first query leaving the rest untouched with no error.
Any help is appreciated..
Then main reason is that all the text boxes for input1 field have one name, then at the result there is only one variable $_POST["input1"], so for other text boxes.
You must set an array-like names for your text boxes:
<?php
$sql2 = "SELECT * FROM table1 WHERE value= '$value'";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
?>
<form method="post" action="submit.php" id="checkout">
<?php
while($row2 = $result2->fetch_assoc()) {
?>
<input type="number" name="input1-<?php echo $row2['id']; ?>" form="checkout" class="input1" id="input1_<?php echo $row2['id']; ?>" value="<?php echo $row2['price']; ?>">
<input type="text" name="input2-<?php echo $row2['id']; ?>" class="input2" id="input2_<?php echo $row2['id']; ?>" value="0" >
<input type="text" name="output-<?php echo $row2['id']; ?>" class="output" form="checkout" id="output_<?php echo $row2['id']; ?>" value="">
<?php
}
?>
<input type="hidden" value="<?php echo $row2["id"]; ?>" name="id"/>
<button type="submit" class="btn btn-primary btn-sm btn-block">
<h4>Submit</h4>
</button>
</form>
<?php
}
?>
Then you must set the submit page:
<?php
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql2 = "SELECT * FROM table1 WHERE value= '$value'";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc()) {
$input1 = $_POST['input1-'.$row2['id']];
$output = $_POST['output-'.$row2['id']];
$sql = "INSERT INTO table2 (input1, output) VALUES ('$input1', '$output')";
if ($conn->query($sql) === TRUE) {
}
else {
echo "ERROR" . $sql . "<br>" . $conn->error;
}
}
?>
I'm in the middle of making a simple inventory system for keeping track of equipment going in and out of our doors. The inventory is stored in MYSQL, with a table looking like this: id name storage used location_storage location
This is all fun and games when I create a simple form with PHP, so it stays dynamic with the content from the server. I can update all values with no problem.
But for the sake of simplicity I'm looking into having a drop down menu, with a button, that creates/shows input fields in a form. The reason being is that I will have many rows in my table in the upcoming time. As the forms earlier have been made from server information, I will also need the scripts to be dynamic. Right now I'm stuck thinking about what I should do.
As of now, my code for the bits look like this:
"Static" PHP form:
<form action="<?php $_PHP_SELF ?>" method="POST">
<?php
//conn stuff
$sql = "SELECT id, name, storage, used, location FROM inventory";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo ' ' . $row["id"]. ' ' . $row["name"]. '<input type="text" name="newamount[' . $row["id"]. ']" />';
echo '<br>';
}
} else {
echo "0 results";
}
$conn->close();
?>
<input type="submit" name="checkout" value="Check out"/>
<input type="submit" name="checkin" value="Check in"/>
</form>
Check in PHP (check out is identical except for change of + and minus):
if(isset($_POST['sjekkinn'])){
//conn stuff
mysql_select_db( 'experimental' );
$newamount = $_POST['newamount'];
foreach($newamount as $key => $value){
$sql = "UPDATE inventory ". "SET storage = (storage + $value), used = (used - $value)". "WHERE ID = $key " ;
if (empty($value)) continue;
$retval = mysql_query( $sql, $conn );}
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully!<br>";
header("Refresh:1");
mysql_close($conn);
}
Those are all working great, but I would like to use something like the code below for a neater setup... Anyone got any advice?
Drop down list generated from MYSQL:
<form action="#" method="post">
<select name="selectinventory">
<?php
//conn stuff
$sql = "SELECT * FROM inventory";
$result = $conn->query($sql);
while ($row = $result->fetch_array()){
echo '<option value="' . $row["id"]. '">' . $row['name'] . '</option>';
}
?>
</select>
<input type="submit" name="submit" value="Add line">
</form>
Okay, so I found my own solution.
I ended up using my table-populated drop down list as I showed you in the last code box of the question. What came to my mind was that I could simply use the jQuery show/hide function.
What I did was to make a script that told (in "readable") div 'x' to show and move when option 'x' was selected and button clicked. I will show you my complete code in the end.
That way I could have my input fields each created inside a div from my table (the same that populated the drop down list), so I could manage them easier (probably possible to do it easier - but if it ain't broken, don't fix it). These were created outside the form. When I then click the previously mentioned button, the div will move inside the form. The next one I select will end up UNDER the previous one, instead of just showing up in table-order.
Feel free to shout any questions!
Here's the complete code:
<form action="<?php $_PHP_SELF ?>" method="post">
<select name="selectinventory" id="selectinventory">
<option selected="selected">Choose one</option>
<?php
//conn stuff
$sql = "SELECT id, name FROM inventory";
$result = $conn->query($sql);
$sql = "SELECT * FROM inventory";
$result = $conn->query($sql);
while ($row = $result->fetch_array()){
echo '<option value="' . $row["id"]. '">' . $row['name'] . '</option>';
}?>
</select>
<div id="btn">Add line</div>
</form>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function(){
$("#" + $("#selectinventory").val()).show();
$("#" + $("#selectinventory").val()).appendTo($(".selecteditems"));
});
});
</script>
<?php
//conn stuff
$sql = "SELECT id, name FROM inventory";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<div style="display:none" id="' . $row["id"]. '"> ' . $row["id"]. ' ' . $row["name"]. '<input type="text" name="newamount[' . $row["id"]. ']" /><br></div>
';
}
} else {
echo "0 results";
}
$conn->close();
?>
<form action="<?php $_PHP_SELF ?>" method="POST" name="isthisthearrayname">
<div class="selecteditems">
</div>
<input type="submit" name="checkout" value="Check out"/>
<input type="submit" name="checkin" value="Check in"/>
</form>
I'm in need of a bit help. I'm trying to find out how to associate a specific query (deletion of a record) with not the id of a record, but the record with which another query (selection of a record) is echoed out.
This line of code totally works when the id is specified, but again I need it for the record that gets called, where the id can skip numbers if I delete a record.
$querytwo = "DELETE FROM `paginas` WHERE id = 5";
I've got a table in my phpmyadmin database with columns 'id', 'pagetitle', 'toevoeging' (addition in Dutch) , 'message'. First one is an INT, rest are varchars/text.
This may be a stupid question, I'm sorry for that. I'm still new to PHP, and to programming in general.
Here is the code. I've commented on lines code to clarify. Thanks you!.
<?php
if (isset($_SESSION['email'])) //if the admin is active, forms can be written out.
{
echo '</nav>
<br><br> <div class="inlogscript">
<form action="verstuurd.php" method="post">
<input type="text" placeholder="Titel" method="POST" name="pagetitle" /><br><br>
<input type="text" placeholder="Toevoeging" method="POST" name="toevoeging" /><br><br>
<textarea class="pure-input-1-2" placeholder="Wat is er nieuws?" name="message"></textarea><br>
<input type="submit" value="Bevestigen" />
</form></div>';
}
?>
<div class="mainContent">
<?php
include_once("config.php"); //this is the database connection
$query = "SELECT * FROM paginas "; //selects from the table called paginas
$result = mysqli_query($mysqli, $query);
while($row = mysqli_fetch_assoc($result))
{
$pagetitle = $row['pagetitle'];
$toevoeging = $row['toevoeging'];
$message = $row['message'];
echo '<article class="topcontent">' . '<div class="mct">' . '<h2>' . "$pagetitle" .'</h2>' . '</div>' . "<br>" .
'<p class="post-info">'. "$toevoeging" . '</p>' . '<p class="post-text">' . '<br>'. "$message" . '</p>' .'</article>' . '<div class="deleteknop">' . '<form method="post">
<input name="delete" type="submit" value="Delete Now!">
</form>' . '</div>' ;
} //This long echo will call variables $pagetitle, $toevoeging and &message along with divs so they automatically CSS styled,
//along with a Delete button per echo that has the 3 variables
$querytwo = "DELETE FROM `paginas` WHERE id = 5";
if (isset($_POST['delete'])) //Deletes the query if 'delete' button is clicked
{
$resulttwo = $mysqli->query($querytwo);
}
?>
</div>
</div>
Also here is the Insert INTO query of the records. Thanks again!
$sql = "INSERT INTO paginas (pagetitle,toevoeging, message)
VALUES ('$_POST[pagetitle]','$_POST[toevoeging]','$_POST[message]')";
//the insertion into the table of the database
if ($MySQLi_CON->query($sql) === TRUE) {
echo "";
} else {
echo "Error: ". $sql . "" . $MySQLi_CON->error;
}
This won't be sufficient but, to begin with your echo :
echo '<article class="topcontent">
<div class="mct">
<h2>' . $pagetitle .'</h2>
</div><br>
<p class="post-info">'. $toevoeging . '</p>
<p class="post-text"><br>'.$message.'</p>
</article>
<div class="deleteknop">
<form method="post">';
// you ll want to use $_POST["id"] array to delete :
echo '<input type="hidden" name="id" value="'.$row['id'].'">
<input name="delete" type="submit" value="Delete Now!">
</form>
</div>' ;
I am a complete beginner, so please bear with me. This is just a test project I am putting together to try to teach myself some of the basics.
I know that a lot of my commands are outdated and/or susceptible to injection, but I'd rather stick with this for now (many reasons).
I just had a question about trying to use SELECT from WHILE, and figured that out and got it to echo the correct response on the page.
Now, how do I make it echo that as a value for an HTML text box? It won't work, and I've tried to look for typos but I don't know what I am doing, frankly.
I see that the $studentid and $teacherinfo show fine, I presume because they are normal variables.
Can I somehow define two more variables for first name and last name further up in the page so that I do not need to include so much code in each input (and to keep it from being buggy)?
Here is my code for the page. The inputs will be hidden, but I have been making them text boxes for debugging purposes.
<?php
$connection = mysql_connect($serverName, $userName, $password) or die('Unable to connect to Database host' . mysql_error());
$dbselect = mysql_select_db($dbname, $connection) or die("Unable to select database:$dbname" . mysql_error());
$studentid = $_POST['student_id'];
$teacherinfo = $_POST['teacher'];
$result = mysql_query("SELECT `first_name` FROM `students` WHERE student_id = '$studentid'",$connection);
?>
</head>
<body>
<div align="center">
<form method="post" action="vote_post.php">
<h1>Vote for Teacher of the Month</h1>
<h4>(step 2 of 2)</h4>
<h2>Confirm the Information Below</h2>
<h5>Student id: <?php echo $studentid ?></br>
Student first name: <?php
while($row = mysql_fetch_array($result)){
echo $row['first_name'];
}
?>
</br>
Voted for: <?php echo $teacherinfo ?>
</h5>
<input type="text" name="student_id" value="<?php echo $studentid; ?>"/></br>
<input type="text" name="first_name" value="<?php while($row = mysql_fetch_array($result)){
echo $row['first_name'];
} ?>"/>
</br>
<input type="text" name="last_name" value="<?php while($row = mysql_fetch_array($result)){
echo $row['last_name'];
} ?>"/>
</br>
<input type="text" name="teacher" value="<?php echo $teacherinfo; ?>"/></br>
<input type="submit" value="Submit Vote" class="inputbutton"/></br></br></br>
</form>
You can't use while because your query return only one student. You have to use if instead of while. If your query return many students you can use while.
Try this code:
<?php
if($row = mysql_fetch_array($result)){
?>
Student first name: <?php echo $row['first_name'];?>
</br>
Voted for: <?php echo $teacherinfo ?></h5>
<input type="text" name="student_id" value="<?php echo $studentid; ?>"/></br>
<input type="text" name="first_name" value="<?php echo $row['first_name'];?>"/></br>
<input type="text" name="last_name" value="<?php echo $row['last_name'];?>"/></br>
<input type="text" name="teacher" value="<?php echo $teacherinfo; ?>"/></br>
<input type="submit" value="Submit Vote" class="inputbutton"/></br></br></br>
<?php
}
?>
I hope this help.
I tried to build a code that will help you. Remember that you use last_name, but does not return the field in SQL.
</head>
<body>
<div align="center">
<form method="post" action="vote_post.php">
<h1>Vote for Teacher of the Month</h1>
<h4>(step 2 of 2)</h4>
<h2>Confirm the Information Below</h2>
<?php
$connection = mysql_connect($serverName, $userName, $password) or die('Unable to connect to Database host' . mysql_error());
$dbselect = mysql_select_db($dbname, $connection) or die("Unable to select database:$dbname" . mysql_error());
$studentid = $_POST['student_id'];
$teacherinfo = $_POST['teacher'];
$result = mysql_query("SELECT `first_name`,`last_name`,`student_id` FROM `students` WHERE student_id = $studentid",$connection);
while($row = mysql_fetch_array($result)){
echo "<h5>Student id: $row['student_id'] </br>" .
"Student first name: $row['first_name'] </br>" .
"Voted for: $teacherinfo </h5> " .
"<input type='text' name='student_id' value='$row[\'student_id\']' /></br>" .
"<input type='text' name='first_name' value='$row[\'first_name\']' /></br>" .
"<input type='text' name='last_name' value='$row[\'last_name\']' /></br>" .
"<input type='text' name='teacher' value='$teacherinfo' /></br>"
}
?>
<input type="submit" value="Submit Vote" class="inputbutton"/></br></br></br>
</form>
WHILE I left because I do not know if your query can return more than one record, despite appearing to be a key. If you do not need to check the response of the Ragnar.
I made a nice flowchart for you since this is kind of complicated.
Basically, I want to have a list of fields from a column in the database, displayed in a table. They have an EDIT button ext to them, and when you click the edit button you can edit the field. Then you click submit and it alters the table with the new value.
I pretty much know how to do each of the individual things, but I am having trouble combining all these things into one.
Flowchart:
Code:
STEP 1:
<table>
<th>First Name</th>
<?php
// Collects data from "users" table
$data = mysql_query("SELECT * FROM users")
or die(mysql_error());
// array
$info = mysql_fetch_array( $data );
// print data
// Print out the contents of the entry
Print "<tr><td>";
Print "".$info['fname'] . " ";
Print "</td><td>";
Print "".$info['lname'] . " ";
Print "</td><td>";
Print "".$info['email'] . " <br>";
Print "</td></tr>";
// loop for each row in the column
while($info = mysql_fetch_array( $data ))
{
Print "".$info['fname'] . " ";
Print "</td><td>";
Print "".$info['lname'] . " ";
Print "</td><td>";
Print "".$info['email'] . " <br>";
Print "</td></tr>";
}
?>
</table>
STEPS 2 & 3: (incomplete or possibly inaccurate as well)
<?php
if(isset($_POST['submit'])){
$variable = "somethinghere";
$variable = "somethinghere";
$variable = "somethinghere";
$variable = "somethinghere";
$variable = "somethinghere";
$query = "UPDATE users
SET fname='$variable1'
WHERE $variable2='$variable3' AND $variable4='$variable5'
(fname, lname, email) VALUES ('".$_POST['fname']."', '".$_POST['lname']."', '".$_POST['email']."')";
mysql_query($query);
}else{
?>
<div class="content">
<form method="post">
<div><strong>First Name:</strong><span class="errortext">*</span></div>
<div><input name="fname" type="text" /></div>
<div><strong>Last Name:</strong><span class="errortext">*</span></div>
<div><input name="lname" type="text" /></div>
<div><strong>Email:</strong><span class="errortext">*</span></div>
<div><input name="email" type="text" /></div>
<div><input id="submit-button" value="submit" name="submit" type="submit" /></div>
</form>
<?php }?>
</div>
Using JQuery is the way to change it.
Here's a plugin: http://www.appelsiini.net/projects/jeditable/default.html ; http://www.appelsiini.net/projects/jeditable