I am trying to populate results with a description from my MySQL database table interest_type
My private function is
private function Get_Interests_Types_From_DB()
{
$sql = "SELECT
InterestID,
InterestDescription
FROM
interest_type";
$result = mysqli_query($this->Con, $sql);
while($row = mysqli_fetch_array($result))
{
$arrayResult[] = $row;
}
return ($arrayResult);
}
The area of code that I am trying to use this function in is within a public function within the same class. The values from the form are numeric. I am trying to tie the $interests variable with the InterestID from the table and then print the InterestDescription, instead of the value of $interests.
function ProcessRegistrationForm()
{
$fname = $_POST['firstname'];
$lname = $_POST['lastname'];
$email = $_POST['email'];
$gender = $_POST['gender'];
$interests = $_POST['interests'];
if(!isset($_POST['firstname']) || !isset($_POST['lastname']) || !isset($_POST['email']) ||
($_POST['firstname']) == '' || ($_POST['lastname']) == '' || ($_POST['email']) == '')
{
echo("Please enter your first / last name and email.");
}
else
{
echo("<h2>Results</h2>");
echo("<div id='results'>");
echo $fname;
echo("<br />");
echo $lname;
echo("<br />");
echo $email;
echo("<br />");
echo $gender;
echo("<br />");
$interestDescription = $this->Get_Interests_Types_From_DB();
foreach($interests as $likes)
{
if($likes == $interestDescription['InterestID'])
echo $$interestDescription['InterestDescription'] . "<br />";
}
echo("<p style='font-weight: bold;'>Your data has been saved! We will contact you soon!</p>");
echo("</div>");
}
$myClub = new Club("localhost","A340User","Pass123Word","info_club");
$date = date("Y/m/d");
$sql="INSERT INTO member
(`FirstName`,`LastName`,`Gender`,`Email`,`MemberSince`)
VALUES
('$fname','$lname','$gender','$email','$date');";
$result = mysqli_query($this->Con,$sql);
/*if($result == true)
{
echo "Successful Insert<br />";
}
else
{
echo "Error Inserting class" . mysqli_error($this->Con) ." <br />";
}*/
for($i = 0; $i < sizeof($interests); $i++)
{
$interest = $interests[$i];
$sql="INSERT INTO member_interests
(`Email`,`InterestID`)
VALUES
('$email',$interest);";
$result = mysqli_query($this->Con,$sql);
}
I am getting: Notice: Undefined index: InterestID in C:\xampp-portable\htdocs\A340\Assign5\Assign5_Club_Membership_Class.php on line 287
How can I print the InterestDescription instead of the value of $interests?
there:
while($row = mysqli_fetch_array($result))
{
$arrayResult[] = $row;
}
now the $arrayResult, which is actually your $interestDescription, contains something like:
$interestDescription[0]["InterestID"]
$interestDescription[1]["InterestID"]
...
and not $interestDescription[InterestID"]
UPDATE:
perhaps you need something like this (assuming that $interests holds an array of IDs)
$interestDescription = $this->Get_Interests_Types_From_DB();
foreach($interests as $likes) {
foreach($interestDescription as $desc) {
if($likes == $desc['InterestID']) {
echo $desc['InterestDescription'] . "<br />";
}
}
}
Related
Edited, please scroll down
I am trying to display 3 variables which consist of data stored in a SQL database. However, only the first gets echoed successfully (topLeftUrl). It is worth noting that the same PHP file also receives data from an input (also in the same PHP file) and stores it in the same SQL database. This code was written for testing purposes and may not be entirely safe.
//Connect
$con = mysqli_connect ("localhost","noneedtoknow","noneedtoknow","noneedtoknow");
if (mysqli_connect_errno())
{
echo "Error: ", mysql_connect_error(), "<br>";
die ();
}
//Store input in SQL database
$result = mysqli_query ($con, "SELECT * FROM edit");
$message = stripslashes ($_POST ['message']);
if ($message !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$message' WHERE id='message'"); }
$topLeftNew = ($_POST ['topLeftUrl']);
if ($topLeftNew !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$topLeftNew' WHERE id='topLeft'"); }
$topRightNew = ($_POST ['topRightUrl']);
if ($topRightNew !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$topRightNew' WHERE id='topRight'"); }
//First echo
while ($row = mysqli_fetch_array ($result))
{
if ($row["id"] == "topLeft" && $done2 == 0)
{
$topLeftUrl = $row["cont"];
}
}
echo "<input type=\"text\" name=\"topLeftUrl\" value=\"" . $topLeftUrl . "\">";
//Second echo
while ($row = mysqli_fetch_array ($result))
{
if ($row["id"] == "topRight" && $done3 == 0)
{
$topRightUrl = $row["cont"];
}
}
echo "<input type=\"text\" name=\"topRightUrl\" value=\"" . $topRightUrl . "\">";
//Third echo
while ($row = mysqli_fetch_array ($result))
{
if ($row["id"] == "message" && $done == 0)
{
echo $row["cont"];
}
}
Edit:
I updated the code, and the problem seems to have changed. For some reason, echo $messageCont; displays an old value of cont WHERE id='message'. The database itself is updated successfully, though, and I see the new value of cont once I refresh the page/re-submit the form. Why do I not see the current value of cont immediately after form submission, though? Here is the new code:
/* Before <!DOCTYPE html> */
//Connect
$con = mysqli_connect ("localhost","noneedtoknow","noneedtoknow","noneedtoknow");
if (mysqli_connect_errno())
{
echo "Error: ", mysql_connect_error(), "<br>";
die ();
}
//Query and update
$result = mysqli_query ($con, "SELECT * FROM edit");
$message = stripslashes ($_POST ['message']);
if ($message !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$message' WHERE id='message'"); }
$topLeftNew = ($_POST ['topLeftUrl']);
if ($topLeftNew !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$topLeftNew' WHERE id='topLeft'"); }
$topRightNew = ($_POST ['topRightUrl']);
if ($topRightNew !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$topRightNew' WHERE id='topRight'"); }
//Query again and read
$done0 = 0;
$done1 = 0;
$done2 = 0;
mysqli_data_seek ($result, 0);
while ($row = mysqli_fetch_array ($result))
{
if ($row["id"] == "topLeft" && $done0 == 0)
{
$topLeftUrl = $row["cont"];
$done0 = 1;
}
else if ($row["id"] == "topRight" && $done1 == 0)
{
$topRightUrl = $row["cont"];
$done1 = 1;
}
else if ($row["id"] == "message" && $done2 == 0)
{
$messageCont = $row["cont"];
$done2 = 1;
}
else null;
}
/* After <!DOCTYPE html> */
/* Form code was omitted as it works perfectly. It is in this same file, though. */
echo "<input type=\"text\" name=\"topLeftUrl\" value=\"" . $topLeftUrl . "\">";
echo "<input type=\"text\" name=\"topRightUrl\" value=\"" . $topRightUrl . "\">";
echo $messageCont;
Any help is appreciated.
Edit: I only had to replace mysqli_data_seek () with the line beginning by $result (cut/paste). Thank you.
I ran into this same problem on my site....you run multiple mysql_fetch_array() on the same query ($result)...I thought this would work on my site but this failed for all but the first of 6 while loops which all referenced the same query on my site (I'm sorry but I don't remember the exact error message in my error_log). Try condensing your 3 while loops into 1 loop, something like this:
while ($row = mysqli_fetch_array ($result)) {
if ($row["id"] == "topLeft" && $done2 == 0) {
$topLeftUrl = $row["cont"];
} else if ($row["id"] == "topRight" && $done3 == 0) {
$topRightUrl = $row["cont"];
} else if ($row["id"] == "message" && $done == 0) {
echo $row["cont"];
} else null;
}
echo "<input type=\"text\" name=\"topRightUrl\" value=\"" . $topRightUrl . "\">";
echo "<input type=\"text\" name=\"topLeftUrl\" value=\"" . $topLeftUrl . "\">";
I'm trying to print/echo values from previous file however instead of showing error, all that is shown is 'Undefined' on a blank page. I've researched and tried several method but nothing works. Please help.
<?PHP
$user_name = "root";
$password = "";
$database = "leadership_program";
$server = "localhost";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
if (isset($_POST['survey_id'])) {
$survey_id = $_POST['survey_id'];
echo $survey_id;
}
if (isset($_POST['marks'])) {
foreach ($_POST['marks'] as $value) {
echo"$value";
}
}
if (isset($_POST['id'])) {
$id = $_POST['id'];
echo $id;
}
// $SQL2 = "UPDATE answer_table SET marks='$value' WHERE survey_id= '$survey_id' AND student_id= '$id'";
//$result2 = mysql_query($SQL2);
//mysql_close($db_handle);
} else {
print "Database NOT Found ";
mysql_close($db_handle);
// header("Location: surveyView.php");
}
?>
Here is displayresult.php
<form action="student_mark_save.php" method="POST"> //<?php...more codes here
if ($strucrow["qns$i"] === 'radio' || $strucrow["qns$i"] === 'checkbox') {
foreach ($arr as $b) {
echo "<br/>";
if (strpos($b, '%#%') !== false) {
$c = substr($b, 3, -2);
//echo $c;
$d = str_replace("$arr[0] :-", ':', $c);
echo $d, "<br/>";
echo "<br/>";
echo "<tr> Marks : <input type=\"text\" name=\"marks[]\"></tr><br />";
//echo $b;
} else {
echo $b;
// echo "is not with comment qns";
}
}
} else if ($strucrow["qns$i"] === 'comment') {
foreach ($arr as $b) {
echo $b;
echo "<tr> Marks : <input type=\"text\" name=\"marks[]\"></tr><br />";
// echo "is not with comment qns";
}
} else {
}
echo "<p/>";
}
$marksquery = sprintf(
"SELECT marks FROM answer_table WHERE survey_id = '%d' AND student_id = '$studentid' ", mysql_real_escape_string($survey_id)
);
$marksQuer = mysql_query($marksquery) or die(mysql_error());
$marksrow = mysql_fetch_assoc($marksQuer);
echo "<td><input type=\"hidden\" value= \"$survey_id\" name=\"survey_id\"></td><br />" ;
echo "<td><input type=\"hidden\" value= \"$studentid\" name=\"id\"></td><br />" ;
echo "<p><input type=\"submit\" value=\"Update\"></p>";
?>
</form>
for undefined mean, there is something which is not existing in global $_POST[]
check try to print $_POST in your first if statement as:
if ($db_found) {
print_r($_POST);
exit();
if (isset($_POST['survey_id'])) {
$survey_id = $_POST['survey_id'];
echo $survey_id;
}
now just see what do you have in $_POST, It might help you...Thanks
Most likely some Post data is not set. Try vardump($_POST); die('happy');.
It would also be better to handle missing Post data instead of just ignoring it so maybe if ($db_found) { should be
<?php
if ( $db_found
&& isset($_POST['survey_id'])
&& isset($_POST['marks'])
&& isset($_POST['id'])
)
{
$survey_id = $_POST['survey_id']; //maybe ensure int
$id = $_POST['id']; //maybe ensure int
$values = array(); //this is important $value will not be available outside the for loop or contain only the last value
foreach ((array)$_POST['marks'] as $value) { //ensure $_POST['marks'] is an array
$values[] = $value; //maybe mysql escape each $value here
}
$SQL2 = sprintf(
"UPDATE answer_table SET marks='%s' WHERE survey_id=%d AND student_id=%d",
impolde(',' $values), //assuming comma separated list here
$survey_id,
$id
);
$result2 = mysql_query($SQL2);
mysql_close($db_handle);
} else { ...
Please also consider to escape the values you read from POST. Doing it this way makes it very easy to SQL inject into your script!
I have created a MySQL database along with a front-end to manipulate it using PHP. However, while I can add content to the database manually, I cannot utilize my front-end. When I try to submit the data in my front-end's form fields, I receive the prompt "Duplicate Candidate Name."
The following PHP file is my general script for displaying the front-end:
<?php
if(isset($_POST['sbmtbtn']) && ($_POST['sbmtbtn'] != ""))
{
$desc = strip_tags($_POST['txtdesc']);
$date = glb_func_chkvl($_POST['txtdate']);
$first = glb_func_chkvl($_POST['txtfirst']);
$last = glb_func_chkvl($_POST['txtlast']);
$skill = glb_func_chkvl($_POST['txtskill']);
$sub1 = glb_func_chkvl($_POST['txtsub1']);
$sub2 = glb_func_chkvl($_POST['txtsub2']);
$person = glb_func_chkvl($_POST['txtperson']);
$company = glb_func_chkvl($_POST['txtcompany']);
$location = glb_func_chkvl($_POST['txtlocation']);
$complex = glb_func_chkvl($_POST['complex']);
$sts = glb_func_chkvl($_POST['lststs']);
$dt = date('Y-m-d');
$emp = $_SESSION['sesadmin'];
$sqryquestion_info
= "SELECT candi_first
FROM question_info
WHERE candi_first='$first'";
if(isset($_POST['frmtyp']) && ($_POST['frmtyp'] == "add"))
{
$srsquestion_info =mysql_query($sqryquestion_info);
$rows = mysql_num_rows($srsquestion_info);
if($rows > 0)
{
$gmsg = "<font color=red size=2>Duplicate Candidate Name . Record not saved</font>";
}
else
{
$iqryquestion_info="insert into question_info(
candi_first,candi_last,date,
skill,subtype_1,
subtype_2,person_int,
comp_name,loc_int,complex_lvl,
type_int,question_candi,q_crton,
q_crtby)
values('$first','$last','$date','$skill','$sub1','$sub2','$person','$company',
'$location','$complex','$sts','$desc','$dt','$emp')";
$irsquestion_info = mysql_query($iqryquestion_info);
if($irsquestion_info==true)
{
$gmsg = "<font color=green size=2>Record saved successfully</font>";
}
else
{
$gmsg = "<font color=red size=2>Record not saved</font>";
}
}
}
if(isset($_POST['frmtyp']) && ($_POST['frmtyp'] == "edit"))
{
$id = $_REQUEST['hdnedit'];
$pg = $_REQUEST['hdnpg'];
$countstart = $_REQUEST['hdncntstrt'];
$sqryquestion_info .=" and ques_id !=$id";
$srsquestion_info = mysql_query($sqryquestion_info);
$rows = mysql_num_rows($srsquestion_info);
if($rows > 0)
{
?>
<script>location.href="view_all_questions.php?sts=d&pg=<?php echo $pg;?>&countstart=<?php echo $countstart;?><?php echo $srchval;?>";</script>
<?php
}
else
{
$uqryquestion_info="update question_info set
date ='$date',
candi_first ='$first',
candi_last ='$last',
skill ='$skill',
subtype_1 ='$sub1',
subtype_2 ='$sub2',
person_int ='$person',
comp_name ='$company',
loc_int ='$location',
complex_lel ='$complex',
type_int ='$company',
question_candi ='$desc',
q_mdfdon ='$dt',
q_mdfdby ='$emp' ";
$uqryquestion_info .= " where ques_id=$id";
$ursquestion_info = mysql_query($uqryquestion_info);
if($ursquestion_info==true)
{
?>
<script>location.href="view_all_questions.php?sts=y&pg=<?php echo $pg;?>&countstart=<?php echo $countstart;?><?php echo $srchval;?>";
</script>
<?php
}
else
{
?>
<script>location.href="view_all_questions.php?sts=n&pg=<?php echo $pg;?>&countstart=<?php echo $countstart;?><?php echo $srchval;?>";
</script>
<?php
}
}
}
/*********************************** End Editing ******************************************************/
}
?>
Here begins my "main file" for editing:
<?php
if(isset($_POST['sbmtbtn']) && ($_POST['sbmtbtn'] != ""))
{
$desc = strip_tags($_POST['txtdesc']);
$date = glb_func_chkvl($_POST['txtdate']);
$first = glb_func_chkvl($_POST['txtfirst']);
$last = glb_func_chkvl($_POST['txtlast']);
$skill = glb_func_chkvl($_POST['txtskill']);
$sub1 = glb_func_chkvl($_POST['txtsub1']);
$sub2 = glb_func_chkvl($_POST['txtsub2']);
$person = glb_func_chkvl($_POST['txtperson']);
$company = glb_func_chkvl($_POST['txtcompany']);
$location = glb_func_chkvl($_POST['txtlocation']);
$complex = glb_func_chkvl($_POST['complex']);
$sts = glb_func_chkvl($_POST['lststs']);
$dt = date('Y-m-d');
$emp = $_SESSION['sesadmin'];
$sqryquestion_info="select candi_first
from question_info
where candi_first='$first'";
if(isset($_POST['frmtyp']) && ($_POST['frmtyp'] == "add"))
{
$srsquestion_info =mysql_query($sqryquestion_info);
$rows = mysql_num_rows($srsquestion_info);
if($rows > 0)
{
$gmsg = "<font color=red size=2>Duplicate Candidate Name . Record not saved</font>";
}
else
{
$iqryquestion_info="insert into question_info(
candi_first,candi_last,date,
skill,subtype_1,
subtype_2,person_int,
comp_name,loc_int,complex_lvl,
type_int,question_candi,q_crton,
q_crtby)
values('$first','$last','$date','$skill','$sub1','$sub2','$person','$company',
'$location','$complex','$sts','$desc','$dt','$emp')";
$irsquestion_info = mysql_query($iqryquestion_info);
if($irsquestion_info==true)
{
$gmsg = "<font color=green size=2>Record saved successfully</font>";
}
else
{
$gmsg = "<font color=red size=2>Record not saved</font>";
}
}
}
if(isset($_POST['frmtyp']) && ($_POST['frmtyp'] == "edit"))
{
$id = $_REQUEST['hdnedit'];
$pg = $_REQUEST['hdnpg'];
$countstart = $_REQUEST['hdncntstrt'];
$sqryquestion_info .=" and ques_id !=$id";
$srsquestion_info = mysql_query($sqryquestion_info);
$rows = mysql_num_rows($srsquestion_info);
if($rows > 0)
{
?>
<script>location.href="view_all_questions.php?sts=d&pg=<?php echo $pg;?>&countstart=<?php echo $countstart;?><?php echo $srchval;?>";</script>
<?php
}
else
{
$uqryquestion_info="update question_info set
date ='$date',
candi_first ='$first',
candi_last ='$last',
skill ='$skill',
subtype_1 ='$sub1',
subtype_2 ='$sub2',
person_int ='$person',
comp_name ='$company',
loc_int ='$location',
complex_lel ='$complex',
type_int ='$company',
question_candi ='$desc',
q_mdfdon ='$dt',
q_mdfdby ='$emp' ";
$uqryquestion_info .= " where ques_id=$id";
$ursquestion_info = mysql_query($uqryquestion_info);
if($ursquestion_info==true)
{
?>
<script>location.href="view_all_questions.php?sts=y&pg=<?php echo $pg;?>&countstart=<?php echo $countstart;?><?php echo $srchval;?>";
</script>
<?php
}
else
{
?>
<script>location.href="view_all_questions.php?sts=n&pg=<?php echo $pg;?>&countstart=<?php echo $countstart;?><?php echo $srchval;?>";
</script>
<?php
}
}
}
/*********************************** End Editing ******************************************************/
}
?>
I'm trying to read a .CSV file and print it in a table format in HTML. At the end of the page is a comments text field where comments get submitted and saved in the database.
When I tested the code below locally it works fine. When I tried to run it on the linux server, it prints out fine when first opened, but when I press submit to save a comment, the page refreshes and the table does not print. Giving an "Invalid argument supplied for foreach()" error. (Note: this doesn't happen locally, i can submit all I want and it does not return an error.)
I've searched on stackoverflow and it seems that most of these problems are related to declaring the variable as an array. However, it seems odd to me as the code works fine the first time with no error, but once I submit it returns an error.
UPDATE: full code for file posted below.
<script>
window.onunload = refreshParent;
function refreshParent() {
window.opener.location.reload();
}
</script>
<?php
//---------------------------------Head/BG---------------------------------------
//Request Case ID
$case = "";
if(isset($_REQUEST['case'])) {
$case = $_REQUEST['case'];
}
$patientID = "";
if(isset($_REQUEST['patient'])) {
$patientID = $_REQUEST['patient'];
}
//Include basic functions to allow connection to SQL db.
include("generic.php");
//Include css and header information.
$printTitle = "Volume Report for Case ".$case."";
$printHeader = "Volume Report for Case ".$case."";
$printFooter = "";
$printBreadcrumb = "";
include("header.php");
//submit tableStatus update
if(isset($_REQUEST['submit'])) {
saveTableStatus($case);
}
//-----------------------------Start of Content----------------------------------
showStatusComment($case);
printVolumeTable($case,$patientID);
tableStatus($case);
//---------------------------End of Content--------------------------------------
//---------------------------Functions Definitions-------------------------------
//print report.csv Table
function printVolumeTable($case,$patientID){
echo "<html><body><table border='1'>\n\n";
$f = fopen("analyze/".$case."/".$patientID."/report.csv", "r");
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
foreach ($line as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "<tr>\n";
}
fclose($f);
echo "\n</table></body></html>";
}
function showStatusComment($case) {
$connection = getMySqlConnection();
$sql = "SELECT p.STATUS_NAME, c.volume_comments FROM cases c, primary_status_lookup as p WHERE c.volume_status=p.STATUS_ID and c.caseid='".$case."'";
$result = mysql_query($sql, $connection) or die(mysql_error());
if($result!== FALSE){
while ($record = mysql_fetch_row($result)) {
$status=$record[0];
$comments=$record[1];
if($status == 'Clear Status') {$status = 'None'; $comments = 'None';}
print("<p><b>Table Status: </b>".$status." / <b>Comments: </b>".$comments."</p>");
}
}
}
//Status & Comments
function tableStatus($case) {
$connection = getMySqlConnection();
$sql = "SELECT volume_status, volume_comments FROM cases WHERE caseid='".$case."'";
$result = mysql_query($sql, $connection) or die(mysql_error());
if($result!== FALSE){
while ($record = mysql_fetch_row($result)) {
$status=$record[0];
$comments=$record[1];
print("<form><p>");
showStatusComment($case);
statusDropdown($case,$status);
print("<input type=hidden name='case' value='".$case."'/>");
print(" <label><b>Comments:</b><textarea name='comments' cols=70 rows=2 >".$comments."</textarea></label><br/><br/>");
print("<input type='submit' name='submit' value='Submit'/><INPUT type='button' value='Close Window' onClick='window.close()'></form>");
}
}
}
//Status Dropdown
function statusDropdown($case,$status){
print("<b>Status:</b>");
$dropdown = "<select name = 'status'><option selected='selected' value=NULL>--Select Status--</option>";
$connection = getMySqlConnection();
$sql = "SELECT STATUS_ID, STATUS_NAME FROM primary_status_lookup ORDER BY STATUS_ID ASC";
$result = mysql_query($sql, $connection) or die(mysql_error());
while($record=mysql_fetch_array($result)){
if ($status == '') {
$dropdown .= "<option value = '{$record['STATUS_ID']}'> {$record['STATUS_NAME']}</option>";
} else if (($status == $record['STATUS_ID']) && ($status == '99')) {
$dropdown .= "<option value = '{$record['STATUS_ID']}'> {$record['STATUS_NAME']}</option>";
} else if ($status == $record['STATUS_ID']) {
$dropdown .= "<option value = '{$record['STATUS_ID']}' selected='selected'> {$record['STATUS_NAME']}</option>";
} else {
$dropdown .= "<option value = '{$record['STATUS_ID']}'> {$record['STATUS_NAME']}</option>";
}
}
$dropdown .="</select>";
echo $dropdown;
}
function saveTableStatus($case)
{
//retrieve selected status
$status = '';
if(isset($_REQUEST['status'])) {
$status = $_REQUEST['status'];
}
//retrieve typed comments
if(isset($_REQUEST['comments'])) {
$comments = $_REQUEST['comments'];
}
if($status=='NULL') {
print("<p class='error'>No status selected, please select a status and try again.</p>");
}
else if (($status!=='NULL')){
$connection = getMySqlConnection();
mysql_query("START TRANSACTION", $connection);
if ($status =='99') {$comments = '';}
$result= mysql_query("Update cases Set volume_status=".$status.", volume_comments ='".mysql_real_escape_string($comments)."' Where caseid='".mysql_real_escape_string($case)."'", $connection);
if($result) {
mysql_query("COMMIT", $connection);
print("<p class='saved'>Table Status Updated!</p>");
} else {
mysql_query("ROLLBACK", $connection);
}
mysql_close($connection);
}
}
?>
If you form, and the script that takes the posted form are not on the same path, then your
$f = fopen("analyze/".$case."/".$patientID."/report.csv", "r");
will not open the same file.
Edit -
Okay I think your problem is your $case variable. If there is no request, the $case is blank (""). So the above line will open "analyze///report.csv" As you can see depending on this code
$case = "";
if(isset($_REQUEST['case'])) {
$case = $_REQUEST['case'];
}
I am working on PHP and databases for an assignment and I would like some help on my coding. The form is submitted to process.php for processing (code for both are reproduced below). I am getting an undefined index warning for $_POST['CustomerID'] and $_POST['BodyStyle'] when process.php runs (the exact location is noted in the code), and the information entered for these fields on the form won't get inserted or updated in the database. The other fields work as intended, generating no errors and are stored in the database. What is going wrong? How can I fix it?
Process.php:
<?php
$dbname = "cars";
$dbuser = "carsuser";
$dbpass = "carspass250";
$dbconnect = odbc_connect($dbname,$dbuser, $dbpass)
or die ("Could not connect. <br>");
$opcode = (int) $_POST["opcode"];
$recno = (int) $_POST["recno"];
if ( ($opcode < -1) || ($opcode > 1) )
{
echo "Invalid data passed from form! <br>";
exit();
}
if (($opcode == 0) || ($opcode == 1))
{
$CustomerID = $_POST['CustomerID']; //Undefined Index
$year = $_POST['year'];
$make = $_POST['make'];
$model = $_POST['model'];
$BodyStyle = $_POST['BodyStyle']; //Undefined Index
$color = $_POST['color'];
if (!all_fields_ok($CustomerID, $year, $make, $model, $BodyStyle, $color))
{
exit();
}
}
if ($opcode == -1)
$SqlStatement = "DELETE from Vehicle WHERE VehicleID = $recno";
if ($opcode == 0)
{
$SqlStatement = "UPDATE Vehicle SET ".
"CustomerID = '$CustomerID', ".
"Year = '$year', ".
"Make = '$make', ".
"Model = '$model', ".
"BodyStyle = '$BodyStyle', ".
"Color = '$color' ".
"WHERE VehicleID = $recno";
}
if ($opcode == 1)
{
$SqlStatement = "INSERT INTO Vehicle ".
"(CustomerID, Year, Make, Model, BodyStyle, Color) ".
"VALUES ('$CustomerID', '$year', '$make', '$model', '$BodyStyle', '$color')";
}
print $SqlStatement."<br>";
$recs = odbc_exec($dbconnect, $SqlStatement)
or die ("Could not locate database");
print "Database Updated! <br>";
print "<a href=listall.php>Return to List</a> ";
function all_fields_ok($CustomerID, $year, $make, $model, $BodyStyle, $color )
{
$errormsg = "";
$flag = 0;
if ( (!is_numeric($CustomerID)) )
{
$errormsg = $errormsg."Input: $CustomerID <br>";
$errormsg = $errormsg."Only numbers are aloud <br><br>";
$flag=1;
}
if(!(is_numeric($year)) || (!(strlen($year)==4)))
{
$errormsg = $errormsg."Input: $year <br>";
$errormsg = $errormsg."Please enter a four-digit year <br><br>";
$flag=1;
}
if ((!ctype_alpha($make)) )
{
$errormsg = $errormsg."Input: $make <br>";
$errormsg = $errormsg."Please enter the make of the vehicle, characters only<br> <br>";
$flag=1;
}
if (!(ctype_alnum($model)) )
{
$errormsg = $errormsg."Input: $model<br>";
$errormsg = $errormsg."Please enter the model of the vehicle, numbers and characters aloud <br><br>";
$flag=1;
}
if ((!ctype_alpha($BodyStyle)) )
{
$errormsg = $errormsg."Input: $BodyStyle <br>";
$errormsg = $errormsg."Please enter the bodystyle of the vehicle, characters only <br><br>";
$flag=1;
}
if ((!ctype_alpha($color)) )
{
$errormsg = $errormsg."Input: $color <br>";
$errormsg = $errormsg."Please enter the color of the vehicle, characters only. <br><br>";
$flag=1;
}
if ($flag == 1)
{
echo "Data not trustworthy. Please revise input and try again. <br><br>";
echo $errormsg;
return false;
}
else
return true;
}
?>
form:
<?php
$dbname = "cars";
$dbuser = "carsuser";
$dbpass="carspass250";
$dbconnect = odbc_connect($dbname,$dbuser, $dbpass)
or die ("Could not connect. <br>");
$opcode = (int) $_POST["opcode"];
$recno = (int) $_POST["recno"];
if ( ($opcode < -1) || ($opcode > 1) )
{
echo "Invalid data passed from form! <br>";
exit();
}
if ($opcode == 0)
{
$SqlStatement = "SELECT * from Vehicle WHERE VehicleID = $recno";
$recs = odbc_exec($dbconnect, $SqlStatement)
or die ("Could not execute query");
$row = odbc_fetch_array($recs) ;
$VehicleID = $row['VehicleID'];
$CustomerID = $row['CustomerID'];
$year = $row['Year'];
$make = $row['Make'];
$model = $row['Model'];
$BodyStyle = $row['BodyStyle'];
$color = $row['Color'];
}
else
{
$recno = 0;
$VehicleID = 0;
$CustomerID = "";
$year = "";
$make = "";
$model = "";
$BodyStyle = "";
$color = "";
}
print "<h1>Vehicle Record </h1>";
print "<form action=process.php method=post> \n";
print "<table>";
if ($opcode == 0)
print "<tr><td> Record Number:</td><td align=left>$recno</td> </tr>\n";
else
print "<tr><td> Record Number: </td><td align=left>New Record</td> </tr>\n";
print "<tr><td> Customer ID: </td>";
print "<td> <input type=text name=CustomerID value=\"$CustomerID\"></td></tr> \n";
print "<tr><td> Year: </td>";
print "<td> <input type=text name=year value=\"$year\"></td></tr> \n";
print "<tr><td> Make: </td>";
print "<td> <input type=text name=make value=\"$make\"></td></tr> \n";
print "<tr><td> Model: </td>";
print "<td> <input type=text name=model value=\"$model\"></td></tr> \n";
print "<tr><td> Style: </td>";
print "<td> <input type=text name=BodyStyle value=\"$BodyStyle\"></td></tr> \n";
print "<tr><td> Color: </td>";
print "<td> <input type=text name=color value=\"$color\"></td></tr> \n";
print "<input type=hidden name=opcode value=$opcode> \n";
print "<input type=hidden name=recno value=$recno> \n";
print "<tr><td> <input type=submit value='Submit Record'></td><td></td></tr> \n \n";
print "</table>";
print "</form>";
odbc_close($dbconnect);
?>
The variables in your $_POST data are defined by the input name attributes, so if you say this
<input name="customer" ... />
<input name="style" ... />
you need to look for
$_POST['customer']
$_POST['style']
so either change your POST lookups or your input names, and make them match.
Also, you should check your html standards, the attributes values should go between "" and you should close all tags with either or finishing it with />
you're not getting the CustomerID and the BodyStyle variables from your POST data, there's something wrong with the request (your form, or whatever you're using)
Correct this column...it cannot have space in it.
"Body Style = '$BodyStyle', ".