Passing variable values into another if condition - php

Here is my code and i need to insert array values in $testar in to the table patients_testings. But it doesn't work with this code, where is the error? if i can do this using one global variable. it will be more helpful. thank you.
<form role="form" method="post" action="" name="testing" onsubmit="return validate_form()">
<?php
$sqltestin = "SELECT * FROM testings";
$querytestin = mysqli_query($dbhandle, $sqltestin);
while ($rowtestin = mysqli_fetch_assoc($querytestin)) {
echo '<input type="checkbox" name="testingar[]" value="' . $rowtestin['TestId'] . '">' . $rowtestin['TestName'] . '<br>';
}
?>
<div class="modal-footer">
<input type="submit" name="submittestin" id="submittestin" class="btn btn-success" value="Add Tests">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div></div>
<?php
$checkBox = '';
$testar = '';
if (isset($_POST['submittestin'])) {
global $checkBox;
global $testar;
$checkBox = $_POST['testingar'];
foreach ($checkBox as $testar1) {
$testar .= $testar1 . ",";
}
$tot = 0.00;
for ($i = 0; $i < sizeof($checkBox); $i++) {
$queryt2 = "SELECT * FROM testings WHERE TestId = $checkBox[$i] ";
$resultt2 = mysqli_query($dbhandle, $queryt2) or die (mysql_error());
while ($rowt2 = mysqli_fetch_assoc($resultt2)) {
echo "<tr><td>" . $rowt2['TestName'] . "</td>";
echo "<td width='100'>" . $rowt2['specimen'] . "</td>";
echo "<td>" . $rowt2['HopePrice'] . "</td></tr>";
//echo '<br/>';
$tot = $tot + $rowt2['HopePrice'];
}
}
echo "<tr><td><b>Total</b></td><td <b>:</b></td><td><b>" . number_format($tot, 2) . "</b></td></tr>";
echo "<tr><td><form role='form' method='post' action=''><input type='submit' name='printinv' id='printinv' class='btn btn-success' value='Print'></form></td></tr>";
//echo $testar;
if (isset($_POST['printinv'])) {
$sqltnum = "INSERT INTO patients_testings VALUES ('$ref_no','$testar')";
if (mysqli_query($dbhandle, $sqltnum) or die (mysql_error())) {
echo "Entered Successfully";
//}
}
}
}
?>

Why your code does not work:
I think the concept that you are missing is that when the page is requested, and on every subsequent form submission, the PHP code is executed then exits which throws out the values of the variables stored in memory. Making the variables global does not make them persist between requests.
Specifics to your code:
The first time the form is submitted isset($_POST['submittestin']) is true and it successfully populates the $testar variable with data. However, on the second post isset($_POST['submittestin']) is false and so you never hit the if (isset($_POST['printinv'])) section. Now, even if you move the if (isset($_POST['printinv'])) outside the first if ... submittestin you still have a problem because the $testar will no longer be populated with data.
Additionally, you use variables which are never initialized anywhere that I can see. $ref_no is an example.
I would also suggest echoing out your DB queries to see if they are properly formatted before you run them. I think that some of them may be missing 's in places.
How to make data persist between requests?
The best way is to start a session. By starting a session you can save variables in the $_SESSION array and then access them durring a different request.
Note: You cannot serialize resorces so you will need to reconnect to the database on each request. I.e., this won't work: $_SESSION['dbhandle'] = $dbhande;
Another way to set <input type=hidden ... elements in your form so that on the second post you can access them again through the $_POST variable.
Attempt to make your code use sessions:
<?php
session_start();
?>
<form role="form" method="post" action="" name="testing" onsubmit="return validate_form()">
<?php
$sqltestin = "SELECT * FROM testings";
$querytestin = mysqli_query($dbhandle, $sqltestin);
while ($rowtestin = mysqli_fetch_assoc($querytestin)) {
echo '<input type="checkbox" name="testingar[]" value="' . $rowtestin['TestId'] . '">' . $rowtestin['TestName'] . '<br>';
}
?>
<div class="modal-footer">
<input type="submit" name="submittestin" id="submittestin" class="btn btn-success" value="Add Tests">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div></div>
<?php
$checkBox = '';
$testar = '';
if (isset($_POST['submittestin'])) {
global $checkBox;
global $testar;
$checkBox = $_POST['testingar'];
foreach ($checkBox as $testar1) {
$testar .= $testar1 . ",";
}
$_SESSION['testar'] = $testar;
$_SESSION['ref_no'] = "This gets used below but I don't see it initialized anywhere?";
$tot = 0.00;
for ($i = 0; $i < sizeof($checkBox); $i++) {
$queryt2 = "SELECT * FROM testings WHERE TestId = '".$checkBox[$i]."'"; // syntax issue here
$resultt2 = mysqli_query($dbhandle, $queryt2) or die (mysql_error());
while ($rowt2 = mysqli_fetch_assoc($resultt2)) {
echo "<tr><td>" . $rowt2['TestName'] . "</td>";
echo "<td width='100'>" . $rowt2['specimen'] . "</td>";
echo "<td>" . $rowt2['HopePrice'] . "</td></tr>";
//echo '<br/>';
$tot = $tot + $rowt2['HopePrice'];
}
}
echo "<tr><td><b>Total</b></td><td <b>:</b></td><td><b>" . number_format($tot, 2) . "</b></td></tr>";
echo "<tr><td><form role='form' method='post' action=''>";
echo "<input type='submit' name='printinv' id='printinv' class='btn btn-success' value='Print'>";
echo "</form></td></tr>";
}
//echo $testar;
if (isset($_POST['printinv'])) {
if(isset($_SESSION['testar']) {
$testar = $_SESSION['testar'];
$ref_no = $_SESSION['refno'];
$sqltnum = "INSERT INTO patients_testings VALUES ('$ref_no', '$testar')"; // Where is $ref_no set?
if (mysqli_query($dbhandle, $sqltnum) or die (mysql_error())) {
echo "Entered Successfully";
}
}
}
?>

Related

how to add foreach array in text input

I have a form in which I enter the name, surname and function (result one select), I display them with a foreach in a table.
I want to add a button to every foreach record that will load the first form with the data from the row but I can not.
Thanks for the help!
<?php
require_once 'functii/functii.php';
$r = functia();
$options = "";
while ($row = mysqli_fetch_array($r)) {
$options = $options . "<option>$row[0]</option>";
}
?>
<form method="POST">
<table id="add"><tr><td>Nume:</td><td><input type="text" name="nume"/></td></tr>
<tr><td>Prenume:</td><td><input type="text" name="prenume"/></td></tr>
<tr><td>Functia:</td><td><select name="functia"><?php echo $options; ?></select></td></tr>
<tr><td>Activ:</td><td><input type="radio" name="activ"/></td></tr>
<tr><td></td><td><input type="submit" name="adaugare" value="Adauga"/><input type="submit" name="modificare" value="Modifica"/></td></tr></table>
</form>
<?php
if (isset($_POST['adaugare'])) {
require_once 'functii/functii.php';
$n = $_POST['nume'];
$p = $_POST['prenume'];
$f = $_POST['functia'];
$r = adaug_utilizator($n, $p, $f);
}
require_once 'functii/functii.php';
$utilizatori = grid_utilizatori();
if (count($utilizatori) == 0) {
print 'Nu sunt utilizatori adaugati';
} else {
?>
<table id="view">
<thead><tr><th colspan="4">Utilizatori adaugati</th></tr>
<tr><th>Nume</th><th>Prenume</th><th>Functia</th></tr>
</thead>
<tbody>
<?php
foreach ($utilizatori as $utilizator) {
print "<tr>";
print "<td>" . $utilizator['nume'] . "</td>";
print "<td>" . $utilizator['prenume'] . "</td>";
print "<td>" . $utilizator['denumire'] . "</td>";
print "<td><input type='submit' name='modifica' value='Modifica'></td>";
print "</tr>";
}
if (isset($_POST['modifica'])) {
$_POST['nume'] = $utilizator['nume'];
$_POST['prenume'] = $utilizator['prenume'];
$_POST['functia'] = $utilizator['denumire'];
}
?>
</tbody>
</table>
<?php
}
?>
You can execute loop as follows:
<?php
foreach($utilizatori as $index => $utilizator){
?>
<input type='submit' name='modifica<?php echo ($index+1);?>' value='Modifica' class="clickBtn"></td>
<?php
}
?>
with above loop name attribute will be as modifica1, modifica2 etc.
Now, you want to fill information based on button clicked to the form shown at your top of code, I think so.
For this, you can use jQuery:
$('.clickBtn').click(function(e){
var buttonOfRowClicked = $(this).attr('name');
var rowNumber = buttonOfRowClicked.substr(8); // It will get 1,2,3 etc table row.
$('input[name=nume]').val($(tr:nth-child(rowNumber) td:nth-child(1).val());
$('input[name=prenume]').val($(tr:nth-child(rowNumber) td:nth-child(2).val()); //similarly fill other variables.
});
I have not check the code by executing. It is overview for you to run your code. I think idea is sufficient for you for direction how should your code works.

send table row to next page

Im trying to make a simpel webshop where I list some items (to order) on each row there is a form field for tell how many the costumer wants of the item. Then she submit a button and the action is another page where the item will be added to an MYSQL table to be processed later Im thinkking that when user hit the submit there is a hidden field that send the itemid.
I need to get a way to make the itemid with me to the other side but I cant make the variable specific for the row. the ArtikelNR variable $row["ArtikelNr"] shoudld be assigned to the hidden form and be accessable on next page as ArtikelNr = $_REQUEST['ArtikelNr']; and it works so far but it always the laast item number not the itemnumber that i specific for the choosen row. How do I make $form4 = ' '; row speciific so i can catch it on next page and add it to the basket.
<?php include 'databas_connect.inc'; ?>
<?php
$sql = "SELECT `ArtikelNr`, `ArtikelNamn`, `Storlek`, `ArtikelPris`,
`artikelbild`FROM `artiklar` ";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
echo "<table><tr><th>Antal</th><th>ArtikelNr</th><th> ArtikelNamn</th>
<th>Storlek</th><th>ArtikelPris</th><th>Artikelbild</th></tr>";
// output data of each row
while($row = $result->fetch_assoc())
{
$number =1;
$artnr = $row["ArtikelNr"];
$prefix = "pre_";
$sufix = 1;
${$prefix .$sufix} =$row["ArtikelNr"] ;
$form1 = '<form action="sida61.php" method="post">';
$form2 = '<label for="antal"></label>';
$form3 = '<input type="text" name="antal" size="2" maxlength="2"value="1" id="antal">';
$form4 = '<input type="hidden" name="ArtikelNr" value="'.${$prefix .$sufix}.'"/> ';
$form5 = '<input type="submit" name="btn_submit" value="KÖP" />';
$form6 = '</form>';
$form = $form1 . $form2 . $form3 . $form4 . $form5 ;
$img = "<img src=./img/>";
$image=$row['artikelbild'];
$path ="<img src='./img/".$image."' />";
echo "<tr><td>" .$form. "</td><td>" . $row["ArtikelNr"]. "</td><td>" .
$row["ArtikelNamn"]. " </td><td> " . $row["Storlek"]. " </td><td>" .
$row["ArtikelPris"]. " </td><td>".$path."</td></tr>";
++$sufix;
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
here is code for sida61.php
<?php include 'databas_connect.inc'; ?>
<?php
session_start();
$ArtikelNr = $_REQUEST['ArtikelNr'];
$antal = $_REQUEST['antal'];
//$KundNr = $_SESSION["Kund"];
// attempt insert query execution
$sql = "INSERT INTO `kundkorg`( `ArtikelNr`, `antal`, `KundNr`)
VALUES (1,$antal, 2)";
if(mysqli_query($conn, $sql)){
print_r($_REQUEST); // I just do this to se value of $_REQUEST it is always 8 since I have 8 items i dont know why
}
else
{
echo "ERROR: Could not able to execute $sql. " .
mysqli_error($conn);
}
// close connection
mysqli_close($conn);
//header("Location: 6.php");
?>
Not sure why you were attempting to add a prefix and a suffix as you say you want to pass just the $row["ArtikelNr"] in your hidden field.
You also missed concatenating your </form> closing tag into your $form variable.
So this code should achieve what you want.
while($row = $result->fetch_assoc()) {
$form .= '<form action="sida61.php" method="post">';
$form .= '<label for="antal"></label>';
$form .= '<input type="text" name="antal" size="2" maxlength="2"value="1" id="antal">';
$form .= "<input type='hidden' name='ArtikelNr' value='{$row['ArtikelNr']}'/>";
$form .= '<input type="submit" name="btn_submit" value="KÖP" />';
$form .= '</form>';
$img = "<img src='./img/{$row['artikelbild']}'/>";
echo "<tr><td>$form</td><td>{$row['ArtikelNr']}</td><td>
{$row['ArtikelNamn']}</td><td>{$row['Storlek']}</td><td>
{$row['ArtikelPris']</td><td>$path</td></tr>";
}
Yes I se now I missed to missed concatenating your closing tag into $form variable. the correct code is
$form1 = '<form action="sida61.php" method="post">';
$form2 = '<label for="antal"></label>';
$form3 = '<input type="text" name="antal" size="2" maxlength="2"value="1"
id="antal">';
$form4 = '<input type="hidden" name="ArtikelNr" value="'.
$row["ArtikelNr"].'"/> ';
$form5 = '<input type="submit" name="btn_submit" value="KÖP" />';
$form6 = '</form>';
$form = $form1 . $form2 . $form3 . $form4 . $form5 . $form6 ;
Thanks so much #RiggsFolly
When I tried your code it added a new form on each row making me have 9 input fields on row 9. but You helped me anyway!!

updating data from mysql in html table

Here is my code. There's is a "Edit" link. I want to update data and save with that link
$op_sql = "SELECT * FROM tbl_users";
$result = $con->query($op_sql);
if ($result->rowCount() > 0)
{
echo "<table class='table' style='margin-left: 301px; margin-top: 10px; background-color: white;'>-;
echo "<tr>";
echo "<th>ID</th>";
echo "<th>Name</th>";
echo "<th>Email</th>";
echo "<th>Date of Birth<th>";
echo "<th></th>"; echo "</tr>";
while($row = $result->fetch())
{
echo "<tr>";
echo "<td>" . $rowrID1 . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['Email']. "</td>";
echo "<td>" . $row['Date of Birth'] . "</td>";
echo "<td><a href='?id=".$row['ID']."'>Edit</a></td>";
echo "</tr>";
}
echo "</table>"; unset($result);
You can add the user_edit.php url in anchor tag href to edit the user details like this.
echo "<td><a href='user_edit.php?id=".$row['ID']."'>Edit</a></td>";
user_edit.php
Here you can get the id of specific user and get the details from database and create update form like this.
if(isset($_GET['id']) && $_GET['id']!='')
{
$op_sql = "SELECT * FROM tbl_users where id=$_GET['id']";
$result = $con->query($op_sql);
if ($result->rowCount() > 0)
{
$row = $result->fetch();
?>
<form action="user_update.php" method="post">
<input type="text" name="Name" value="<?php $row['Name'] ?>" />
.
.
<input type="hidden" name="id" value="$_GET['id']" />
.
.
<input type="submit" name="update" value="update" />
<?php
}
}
user_update.php
Here you can get the updated form data and update in database
if(isset($_POST['update']) && isset($_POST['id']) && $_POST['id']!='' )
{
// here you can get the updated form data and update in database
// update user set Name=$_POST['Name'],.... where id=$_POST['id'];
}
NOTE :
Try to use Prepared statement or PDO
I am giving an answer from This question you can use the same answer in your context here I'm providing the code from the accepted answer.
You can use a get method here in place of the post according to your situation.
HTML form:
<form method="post" action="handler.php">
<button type="submit" name="passed" id="passed" class="btn btn-success btn-flat"><i class="fa fa-check"></i></button>
<button type="submit" name="insufficient" id="insufficient" class="btn btn-danger btn-flat"><i class="fa fa-times"></i></button>
</form>
PHP:
<?php
// db connection
if(isset($_POST['passed'])){
$allowed = mysqli_query($conn," UPDATE users SET Access = "1" WHERE id = '27' ");
}
if(isset($_POST['insufficient'])){
$notallowed = mysqli_query($conn," UPDATE users SET Access = "0" WHERE id = '453' ");
}
Be careful if this has any user interaction at any given point.
Use a prepared statement, or PDO with prepared statements, they're much safer.

Adding css to a form

I am trying to add CSS to my form but not sure how to do this. The form is created in php and MySQL, in browser it looks like: http://gyazo.com/5d099ead9bd6ea83859a5114b2438748
I need to allign the text and drop downs so they are in the equal throughout and add some spacing. Anyone help with CSS for this?
html currently:
<div class="wrap">
<img src="/images/logo.png" alt="Highdown logo" />
<h1>Entry form</h1>
</div>
css currently:
.wrap {
position: relative;
}
The form is produced with this:
if ($event_result = $con->query("SELECT Event.Name FROM event")) {
echo "<form method =\"POST\" action=\"save.php\"> ";
while ($row = $event_result->fetch_assoc()) {
echo $row['Name']. ' ';
if ($student_result = $con->query("SELECT Student.Form, Teacher.Form, Student.Forename, Student.Surname, Student_ID " .
"FROM Student, Teacher " .
"WHERE Student.Form = Teacher.Form AND Teacher.Username = '" . $_SESSION['Username'] . "'")) {
if ($student_result->num_rows) {
echo "<select name ='". $row['Name']."'>";
while ($row1 = $student_result->fetch_assoc()) {
echo '<option value="" style="display:none;"></option>';
echo "<option value ='" . $row1['Student_ID'] . "'>" . $row1['Forename'] . ' ' . $row1['Surname'] . "</option>";
}
echo "</select> <br />";
}
}
}
echo '<input type="submit" value ="Submit">';
echo '<input type="reset" value ="Reset">';
echo '<input type="button" value = "Add student" onclick="location.href=\'http://localhost/sportsday/addstudent.php\'">';
echo '<input type="button" value = "Delete student">';
echo "</form>";
}
Use
<form>
<table>
<tr> //1st Table row
<td></td> //Table column data
<td></td> //table column data
</tr> //1st row ends
<tr> // 2nd Table row
<td></td> //Table column data
<td></td> //table column data
</tr> //2nd row ends
</table>
</form>
This will give you a better layout of the form.
This should work i did not try as i dont have the database
//Query to display all events
if ($event_result = $con->query("SELECT Event.Name FROM event")) {
echo "<form method =\"POST\" action=\"save.php\"> ";
echo '<table>';
echo '<tr>';
echo '<td>';
while ($row = $event_result->fetch_assoc()) {
echo $row['Name']. ' ';
echo '</td>';
if ($student_result = $con->query("SELECT Student.Form, Teacher.Form, Student.Forename, Student.Surname, Student_ID " .
"FROM Student, Teacher " .
"WHERE Student.Form = Teacher.Form AND Teacher.Username = '" . $_SESSION['Username'] . "'")) {
if ($student_result->num_rows) {
echo '<td>';
echo "<select name ='". $row['Name']."'>";
while ($row1 = $student_result->fetch_assoc()) {
echo "<option value ='" . $row1['Student_ID'] . "'>" . $row1['Forename'] . ' ' . $row1['Surname'] . "</option>";
}
echo "</select> <br />";
echo '</td>';
echo '</tr>';
}
}
}
echo '</table>';
echo '<input type="submit" value ="Submit">';
echo '<input type="reset" value ="Reset">';
echo '<input type="button" value = "Add student" onclick="location.href=\'http://localhost/sportsday/addstudent.php\'">';
echo '<input type="button" value = "Delete student">';
echo "</form>";
}
?>
you can directly write in css
form {
⋮ declare css
}
or give name to form
form[name="value"]{
⋮ declare css
}
or add any class or id on form
#formid{
⋮ declare css
}
.formclass{
⋮ declare css
}
First , check your database...
May be there is Another Issue not related to Tabular Output.
So , First remove Table Tag..and check whether its working ?
Then try in HTML TABLE TAG
Otherwise give me sample database .sql File and complete PHP code in google drive or on shared drive.
So that I can check and identify where is problem ?

jquery .append() not working for my html

I have a program which appends an input(type="hidden") using jquery, to an html so that when I click the submit button, it passes the value to a php file and I can process it. However, it seems that the hidden type is not really being appended to the html nor it is being passed to the php file. I already used method="get" to see the values in the address bar and print_r to see the values being catched but there's nothing. To check if my form is actually passing a value, I added a
<input type="hidden" name="absent[]" value="testing" />
in the HTML and the value got passed but the ones in the jquery aren't.
Here are my files:
jquery:
$(function(){
$("td").click(function(){
if($(this).hasClass("on"))
{
alert("Already marked absent");
}
else
{
$(this).addClass("on");
var currentCellText = $(this).text();
var temp = $(this).attr('id');
$("#collect").append("<input type='hidden' name='absent[]' value = '" + temp + "'/>" + currentCellText);
alert(temp);
}
});
$("#clicky").click(function(){
$("td").removeClass("on");
$("#collect").text('');
$("#collect").append("Absentees: <br>")
alert(temp);
});
});
Here is the html part:
<?php
session_start();
include 'connectdb.php';
$classID = $_SESSION['csID'];
$classQry = "SELECT e.csID, c.subjCode, c.section, b.subj_name, e.studentID, CONCAT(s.lname, ', ' , s.fname)name
FROM ENROLLMENT e, CLASS_SCHEDULE c, STUDENT s, SUBJECT b
WHERE e.csID = c.csID
AND c.csID = '" . $classID . "'
AND c.subjCode = b.subjCode
AND e.studentID = s.studentID
ORDER BY e.sort;";
$doClassQry = mysql_query($classQry);
echo "<table id='tableone'>";
while($x = mysql_fetch_array($doClassQry))
{
$subject = $x['subj_name'];
$subjCode = $x['subjCode'];
$section = $x['section'];
$studentArr[] = $x['name'];
$studentID[] = $x['studentID'];
}
echo "<thead>";
echo "<tr><th colspan = 7>" . "This is your class: " . $subjCode . " " . $section . " : " . $subject . "</th></tr>";
echo "</thead>";
echo "<tbody>";
echo "<tr>";
for($i = 0; $i < mysql_num_rows($doClassQry); $i++)
{
if($i % 7 == 0)
{
echo "</tr><tr><td id = '". $studentID[$i] . " '>" . $studentArr[$i] . "</td>";
}
else
{
echo "<td id = '". $studentID[$i] . " '>" . $studentArr[$i] . "</td>";
}
}
echo "</tr>";
echo "</tbody>";
echo "</table>";
?>
Here's the html part with the form:
<form name="save" action="saveTest.php" method="post">
<div id="submitt">
<input type="hidden" name="absent[]" value="testing"/>
<input type="submit" value="submit"/>
</div>
</form>
And here's the php part which processes the form (saveTest.php):
<?php
$absent = $_POST['absent'];
//echo "absnt" . $absent[] . "<br>";
echo count($absent) . "<br>";
//print_r($_POST) . "<br>";
?>
Is the element with id collect inside the form? It needs to be.
$("<input type='hidden' name='absent[]' />").val(temp)
.appendTo('form[name="save"]');
$('#collect').append(currentCellText);
This works perfectly.
$("body").delegate("#editorjs_menu_list ul li a", "click", function(e){
e.preventDefault();
$(this).toggleClass("active");
});

Categories