input type hidden does'nt post - php

I have a system where people can indicate whether they are attending an event. There are several events to choose from. The events come from the database and have a unique id. Everything works fine, except the event and date can't be posted together. Only when I make a checkbox of the date (or the event) everything neatly posted. A hidden textfield always posts the wrong date or event.
<form action="insert.php" method="post">
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "user", "pass", "db");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM events WHERE datum >= CURDATE() AND toon > 0 ORDER BY datum";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
echo "<input type=\"radio\" id=\"datum\" name=\"datum\" value=\" "; echo "" . $row['datum'] . "\" required> ";
echo "<input type=\"checkbox\" id=\"event\" name=\"event\" value=\" "; echo "" . $row['event'] . "\"> ";
print date('l d/m/Y', strtotime($row['datum']));
echo " • ";
if(strlen($row['url']) > 0):
echo " <a href=\" " . $row['url'] . " \" target=\"_blank\">";
endif;
echo "" . $row['event'] . "</a>";
echo " • " . $row['info'] . "";
echo "<br>";
}
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
<br><br>
<label for="naam">Naam:</label>
<input type="text" name="naam" id="naam" placeholder="Jouw naam..." required>
<input type="hidden" id="mee" name="mee" value="mee">
<label for="opmerking">Opmerking:</label>
<input type="text" name="opmerking" id="opmerking" placeholder="Eventuele opmerkingen...">
<input type="hidden" id="toon" name="toon" value="0">
<input type="submit" value="Ik ga mee!" class="w3-button w3-black">
</form>
</div>

There are a number of issues
Each input must have a different name, otherwise how are you going to know which one has been entered?
Because you have used escape characters for the double quotes, there is confusion there. To, clarify I have used single quotes inside.
Each id must also be unique
As a suggestion, in the loop
$event = $row['event'];
echo "<input type='radio' id='datum-$event' name='datum-$event' value='' $row['datum'] required> ";
So, now the id and name are unique. When this radio button is selected you will have
$_POST['datum-eventname'];
You dont need two inputs in the loop.

Related

Insert php sql row record into hidden form input value field

I'm trying to insert sql ID record inside php echo form input value. Values that are inserted manualy via input field (by typing) are being displayed fine. Value inside input (named: potnik) is not being displayed. Is it ignored because is inside echo or is inserted wrong?
$sql3 = "
SELECT id, potnik_id, ura, naslov
FROM prevoznik
ORDER BY HOUR(ura), MINUTE(ura) ASC;
";
$result = $conn->query($sql3);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//Spremenjena oblika datuma
$date = date_create($row["ura"]);
$ura_pobiranja = date_format($date,"H:i");
echo "<div class=\"row list divider-gray\">
<div class=\"col-1 fs-09 fw-600\">" . $row["id"] . " </div>
<div class=\"col-3 flex-vcenter-items fw-600 fs-09\">" . $row["naslov"] . " </div>
<div class=\"col-1 flex-vcenter-items fw-600 fs-09\">$ura_pobiranja</div>
";
if ($row["naslov"] !== null) {
echo " <div class=\"col-6 flex-vcenter-items fs-1\">Nastavi uro<form action='update.php?id=" . $row["id"] . "\"' method='POST'><input name=\"potnik\" value='".$row["id"]."' type='hidden' /> <input class=\"form-control fancy-border\" type=\"text\" name=\"posodobljeni_cas\"/><input type='submit' value='Posodobi'> </form></div>";
echo " </div>";
}
else {
echo " </div>";
}
}
} else {
echo "<div class=\"col flex-vcenter-items fw-100 fs-1\"><i class=\"far fa-frown-open pr-3\"></i>Nimaš še nobenih opravil
</div>";
}
Code that isn't working (hidden input field value):
echo " <form action='update.php?id=" . $row["id"] . "\"' method='POST'><input name=\"potnik\" value='".$row["id"]."' type='hidden' /> <input class=\"form-control fancy-border\" type=\"text\" name=\"posodobljeni_cas\"/><input type='submit' value='Posodobi'> </form></div>";
I had post parameters instead of get parameters set for update.php form action
update.php?id=
echo"Error on update ID:{$_GET['id']} POSODOBLJENI CAS:{$_POST['posodobljeni_cas']}";

Fetching data in form of radio button format for quiz game in PHP

I have stored data in database statically. Its having 5 col One for question and 4 col. for answers. Basically its a quiz game format. Now I want to fetch data from database in the form of radio button for that 4 col. How to implement that method. Currently i am fetching in normal text mode.
Here is the code
<?php
// Create connection
$conn = new mysqli("localhost","root","","QuizQuestions");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully<br><br>";
$sql = "SELECT Question, Answer1, Answer2, Answer3, Answer4 FROM Questions";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br>Question: " . $row["Question"]. "<br>";
echo " A) " . $row["Answer1"]. "<br>";
echo " B) " . $row["Answer2"]. "<br>";
echo " C) " . $row["Answer3"]. "<br>";
echo " D) " . $row["Answer4"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
if i understood your question correctly.
and if your database field contain html code for radio button then u need to:
Use htmlspecialchars_decode
and stripslashes
Replace the following line..
echo " A) " . $row["Answer1"]."<br>";
With
echo htmlspecialchars_decode(stripslashes($row["Answer1"]));
else use simple php code to show front end
<input type='radio' name="ans" value="1" > <?php echo $row["Answer1"]; ?>
<input type='radio' name="ans" value="2" > <?php echo $row["Answer2"]; ?>
<input type='radio' name="ans" value="3" > <?php echo $row["Answer3"]; ?>
<input type='radio' name="ans" value="4" > <?php echo $row["Answer4"]; ?>
after that check value and validate ans on post
why you dont try select than radio? but here's what you're looking for if i'm not mistaken
<input type="radio" name="'.$row["Answer1"].'" value="'.$row["Answer1"].'" />
then just validate in your javascript if the radio button has a value make it checked.
If I understand your question correctly, you simply want to make the answers into radio buttons. You can achieve this by doing this:
while($row = $result->fetch_assoc()) {
echo "<br>Question: " . $row["Question"]. "<br>";
echo ' A) <input type="radio" value="'.$row["Answer1"].'">'.$row["Answer1"].'<br>';
echo ' B) <input type="radio" value="'.$row["Answer2"].'">'.$row["Answer2"].'<br>';
echo ' C) <input type="radio" value="'.$row["Answer3"].'">'.$row["Answer3"].'<br>';
echo ' D) <input type="radio" value="'.$row["Answer4"].'">'.$row["Answer4"].'<br>';
}

Data is not submitted to the database and a message "ERROR" shows

There are two php files one contains the form and the other contains the code to insert the form data to the table in a database.
This is the submit form code from the first file
<form name="form" action="insert_dataE.php" onSubmit="return
validation()" method="post" id="formServiceEntry">
<fieldset id="fieldSetServiceEntry">
<legend align="center">Please fill the form</legend>
<p class="FieldHeading"><i>Vehicle No(*): </i></p>
<input id="VehicleNoFieldArea" type="text" name="VehicleNoField"
size="6" maxlength="8"/>
<p class="FieldHeading"><i>Description(*):</i></p>
<textarea id="descriptionFieldArea" name="descriptionField"
rows="2" cols="20" size="15" maxlength="18"></textarea>
<p class="FieldHeading"><i>Total(*):</i></p>
<input id="totalFieldArea" name="totalField" type="text"
size="4" maxlength="4"/>
<p id="amountFieldHeading"><i>Bill(*):</i></p>
<input id="amountFieldArea" name="amountField" type="text"
size="3" maxlength="3" onKeyUp="balance();" />
<br/>
<div id="divisionRadioButton">
<h3 id="radioButtonHeading">Service(*):</h3>
Service
<input class="textFields" type="radio"
name="serviceSelection" value="service" checked />
<br/>
Wash
<input class="textFields" type="radio"
name="serviceSelection" value="wash" />
</div>
<p id="balanceFieldHeading"><i>Balance(*):</i></p>
<input id="balanceFieldArea" name="balanceField" type="text"
size="4" maxlength="4"/>
</fieldset>
<input class="btnsSE" type="submit" name="Button" value="Submit" />
<input class="btnsSE" type="reset" name="Button" value="Reset Form"/>
<input type="button" class="btnsSE" value="Back to the staff
interface" onClick="window.location='staffE.php';"/>
</form>
This is the insert data code from the second file
<?php
// Connects to your Database
$conn=mysql_connect("localhost", "webgeek1_service", "6defyu4642070") or
die(mysql_error());
mysql_select_db("webgeek1_software_order", $conn) or die(mysql_error());
$result = mysql_query("SELECT * FROM application", $conn);
$num_rows = mysql_num_rows($result);
$num_rows = $num_rows + 1;
$id= $num_rows;
$dateAndTime = date('y-m-d H:i:s',time());
$vehicleNo=mysql_real_escape_string($_POST['VehicleNoField']);
$description=mysql_real_escape_string($_POST['descriptionField']);
$amount=mysql_real_escape_string($_POST['amountField']);
$service=mysql_real_escape_string($_POST['serviceSelection']);
// Build an sql statment to add the query details
$sql="INSERT INTO `webgeek1_software_order`.`application`(`serialNo`,
`dateAndTime` , `vehicleNo` , `description` ,`amount`,`service`)
VALUES
('$id',
'$dateAndTime','$vehicleNo','$description','$amount','$service')";
$result = mysql_query($sql, $conn);
if($result)
{
echo "<p id='headingInsertData'>Service Station Web Application</p>";
echo "<p id='receiptHeading'>Receipt</p>";
echo "<div id='mainFieldsInsertData'>";
echo "Serial No: " . " " . $id;
echo "<br/>";
echo "Date and Time: " . " " . $dateAndTime;
echo "<br/>";
echo "Vehicle No: " . " " . $vehicleNo;
echo "<br/>";
echo "Description: " . " " . $description;
echo "<br/>";
echo "Amount: " . " " . $amount;
echo "<br/>";
echo "Service:" . " " . $service;
echo "<br/>";
echo "<br/>";
echo"Thanks for using our services";
echo "</div>";
echo "<div id='footerInsertData'>";
echo "<i>Developed by: Web Geeks - Information Technology (IT)
Company</i>";
echo "</div>";
echo "<div align='center'>";
echo "<input class='btns' type='button' value='Print'
onClick='javascript: window.print();'/>";
echo "<input type='button' class='btns' value='Back to the
Application' onClick='newDoc()'/>";
echo "</div>";
}
else
{
echo "ERROR";
}
// close connection
mysql_close($conn);
?>
The error you're having (Duplicate entry '51' for key 'PRIMARY') seems pretty logical since you're giving your specified ID to row instead of writing automatically. Moreover, you're using ID based off of the amount of rows there currently are. This leads to MySQL error with ID duplication.
To solve this issue:
Modify serialNo column and tick a checkbox on A_I column (AUTO_INCREMENT). This will make sure you will always have unique ID.
Remove entirely this part in your code:
$result = mysql_query("SELECT * FROM application", $conn);
$num_rows = mysql_num_rows($result);
$num_rows = $num_rows + 1;
$id= $num_rows;
Modify your query:
This is modified already
$sql="INSERT INTO `webgeek1_software_order`.`application` (`dateAndTime`, `vehicleNo`, `description`,`amount`, `service`) VALUES('$dateAndTime', '$vehicleNo', '$description', '$amount', '$service')";
I believe database should automatically set what next ID should come after inserting new data. This will prevent your from getting such errors as ID duplication because you're no longer inserting your own number.
A side note (but important): you should use mysqli or PDO statements because mysql extension is deprecated (and is even removed in PHP 7.0.0).
In the structure for my table in phpmyadmin, I needed to set the column 'serialNo' to AI (Autoincrement) and in the insert data code, I needed to comment the lines:
$num_rows = mysql_num_rows($result);
$num_rows = $num_rows + 1;
$id= $num_rows;
Similarly, I needed to remove the 'serialNo' from the insert query in the same file. At last I needed to comment the lines :
echo "Serial No: " . " " . $id;
echo "<br/>";
in the insert data code

Sort by using drop down and variable in MySQL statement (PHP)

I am trying to sort my results by using a drop down menu. I want to get a value from the drop down and enter it into a MySQL statement by assigning it to a variable. I have tried a few things with no success. Any ideas? Thank you.Before I could pull the data from the table and it displayed correctly. It's just the sorting issue.
<form name="order" method="post">
<select name='order'>
<option value='ORDER BY product_name ASC'>A-Z
<option value='ORDER BY product_name DSC'>Z-A
<input type="submit" value="Submit" />
</select>
</form>
<div id="Products">
<p>
Products:
</p><?php
$con=mysqli_connect("localhost","root","","db_tc");
// Check connection
$order=$_POST['order'];
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM tbl_products ORDER BY $order");
while($row = mysqli_fetch_array($result))
{
echo "<div id='item'>";
echo "<div id= 'pic'><img class='pic' src='". $row['product_img'] . "'/></div>";
echo "<div id= 'itemname'><h1> " . $row['product_name'] . "</h1></div>";
echo "<div id= 'price'> <h2>Price:</h2><br>£" . $row['product_price'] . "</div>";
echo "<div id= 'signed'> <h2>Signed:</h2><br>" . $row['product_signed'] . "</div>";
echo "<div id= 'type'> <h2>Type:</h2><br>" . $row['product_type'] . "</div>";
echo "</div>";
}
echo "</table>";
mysqli_close($con);
?>
</div>
well the value you are sending with the $_POST field is "ORDER BY name ASC" and you try to add it to a sql statement which already contains "ORDER BY" clause which might be the problem for you. And I guess it's "DESC" not "DSC"
Have you considered, what would have happened if someone added a single quote to the value of the select field and post that? You should always escape the values you receive from the user. Better if you use prepared statements too.

PHP deleting from database not working

I'm trying to let the user check off which item to be deleted. When the user check off one or many items and click the Delete button, those data will be erased from the database. I've also added a search box to search for the dvd. The search box works, but the deleting doesn't. This is what it looks like in the browser.
My PHP looks like this (I took out the searching code):
<form action="" method="post">
<p><input type="text" name="search"> <input type="submit" value="Search"></p>
<p><input type="submit" name="deleting" value="Delete"></p>
</form>
<?php
$link = mysqli_connect( $host, $user, $password, $dbname);
if (!$link) {
die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully<br/>';
//searching code goes here
if (isset ($_POST['deleting']) && isset ($_POST['deleteThese']) )
{
$deleteThese = implode(",", $_POST['deleteThese']);
$queryTwo = "DELETE FROM `$dbname`.`dvds` WHERE `dvds`.`DvdID` IN ($deleteThese)";
$resultTwo = mysqli_query($link, $queryTwo);
}
echo "<table border=\"1\"><tr><th>DvdTitle</th><th>RunningTime</th><th>Delete</th></tr>";
if (mysqli_num_rows($result) == 0)
echo "<tr><td colspan='2'>No records found.</td></tr>";
else {
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>" . $row['DvdTitle'] . "</td>";
echo "<td>" . $row['RunningTime'] . "</td>";
echo "<td>" . "<form>" . "<input type='checkbox' name='deleteThese[]' value='" . $row['DvdID'] . "' >" . "</form>" . "</td></tr>\n";
}
}
echo "</table>";
mysqli_free_result($result);
mysqli_close($link);
?>
Each DvdTitle has an unique Dvd ID, hence the value of each row is the dvd's ID $row['DvdID'].
Adding the parentheses will allow for those ID's to be selected for deletion.
IN($deleteThese)
EDIT
Do not close the form after the submit button. Put that at the end of the code. This will allow the form to include the checkbox values.
<form action="" method="post">
<p><input type="text" name="search"> <input type="submit" value="Search"></p>
<!-- YOUR PHP CODE -->
<p><input type="submit" name="deleting" value="Delete"></p>
</form>
2nd Edit [requested to improve code]
Move the isset on top of the form.
<?php
if (isset ($_POST['deleting']) && isset ($_POST['deleteThese']) )
{
$deleteThese = implode(",", $_POST['deleteThese']);
$queryTwo = "DELETE FROM `$dbname`.`dvds` WHERE `dvds`.`DvdID` IN ($deleteThese)";
$resultTwo = mysqli_query($link, $queryTwo);
}
?>
<form>....
$deletethese might need to have quotes around it.

Categories