How to set unique id on html form in while loop - php

How I can set unique id for html form which is in while loop, and get this id when check is the form is submit? You can check out my code:
while($row_lessons = mysqli_fetch_assoc($queryLessons)) {
echo 'someinfohere';
if(isset($_POST['buy'])) {
mysqli_query($link, "UPDATE users SET credits = credits - ".$row_lessons['price']." WHERE id = '".$_SESSION['userid']."' ");
mysqli_query($link, "INSERT INTO `lessonpurchases` (lesson_id, user_id, date) VALUES ('".$row_lessons['id']."', '".$_SESSION['userid']."', '".time()."')") or die(mysqli_error($link));
}
echo '
Цена: '.levche($row_lessons['price']).'лв. <br />
<form action="" method="post">
<input type="submit" name="buy" value="Купи" />
</form>';
}
The unique id is needed, because when submit the form the mysql queries are being executed for all results in loop.

If you want to keep it simple:
$i = 1;
while($row_lessons = mysqli_fetch_assoc($queryLessons)) {
echo 'someinfohere';
if(isset($_POST['buy'.$i])) {
mysqli_query($link, "UPDATE users SET credits = credits - ".$row_lessons['price']." WHERE id = '".$_SESSION['userid']."' ");
mysqli_query($link, "INSERT INTO `lessonpurchases` (lesson_id, user_id, date) VALUES ('".$row_lessons['id']."', '".$_SESSION['userid']."', '".time()."')") or die(mysqli_error($link));
}
echo '
Цена: '.levche($row_lessons['price']).'лв. <br />
<form action="" method="post">
<input type="submit" name="buy'.$i.'" value="Купи" />
</form>';
$i++;
}

You can use uniqid() as follow
$formId = uniqid();
In your form you can use it like
<form action="" method="post" id="<?php echo $formId;?>">
<input type="hidden" name="formId" value="<?php echo $formId;?>" />
<input type="submit" name="buy" value="Купи" />
</form>
On form submission you will get the formId by using $_REQUEST['formId']

Related

Submit data into table based on certain input field in HTML form

I am currently creating a survey where the answers are entered into a database.
I have 2 main tables:
questions, with 2 columns: questionID and questionBody
answers, with 3 columns: answerID, questionID (I want this to be tied to the column in table questions) and answerBody.
On the HTML page I am planning to create there will be multiple questions with multiple text boxes to fill in correlating to each quesiton. Is it possible that when the person submits the form, the answers are inserted into table answers with the questionID being based on what field was filled out?
So for example, If I have questionBody as "What is this Question asking?" and the questionID as 1 in table questions, when I submit the form I want table answers to also have questionID 1 in there.
At the moment this is my code:
//Check if error variables have any values assigned
if (empty($answerError))
{
//Prepare database insert
$sql = "INSERT INTO answers (questionID, answerBody) VALUES (?,?)";
//Check if the statement has the connect and sql variables
if ($statement = mysqli_prepare($connect, $sql))
{
//Add variables to the statement
mysqli_stmt_bind_param($statement, "ss", $paramQuestion, $paramAnswer);
//Set the parameter to the answer
$paramQuestion = getQuestionName($connect);
$paramAnswer = $answer;
//Execute statement with entered variable
if (mysqli_stmt_execute($statement))
{
//Redirect user to success page
header("location: thankyou.php");
}
else
{
echo "Something went wrong. Please try again later.";
}
//Close statement
mysqli_stmt_close($statement);
}
}
and for the function getQuestionName():
function getQuestionName($connect)
{
$query = "SELECT * FROM questions";
$result = mysqli_query($connect, $query);
if ($result)
{
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$questionID = $row['questionID'];
return $questionID;
}
}
}
The code I am using to output the form into a HTML page is:
function getQuestions($connect)
{
$query = "SELECT * FROM questions";
$result = mysqli_query($connect, $query);
if ($result)
{
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$body = $row['questionBody'];
echo '<div class="entry">
<div class="questionTitle"><h3>' . $body . '</h3>
<form action="survey.php" method="POST">
<input type="text" name="answer" size="50" />
<input type="submit" value="Submit" name="submit" />
</form>
</div>
</div>';
}
}
Any help on this would be greatly appreciated :)
Yes it's completely possible. Just put the question ID as a hidden field in the form, and it will be submitted along with the answer data when the form is submitted. Then you can retrieve it from the $_POST data just like the answer, and use it in your SQL query.
For example:
HTML form:
<form action="survey.php" method="POST">
<input type="hidden" name="questionID" value="<?php echo $row["questionID"]; ?>" />
<input type="text" name="answer" size="50" />
<input type="submit" value="Submit" name="submit" />
</form>
survey.php:
$paramQuestion = $_POST["questionID"];
From your question, I will suggest you make use of input with a hidden attribute.
something like this
<input type='text' name='question-id' value="<?php echo $questionId ;?>" hidden>
The user doesn't see the input it get filled from whatever you are providing into it.
Editing your code, you should do something like this.
function getQuestions($connect)
{
$query = "SELECT * FROM questions";
$result = mysqli_query($connect, $query);
if ($result)
{
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$body = $row['questionBody'];
$questionId = $row['questionId'];
echo '<div class="entry">
<div class="questionTitle"><h3>' . $body . '</h3>
<form action="survey.php" method="POST">
<input type="text" name="answer" size="50" />
<input type="number"name="question-id" value="'.$questionId.'" hidden>
<input type="submit" value="Submit" name="submit" />
</form>
</div>
</div>';
}
}

Inserting an array of checkbox values into a database including unchecked

In the form below, students are selected from student table in my DB. For each student selected a checkbox is checked if the student is absent and left unchecked if the student is present. The form is later on submitted for it to be inserted in the exam_status table in my DB.
<form method="POST" action="action.php">
<?php
$query = "SELECT * from student ORDER BY student_name,student_surname";
$result=mysqli_query($conn,$query);
if(false===$result)
{
printf("error: %s \n",mysqli_error($conn));
}
while($row= $result->fetch_assoc())
{
$studentmatricule = $row['student_matricule'];
$studentname = $row['student_name'];
$studentsurname = $row['student_surname'];
?>
<div id="studentdiv">
<label>Matricule</label>
<input type="text" name="matricule[]" value="<?php echo "$studentmatricule)"; ?>" readonly>
<label>Name</label>
<input type="text" name="name[]" value="<?php echo "{$studentname} {$studentsurname}"; ?>" readonly>
<label > Absent
<input type="checkbox" name="absent[]" value="absent" />
</label>
</div> <br><br>
<?php
}
?>
<input type="submit" name="submit" value="submit">
</form>
and my action page "action.php" is as follows
$matricule = $_POST['matricule'];
$absent=$_POST['absent'];
for ($i=0; $i<sizeof($matricule); $i++)
{
if($absent[$i]=='absent')
{
$status='absent';
}else{
$status='present';
}
$query = "INSERT INTO exam_status (student_matricule,status) VALUES ('". $matricule[$i] . "','". $status . "')";
$result=mysqli_query($conn,$query);
}
Now the issue is it doesn't just work as i want. the result always gives the first student absent and the rest present. I have tried all i can and have really researched too but with no success at all. Please anyone around to help me out?
Thanks in advance!
<form method="POST" action="action.php">
<?php
$query = "SELECT * from student ORDER BY student_name,student_surname";
$result=mysqli_query($conn,$query);
if(false===$result)
{
printf("error: %s \n",mysqli_error($conn));
}
$index = 0;
while($row= $result->fetch_assoc())
{
$index++;
$studentmatricule = $row['student_matricule'];
$studentname = $row['student_name'];
$studentsurname = $row['student_surname'];
?>
<div id="studentdiv">
<label>Matricule</label>
<input type="text" name="studenInfo[<?php echo $index; ?>][matriculate]" value="<?php echo $studentmatricule; ?>" readonly>
<label>Name</label>
<input type="text" name="studenInfo[<?php echo $index; ?>][name]" value="<?php echo $studentname." ".$studentsurname; ?>" readonly>
<label > Absent
<input type="checkbox" name="studenInfo[<?php echo $index; ?>][status]" value="absent" />
</label>
</div> <br><br>
<?php
}
?>
<input type="submit" name="submit" value="submit">
Update your mail file like this. I have changed the form names into a single array. The reason is the checkbox values won't post to the page when the values are not checked. So its not possible to track which one was checked and which is not if you have same name.
And update your action.php like this,
<?php
$conn = mysqli_connect("localhost","username","password","db_name"); // update this values as per your configuration
$studenInfo = (!empty($_POST['studenInfo'])) ? $_POST['studenInfo'] : [];
foreach($studenInfo as $value ) {
$status = (isset($value['status'])) ? 'absent' : 'present';
$query = "INSERT INTO exam_status (student_name, student_matricule,status) VALUES ('". $value['name'] . "','". $value['matriculate'] . "','". $status . "')";
$result=mysqli_query($conn,$query);
}
?>
I have used my own table schema where i have added student_name in exam_status table for better tracking. Now you can see the values updating correctly. Also we can use bulk insert if we need to insert multiple data (Note : I haved used the bulk insert in this answer, i just followed the way you used)

Increment id on click in MySQL

I have a problem to visualize the solution for the problem that I have now.
The user is allowed to insert a row in a table.
And I try to display a button (input) +1 who allow the user to increment a column (vote) in a selected row among all created.
The problem is that I don't get the thing for rely incrementation to the desired id.
Here my code :
<form action="" method="post">
<input type="text" name="disease">name
<input name="mainsubmit" type="submit" value="submit">
</form>
</body>
</html>
<?php
if(isset($_POST['mainsubmit']))
{
$nameDisease = $_POST['disease'];
$req = $db->prepare('INSERT into disease(name) VALUES(:name)');
$req->execute(array('name' => $nameDisease));
}
$query = $db->query('SELECT * FROM disease');
while ($result = $query->fetch())
{
$id = $result['id'];
echo $id ?>
<form action="" method="post"> <input name="secondsubmit" type="submit" value="+1"> </form><?php
if(isset($_POST['secondsubmit']))
{
$db->exec("UPDATE disease SET vote = vote + 1 WHERE id = " .$id);
}
}
Logically, the code above doesn't work but I don't understand how find the solution.
In brief, i want to allow the user to increment a column in a selected row.
Thanks
Edit: Shadow, it's not my problem because your solution is used for automatically chose between INSERT or UPDATE if the line doesn't exist or exist. Me, I want allow the user to create rows and allow he to vote +1 on each of one that exist, and it will not be possible for he to insert a row from the input +1.
I created code snippet similar to your code style.
You have two submit buttons so you need to separate handling of those two requests.
The $id of the item you want to update in the second submit need's to come from hidden value in form.
In order for this to work you need to create table in mysql:
create table disease (id MEDIUMINT NOT NULL AUTO_INCREMENT, name VARCHAR(20), vote INTEGER, PRIMARY KEY (id)); - for example like this
<html>
<body>
<form action="" method="post">
<input type="text" name="disease">name
<input name="mainsubmit" type="submit" value="submit">
</form>
</body>
</html>
<?php
$db = new PDO('mysql:dbname=phpapp;host=db', 'root', 'phpapptest');
if (isset($_POST['mainsubmit'])) {
$nameDisease = $_POST['disease'];
$req = $db->prepare('INSERT into disease (name, vote) VALUES(:name, 0)');
$req->bindParam(':name', $nameDisease);
$req->execute();
$query = $db->query('SELECT * FROM disease');
while ($result = $query->fetch()) { ?>
<form action="" method="post">
<p><?php echo $result['name'] . " : " . $result['vote'];?>
<input name="secondsubmit" type="submit" value="+1" />
<input type="hidden" name="id" value="<?php echo $result['id'];?>" />
</p>
</form>
<?php }
}
if (isset($_POST['secondsubmit'])) {
$req = $db->prepare("UPDATE disease SET vote = vote + 1 WHERE id = " . $_POST['id']);
$req->execute();
$query = $db->query('SELECT * FROM disease');
while ($result = $query->fetch()) {?>
<form action="" method="post">
<p><?php echo $result['name'] . " : " . $result['vote'];?>
<input name="secondsubmit" type="submit" value="+1" />
<input type="hidden" name="id" value="<?php echo $result['id'];?>" />
</p>
</form>
<?php }
}
?>

PHP - Can't update information from table

I can't change the information from my database.
I'm trying to update information from my database. But it's not working.
The user just need to put one existing ID from the table, and it will update the information from the specific column, in this case, it's a column called "titulo".
Here my page code:
<?php
if(isset ($_POST['submit']))
{
include("../classes/administrador/Administrador.class.php");
$Administrador = new Administrador();
if ($Administrador->atualizarCD($_REQUEST['id'],$_REQUEST['titulo']))
{
echo "It works !!!<br>";
} else {
echo "its not working<br>";
}
$Administrador->endAdministrador();
}
else{
?>
<b>Alterar CD</b><br><br>
<form name="form3" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<b>ID</b>:
<input type="text" name="id" size="3">
<br>
<br>
<b>Titulo</b>:
<input type="text" name="titulo">
<br>
<input type="submit" name="submit" value="submit">
</form>
<p> </p>
<?php
}
?>
And my function code:
function atualizarCD($id, $titulo) {
$sql= "UPDATE `cds` SET `titulo` = '$titulo' WHERE `ID` = '$id";
if($this->bd->executarSQL($sql)) return true;
else return false;
}
You have missed to add ' end of the query
$sql= "UPDATE `cds` SET `titulo` = '$titulo' WHERE `ID` = '$id' ";

If content exists in database, provide form to update it - else provide form to add new row

It's all going wrong. I need to output a form onto my website that will do 1 of 2 things:
If the user already has content in the database, provide a form that posts to self to update the existing content.
If the user does not have content in the database, provide a form to let the user add information to the database.
The forms should submit to themselves to keep coding tidy. I'm getting into a right mess. I'll show what I have so far, but I'm getting in a muddle.
//look in db to see if content exists, if it does set variable
$result = mysql_query(
"SELECT * from tbl_profiles
WHERE user_id = $who
");
while($row = mysql_fetch_array($result))
{
$profileText = $row['text'];
}
// Check if user has content in db
$result = mysql_query(
"SELECT * FROM tbl_profiles WHERE user_id='$who'");
if(mysql_fetch_array($result) !== false){
echo
'<form action="../edit/indexUpdate.php" method="post" name="edit">
Comments:<br />
<textarea name="updatedText" id="comments">' .
$profileText .'
</textarea><br />
<input type="submit" value="Submit" />
</form>'
;}
else{
$profileText = $row['text'];
echo
"<form action='../edit/index.php' method='post' name='add'>
Comments:<br />
<textarea name='comments' id='comments'>" .
$profileText
."</textarea><br />
<input type='submit' value='Submit' />
</form>"
;}?>
You've pretty much got the functionality there, just needs tidying up.
Try something like this:
<?php
//look in db to see if content exists, if it does set variable
$profileText="";
if($result = mysql_query("SELECT * from tbl_profiles WHERE user_id = $who")) {
while($row = mysql_fetch_array($result))
{
$profileText .= $row['text'];
}
?>
<form action="../edit/indexUpdate.php" method="post" name="edit">
Comments:<br />
<textarea name="updatedText" id="comments">
<?php echo $profileText; ?>
</textarea><br />
<input type="submit" value="Submit" />
</form>
<?php
} else {
?>
<form action='../edit/index.php' method='post' name='add'>
Comments:<br />
<textarea name='comments' id='comments'>
<?php echo $profileText; ?>
</textarea><br />
<input type='submit' value='Submit' />
</form>
<?php
}
?>
The basic idea is to add a record if new and update if not. What you can do is use an id to represent the record or -1 if it's a new entry
Something along the lines of:
//Defaults
$recordid=-1;
$name='';
$comments='';
//look in db to see if content exists, if it does set variable
$result = mysql_query(
"SELECT * from tbl_profiles
WHERE user_id = $who
");
// Check if user has content in db
$result = mysql_query(
"SELECT * FROM tbl_profiles WHERE user_id='$who'");
if(mysql_fetch_array($result) !== false){
//Yes. Get the id
$recordid = $result->id;
//Get the values
$name= $result->name;
$comments= $result->name;
}
<form action="../edit/index.php" method="post" name="formdata">
<input type="hidden" name="recordid" value="<? echo htmlspecialchars($recordid) ?>">
<input type="hidden" name="name" value="<? echo htmlspecialchars($name) ?>">
<textarea name="comments" id="comments"><? echo htmlspecialchars($comments) ?></textarea>
<input type="submit" value="submit"/>
</form>
This way a new form will have a -1 but an existing will have an id.
As an additional point it is very important to sanitize your inputs for SQL and what you output in HTML to stop SQL Injections. For your reference on this:
SQL
Little Bobby Tables
Cross Site Scripting

Categories