After the user select the CD, I'm trying to display a user's selection with editing so I'm displaying it in either textbox or dropdown list. As in the picture I can get Publisher to display in a textbox but for the dropdownlist it's showing as blank. I have try to $CDPub within the option value but it doesn't work.
<form method="get" action="UpdateCD.php">
<div align="center">
<div>Title <input type = "text" name = "CDTitle" value = "<?php echo $CDTitle; ?>" /></div></br>
<div>Year <input type = "text" name = "CDYear" value = "<?php echo $CDYear; ?>" /></div></br>
<div>Price <input type = "text" name = "CDPrice" value = "<?php echo $CDPrice; ?>" /></div></br>
<div>Category <input type = "text" name = "CDCat" value = "<?php echo $CDCat; ?>" /></div></br>
<div>Publisher <input type = "text" name = "CDPub" value = "<?php echo $CDPub; ?>" /></div></br>
Publisher
<select name="CDPub">
<option value= " ">
<?php
include 'database_conn.php'; //make db connection
if (! ( is_object($conn ) && ( get_class( $conn ) == 'mysqli' ))) {
die("DB connection failure.");
}
$rsCDpub = mysqli_query($conn, "SELECT nmc_publisher.pubName FROM nmc_publisher");
if ( !$rsCDpub ) {
die("No result from DB query."); //probably invalid SQL, table error
}
if ( $rsCDpub->num_rows < 1 ) {
die("No rows returned from DB query."); //query runs but nothing is found in DB to match
}
while($Catpubresult = mysqli_fetch_array($rsCDpub)){
echo "<option value='".$Catpubresult[0]."'>".$Catpubresult[0]."</option>";
//echo "<option value='".$Catpubresult[0]."'>".$Catpubresult[0]."</option>";
}
?></br></br>
<div><input type="submit" value="Update"></div>
</form>
You can do something like this:
// your code
while($Catpubresult = mysqli_fetch_array($rsCDpub)){
$option = "<option value='{$Catpubresult[0]}'";
if($Catpubresult[0] == $CDPub){
$option .= " selected='selected'";
}
$option .= ">{$Catpubresult[0]}</option>";
echo $option;
//echo "<option value='".$Catpubresult[0]."'>".$Catpubresult[0]."</option>";
}
// your code
Related
I'm having an issue inserting php form array values into a MySQL table. Right now the form itself pulls worker information from another table to populate the fields and their values. Right now there are only three workers that would populate those fields, however as more workers get added, there could be as many as 40. When I add just the first worker from the form, all the information inserts normally. However, when I add more than one, the title and employeeId fields are blank and I can't figure out why. Any help would be greatly appreciated.
Here is the form:
<form method = 'POST' action = 'addworkers.php'>
<?php
$sql2 = "select * from workers where companyId = 1";
$result2 = mysqli_query($conn,$sql2);
$numRows = mysqli_num_rows($result2);
$check = 0;
while($row2 = $result2->fetch_assoc()) {
$employeeId = $row2["id"];
$name = $row2["name"];
echo '<input type="checkbox" name="employeeId[]" value="' . $employeeId . '">';
echo "$name\n";
echo '<input type = "hidden" value="' . $companyId . '" name = "companyId[]"/>';
echo '<input type = "hidden" value="' . $jobNumber . '" name = "jobNumber[]"/>';
echo 'Site Title : <input type = "text" name = "title[]"/><br/>';
}
?>
<input type="hidden" name="count" value="<?php echo "$numRows"; ?>"/>
<input type = 'submit' value = 'SEND'/>
</form>
Then the addworkers.php code
require_once("dbConfig.php");
session_start();
$timestamp = date("Y-m-d");
if (isset($_SESSION['loginname'])) {
$companyId = isset($_POST['companyId']) ? $_POST['companyId'] : "" ;
$jobNumber = isset($_POST['jobNumber']) ? $_POST['jobNumber'] : "" ;
$employeeId = isset($_POST['employeeId']) ? $_POST['employeeId'] : "" ;
$title = isset($_POST['title']) ? $_POST['title'] : "" ;
foreach($title as $key=>$value){
if (!empty($value)) {
$query = "insert into `Jobs` (id, companyId, jobId, employeeId, siteTitle, dateAdded) values (NULL,'$companyId[$key]', '$jobNumber[$key]','$employeeId[$key]','$value','$timestamp')";
$result = mysqli_query($conn,$query);
}
}
} else {
echo "Error";
}
I changed the echo "Error" line but the output was clear.
It must be a problem with how the array is counted but I'm not sure how to fix it. in the form, if I check the boxes next to each row, all the information is entered into the table properly. If I only check the second and/or third line, it doesn't include the Site Title and the employeeId is reversed.
Here is the output of the form:
<form method = 'POST' action = 'insertworkers.php'>
<input type="checkbox" name="employeeId[]" value="1">Mike
<input type = "hidden" value="1" name = "companyId"/>
<input type = "hidden" value="12345" name = "jobNumber"/>
Site Title : <input type = "text" name = "title[]"/>
<input type="checkbox" name="employeeId[]" value="2">Steve
<input type = "hidden" value="1" name = "companyId"/>
<input type = "hidden" value="12345" name = "jobNumber"/>
Site Title : <input type = "text" name = "title[]"/>
<input type="checkbox" name="employeeId[]" value="3">Roger
<input type = "hidden" value="1" name = "companyId"/>
<input type = "hidden" value="12345" name = "jobNumber"/>
Site Title : <input type = "text" name = "title[]"/>
<input type="hidden" name="count" value="3"/>
<input type = 'submit' value = 'SEND'/>
</form>
I also changed the foreach loop to a for loop since the array depth should be the same as all fields will be mandatory
require_once("dbConfig.php");
session_start();
$counter = "".$_POST["count"]."";
$timestamp = date("Y-m-d");
if ( isset( $_SESSION['loginname'] ) ) {
$companyId = isset($_POST['companyId']) ? $_POST['companyId'] : "" ;
$jobNumber = isset($_POST['jobNumber']) ? $_POST['jobNumber'] : "" ;
$employeeId = isset($_POST['employeeId']) ? $_POST['employeeId'] : "" ;
$title = isset($_POST['title']) ? $_POST['title'] : "" ;
for($i=0, $count = count($employeeId);$i<$count;$i++){
if (!empty($employeeId)) {
$query = "insert into `customerJobs` (id, companyId, jobId, employeeId, siteTitle, dateAdded) values (NULL,'$companyId', '$jobNumber','$employeeId[$i]','$title[$i]','$timestamp')";
$result = mysqli_query($conn,$query);
}
}
} else {
echo "Error";
}
Once I check one checkbox of multiple students, only one student is stored inside my database. I want to get the value of the checkbox of each student added every input of the admin. One more thing is that I want to copy the data of the first name and section inside the table //see comment to "attendance" database. The database of the value inside the table is "student". Thanks in advance.
<html>
<body>
<form method = "POST"><strong>
Set the date:
</strong>
<input type = "date" name = "set_date"></br></br>
<table width="800" border="3" cellpadding="1" cellspacing="1">
<tr>
<th><center>First name</center></th>
<th><center>Section</center></th>
<th><center>Status</center></th>
</tr>
<?php
$con = mysql_connect("localhost", "root", "avtt123");
mysql_select_db("arvintarrega",$con);
$query = mysql_query("SELECT * FROM student");
echo "<form action = attendance.php method = POST>";
while($student=mysql_fetch_array($query))
{
echo "<tr>";
echo "<td><center>".$student['fname']."</center></td>"; // the 'fname' and the 'section'
echo "<td><center>".$student['section']."</center></td>";
echo '<td><center><input type = "checkbox" name = "status" value = "Present">Present </input>';
echo '<input type = "checkbox" name = "status" value = "Absent">Absent </input>';
}
echo "</form>";
echo "</table>";
if(isset($_POST['save']))
{
if(filter_input(INPUT_POST, 'set_date') && filter_input(INPUT_POST, 'status'))
{
if(isset($_POST['set_date']) && ($_REQUEST['status']=="Present"))
{
$sql = "INSERT INTO attendance(date, status) VALUES('$_POST[set_date]', '$_REQUEST[status]')";
echo '<span style="color:green;"><strong></br>Attendance Complete!<strong></span>';
}
else if(isset($_POST['set_date']) && ($_REQUEST['status']=="Absent"))
{
$sql = "INSERT INTO attendance(date, status) VALUES('$_POST[set_date]', '$_REQUEST[status]')";
echo '<span style="color:green;"><strong></br>Attendance Complete!<strong></span>';
}
mysql_query($sql, $con);
}
else
echo '<span style="color:red;"><strong></br>All fields are required</strong></span>';
}
?>
</br></br>
<input type = "submit" name = "save" value = "Submit>
</form>
</body>
</html>
I am making a web-application for Quiz competition. For the purpose, I wrote a php script which is processed by the same page. Now when I am adding scores and question numbers, the score is incremented or remain unchanged depending upon the previous answer if someone is refreshing the page. Now I googled the problem and found something like PRG.But this method works if the page is processed by other page (What I think ). Again, a friend of mine told me to use Javascript. But what if someone has turned Js off? Can't we have a solution in php itself. I tried session method also, but I did not fix the issue .
Please help me .
PHP Quiz script is here:
<?php
// starting session
session_start();
if (!isset($_SESSION['user_id'])) {
echo '<p class="login">Please log in to access this page.</p>';
exit();
}
else {
echo('<p class="login">You are logged in as ' . $_SESSION['username'] . '. Log out.</p>');
}
// $query = ;
//this get is taking level from index.php
if ( isset($_GET['level']))
{
$level = $_GET['level'];
}
else
{
$level = 'E';
}
//connecting to Data Base
require_once('connectvars.php');
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (isset($_POST['submit']))
{
$level = $_POST['level'];
// $_SESSION['flag']
$answer = $_POST['answer'];
if ( !empty($answer))
{
$qid = $_POST['qid'];
$select = $_POST['select'];
$user_id = $_SESSION['user_id'];
$result = mysqli_query($dbc,"select * from question where qid = '$qid'")
or die("Error in connection.");
$row = mysqli_fetch_array($result);
if ( $row['ANSWER'] == $answer)
{
echo 'Your answer is correct.';
mysqli_query($dbc,"insert into user_question ( qid,user_id,answer_key) values ( '$select','$user_id',1)")
or die ("Error in updating values in user_question");
}
else
{
echo 'Your answer is incorrect.';
mysqli_query($dbc,"insert into user_question ( qid,user_id,answer_key) values ( '$select','$user_id',0)")
or die ("Error in updating values in user_question");
}
$answer = "";
}
else
{
echo 'You did not answer the previous question';
}
}
$user_id = $_SESSION['user_id'];
// $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
//Taking a random value from the list of question
$id_list = array();
// echo $user_id;
// echo $level;
$result = mysqli_query($dbc,"select * from question where lvl = '$level' and user_id != '$user_id' and qid not in ( select qid from user_question where user_id = '$user_id' )");
while ( ($row = mysqli_fetch_array($result)) )
{
if ( $row['user_id'] != $user_id)
array_push($id_list,$row['qid']);
}
// print_r($id_list);
//Whether user viewed all the questions
if ( empty($id_list))
{
echo 'Great, You have visited all the question, wait for more update ';
echo '<br>';
echo '❤ View Your Score<br />';
exit();
}
// Taking a random value after shuffling it
shuffle($id_list);
$select = $id_list[array_rand($id_list)];
$result = mysqli_query($dbc,"select * from question where qid='$select'");
// Showing the question
while ( ($row = mysqli_fetch_array($result)) )
{
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h3> <?php echo $row['sawal']; ?></h3>
<form method = "POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="radio" name=" answer" value="A" ><?php echo $row['a']; ?><br>
<input type="radio" name=" answer" value="B" ><?php echo $row['b']; ?><br>
<input type="radio" name=" answer" value="C" ><?php echo $row['c']; ?><br>
<input type="radio" name=" answer" value="D" ><?php echo $row['d']; ?><br>
<input type="hidden" name = "qid" value="<?php echo $row['qid'] ?>">
<!-- <input type="hidden" name = "range" value="<?php $range ?>"> -->
<input type="hidden" name = "level" value="<?php echo $level ?>">
<input type="hidden" name = "select" value="<?php echo $select ?>">
<input type="submit" name="submit" value="ANSWER"/>
</form>
</body>
</html>
<?php
require_once('view_score.php');
}
?>
Edit:
I changed my code as Mat is suggested. But it is not allowing me to have different question from the table?
The revised php code is here:
<?php
// starting session
session_start();
if (!isset($_SESSION['user_id'])) {
echo '<p class="login">Please log in to access this page.</p>';
exit();
}
else {
echo('<p class="login">You are logged in as ' . $_SESSION['username'] . '. Log out.</p>');
}
// $query = ;
//this get is taking level from index.php
if ( isset($_GET['level']))
{
$level = $_GET['level'];
}
else
{
$level = 'E';
}
//connecting to Data Base
require_once('connectvars.php');
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (isset($_POST['submit']))
{
$is_new_post = true;
if (isset($_SESSION["myform_key"]) && isset($_POST["myform_key"]))
{
if($_POST["myform_key"] == $_SESSION["myform_key"] ){
$is_new_post = false;
}
}
if($is_new_post){
$_SESSION["myform_key"] = $_POST["myform_key"];
$level = $_POST['level'];
// $_SESSION['flag']
$answer = $_POST['answer'];
if ( !empty($answer))
{
$qid = $_POST['qid'];
$select = $_POST['select'];
$user_id = $_SESSION['user_id'];
$result = mysqli_query($dbc,"select * from question where qid = '$qid'")
or die("Error in connection.");
$row = mysqli_fetch_array($result);
if ( $row['ANSWER'] == $answer)
{
echo 'Your answer is correct.';
mysqli_query($dbc,"insert into user_question ( qid,user_id,answer_key) values ( '$select','$user_id',1)")
or die ("Error in updating values in user_question");
}
else
{
echo 'Your answer is incorrect.';
mysqli_query($dbc,"insert into user_question ( qid,user_id,answer_key) values ( '$select','$user_id',0)")
or die ("Error in updating values in user_question");
}
$answer = "";
}
else
{
echo 'You did not answer the previous question';
}
}
}
$user_id = $_SESSION['user_id'];
// $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
//Taking a random value from the list of question
$id_list = array();
// echo $user_id;
// echo $level;
$result = mysqli_query($dbc,"select * from question where lvl = '$level' and user_id != '$user_id' and qid not in ( select qid from user_question where user_id = '$user_id' )");
while ( ($row = mysqli_fetch_array($result)) )
{
if ( $row['user_id'] != $user_id)
array_push($id_list,$row['qid']);
}
// print_r($id_list);
//Whether user viewed all the questions
if ( empty($id_list))
{
echo 'Great, You have visited all the question, wait for more update ';
echo '<br>';
echo '❤ View Your Score<br />';
exit();
}
// Taking a random value after shuffling it
shuffle($id_list);
$select = $id_list[array_rand($id_list)];
$result = mysqli_query($dbc,"select * from question where qid='$select'");
// Showing the question
while ( ($row = mysqli_fetch_array($result)) )
{
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h3> <?php echo $row['sawal']; ?></h3>
<form method = "POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="radio" name=" answer" value="A" ><?php echo $row['a']; ?><br>
<input type="radio" name=" answer" value="B" ><?php echo $row['b']; ?><br>
<input type="radio" name=" answer" value="C" ><?php echo $row['c']; ?><br>
<input type="radio" name=" answer" value="D" ><?php echo $row['d']; ?><br>
<input type="hidden" name = "qid" value="<?php echo $row['qid'] ?>">
<!-- <input type="hidden" name = "range" value="<?php $range ?>"> -->
<input type="hidden" name = "level" value="<?php echo $level ?>">
<input type="hidden" name = "select" value="<?php echo $select ?>">
<input type="hidden" name="myform_key" value="<?php echo md5("CrazyFrogBros"); ?>" />
<input type="submit" name="submit" value="ANSWER"/>
</form>
</body>
</html>
<?php
require_once('view_score.php');
}
?>
I tried session method also, but I did not fix the issue
I don't know how you code it but you can try this:
1. Set a session token with unique hash value e.g.
$_SESSION['formtoken'] = sha1(uniqid('', true));
include it in your form (input hidden) value = $_SESSION['formtoken']
everytime the user submit the form reset the $_SESSION['formtoken'] value
I've been trying to get this code to work for a long time now but i keep getting this error:
Notice: Undefined index: id in C:\xampp\htdocs\Project\modify.php on line 4
Here's the code:
<?php
include 'includes/phpConnection.php';
if(!isset($_POST["submit"])) {
$q = "SELECT * FROM members WHERE ID =".$_GET['id'];
$result = mysql_query($q);
$person = mysql_fetch_array($result);
}
?>
<h1>Edit A Member</h1>
<form method='post' action= '<?php echo $_SERVER['PHP_SELF']; ?>'>
First Name<input type = 'text' name= 'inputFName' value = '<?php echo $person['FIRST_NAME']?>'/>
First Last Name<input type = 'text' name= 'inputLname' value = '<?php echo $person['LAST_NAME']?>'/>
Second Last Name<input type = 'text' name= 'inputLname2' value = '<?php echo $person['LAST_NAME2']?>'/>
Date of Birth<input type = 'date' name= 'inputDoB' value = '<?php echo $person['DATE_OF_BIRTH']?>'/>
relation<input type = 'text' name= 'inputRelation' value = '<?php echo $person['relation_to_me']?>'/>
age<input type = 'text' name = 'age' />
<input type="hidden" name = "id" value="<?php echo $_GET['id'];?>"/>
<br />
<input type="submit" name="submit"/>
</form>
<?php
if(isset($_POST['submit'])){
$u = "UPDATE members SET `FIRST_NAME`='$_POST[inputFName]',`LAST_NAME`='$_POST[inputLname]',`LAST_NAME2`='$_POST[inputLname2]',`DATE_OF_BIRTH`='$_POST[inputDoB]',`AGE`= '$_POST[age]',`relation_to_me`='$_POST[inputRelation]' WHERE ID =".$_POST['id'];
mysql_query($u) or die(mysql_error());
}
?>
please help
It looks like you're posting id, not sending it as a query parameter.
if($_POST["id"] === "") echo "id is an empty string\n";
if($_POST["id"] === null) echo "id is null\n";
if(isset($_POST["id"])) echo "id is set\n";
if(!empty($_POST["id"])) echo "id is not empty";
Correct this in your code:
<?php
include 'includes/phpConnection.php';
if(!isset($_POST["submit"]) && isset($_GET["id"])) { // <--- declare id here
$id = intval($_GET["id"]); // <--- declare id here and admit only integer values
$q = "SELECT * FROM members WHERE ID =".$id;
$result = mysql_query($q);
$person = mysql_fetch_array($result);
}
?>
Remember to sanitize data input to prevent SQL Injection.
<?php for ($i=0; $i <$num_results; $i++){?>
<tr height="25px">
<td align="center "><?php $row = $result->fetch_assoc();
echo "<strong>". ($i+1)?><td >
<td align="center "><?php echo stripslashes($row['I'd]); ?><td>
I want the value which I select from the listbox and want to store in php variable because I want to use that variable for further use. Please help..
<form name="myform" method="post">
<?php
include('dbconnect.php');
db_connect();
$query = "SELECT * FROM test_customer"; //Write a query
$data = mysql_query($query); //Execute the query
?>
<select id="cust_name" name="mylist" onchange="selectedvalue()">
<?php
while($fetch_options = mysql_fetch_array($data)) { //Loop all the options retrieved from the query
?>
//Added Id for Options Element
<option id ="<?php echo $fetch_options['test_id']; ?>" value="<?php echo $fetch_options['cust_name']; ?>"><?php echo $fetch_options['cust_name']; ?></option><!--Echo out options-->
<?php
}
?>
</select>
</form>
<select id="cust_name" name="mylist" onchange="selectedvalue(this.value)">
access that values selectedvalue(val) in parameter
get that selected value and store it in input type= hidden as u need it for further use..
If you want to store into a php-variable, you must post the form. I've added a submit-button below. You also must speciy an action to where the form is submitted to: action="whatever.php"
<form name="myform" method="post" action="whatever.php"> <!-- added action here -->
<?php
include('dbconnect.php');
db_connect();
$query = "SELECT * FROM test_customer"; //Write a query
$data = mysql_query($query); //Execute the query
?>
<select id="cust_name" name="mylist" onchange="selectedvalue()">
<?php
while($fetch_options = mysql_fetch_array($data)) { //Loop all the options retrieved from the query
?>
//Added Id for Options Element
<option id ="<?php echo $fetch_options['test_id']; ?>" value="<?php echo $fetch_options['cust_name']; ?>"><?php echo $fetch_options['cust_name']; ?></option><!--Echo out options-->
<?php
}
?>
</select>
<!-- added submit button -->
<input type="submit" value="ok" />
</form>
Create a php-file called whatever.php and in this file, store the value into $cust_name by doing this:
<?php
$cust_name = $_POST['mylist']; //mylist is the name of the select-list
?>
If you want to post the form without having to reload the page, you must use something called ajax.
This works for me.Try this example.
public function getAptTypesBySelectedKy($valKy) {
$stmt = "SELECT ap_typ_ky, ap_typ_desc FROM apt_types WHERE ap_stat=1 order by ap_typ_desc";
try {
$con = DataHandler::connect();
$values = $con->prepare($stmt);
if ($values->execute()) {
echo '<select class="form-control" name="type" id="apt_types_slc">';
while ($row = $values->fetch(PDO::FETCH_ASSOC)) {
if ($valKy === $row['ap_typ_ky']) {
echo '<option value="' . $row['ap_typ_ky'] . '" selected>' . $row['ap_typ_desc'] . '</option>';
} else {
echo '<option value="' . $row['ap_typ_ky'] . '">' . $row['ap_typ_desc'] . '</option>';
}
}
echo '</select>';
}
} catch (PDOException $ex) {
echo 'Error on apartment types';
$error = $ex;
print_r('<pre>' . $ex->getCode() . '</pre>');
print_r('<pre>' . $ex->getMessage() . '</pre>');
}
}
In your html form page.
$__typKy = $_RA['typeky'] //this line get the selected value from database and set as parameter to the function getAptTypesBySelectedKy()
<?php
$__typKy;
if (isset($_RA)) {
$__typKy = $_RA['typeky'];// you need to find this key from database.
//this is the selected value key of `<select>`
}
$var = new DataHandler();
$var->getAptTypesBySelectedKy($__typKy);
?>