sorting particular data from table php - php

I tried to sort the particular data from my database. I have done to show the particular data according to the user input from the first page. However when I tried to sort the table, I got some errors which are undefined variable
this is my code to show the data in table and sort the table
<?php
//connect to server
$connect = mysql_connect("localhost", "root", "") or die('no database');
//connect to database
//select the database
mysql_select_db("fak_databases");
//submit button
if($_POST['formSubmit'] == "Submit")
{
$country = $_POST['country'];
}
//query the database
if($country == TRUE) {
$order = "";
$sort = "asc";
if(isset($_GET['orderby'])){
$order = $_GET['orderby'];
$sort = $_GET['sort'];
//limiting the possible values of order/sort variables
if($order != 'wipo_applicant1_city' && $order != 'applicant1_addr1')$order = "applicant1_addr1";
if($sort != 'asc' && $sort != 'desc')$sort = "asc";
$sql = "SELECT wipo_applicant1_city, applicant1_addr1 FROM auip_wipo_sample WHERE applicant1_country='$country' ORDER BY ".mysql_real_escape_string($order)." ".$sort;
//here we reverse the sort variable
if($sort == "asc"){
$sort = "desc";
}
else{
$sort = "asc";
}
}
}
$sql = "SELECT wipo_applicant1_city, applicant1_addr1 FROM auip_wipo_sample WHERE applicant1_country='$country'";
$result = mysql_query($sql) or die('failed to run');
$num_rows = mysql_num_rows($result);
$row_counter = 0;
$icon = "";
echo "<table border=\"1\" cellspacing=\"0\">\n";
echo "<tr>\n";
// first column
echo "<th>";
$icon = "";
if($order == "wipo_applicant1_city"){
if($sort == "asc"){
$icon = "<img src=\"images/up.png\" class=\"arrowSpace\"/>";
}
if($sort == "desc"){
$icon = "<img src=\"images/down.png\" class=\"arrowSpace\"/>";
}
}
//print the result
echo "<a href='showDB1.php?orderby=wipo_applicant1_city&sort=".$sort."'>City</a>".$icon;
echo "</th>\n";
// second column
echo "<th>";
$icon = "";
if($order == "applicant1_addr1"){
if($sort == "asc"){
$icon = "<img src=\"images/up.png\" class=\"arrowSpace\"/>";
}
if($sort == "desc"){
$icon = "<img src=\"images/down.png\" class=\"arrowSpace\"/>";
}
}
echo "<a href='showDB1.php?orderby=applicant1_addr1&sort=".$sort."'>Address</a>".$icon;
echo "</th>\n";
echo "</tr>";
//fetch the result
while($row = mysql_fetch_array($result))
{
if($row_counter % 2){
$row_color="bgcolor='#FFFFFF'";
}else{
$row_color="bgcolor='#F3F6F8'";
}
echo "<tr class=\"TrColor\" ".$row_color.">";
echo "<td>" . $row['wipo_applicant1_city'] . "</td>\n";
echo "<td>" . $row['applicant1_addr1'] . "</td>\n";
echo "</tr>";
$row_counter++;
}
Print "</table>";
?>
I got errors on
Undefined index: formSubmit in C:\xampp\htdocs\fak_ict1999\sorting\showDB1.php
Undefined variable: country in C:\xampp\htdocs\fak_ict1999\sorting\showDB1.php
Undefined variable: country in C:\xampp\htdocs\fak_ict1999\sorting\showDB1.php
Undefined variable: order in C:\xampp\htdocs\fak_ict1999\sorting\showDB1.php
Undefined variable: sort in C:\xampp\htdocs\fak_ict1999\sorting\showDB1.php
and when I analyze my code I think I got a logic error on the
if($_POST['formSubmit'] == "Submit")
{
$country = $_POST['country'];
}
//query the database
if($country == TRUE) {
$order = "";
$sort = "asc";
if(isset($_GET['orderby'])){
$order = $_GET['orderby'];
$sort = $_GET['sort'];
//limiting the possible values of order/sort variables
if($order != 'wipo_applicant1_city' && $order != 'applicant1_addr1')$order = "applicant1_addr1";
if($sort != 'asc' && $sort != 'desc')$sort = "asc";
$sql = "SELECT wipo_applicant1_city, applicant1_addr1 FROM auip_wipo_sample WHERE applicant1_country='$country' ORDER BY ".mysql_real_escape_string($order)." ".$sort;
//here we reverse the sort variable
if($sort == "asc"){
$sort = "desc";
}
else{
$sort = "asc";
}
}
}
$sql = "SELECT wipo_applicant1_city, applicant1_addr1 FROM auip_wipo_sample WHERE applicant1_country='$country'";
because when I tried to to sort the table, the sorting function is trying to access the formsubmit again which is the the form submit is only accessed on the first page when the user choose their option.
is anyone know how to solve this?
my html code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Data Mining</title>
</head>
<body>
<form action="showDB.php" method="post">
<table border="0">
<tr>
<th colspan="3">test</th>
</tr>
<tr>
<td>Select Foreign Agent Country</td>
<td></td>
<td>
<select name="country">
<option value="US">United States</option>
<option value="NZ">New Zealand</option>
<option value="JP">Japan</option>
</select>
</td>
</tr>
<td colspan="3">
<input type="submit" name="formSubmit" value="Submit">
</td>
</table>
</form>
</body>
</html>
here is my javascript code
function SelectAll(btn) {
var blnVal = false;
if (btn.value == "Select All") {
btn.value = "Unselect All";
blnVal = true;
}else {
btn.value = "Select All";
blnVal = false;
}
var d = document.forms["auip_wipo_sample"];
if(d["auip_wipo_sample[]"] == null)
{}
else if (d["auip_wipo_sample[]"].length == null) {
d["auip_wipo_sample[]"].checked = blnVal;
}
else {
for (var i = 0; i < d["auip_wipo_sample[]"].length; i++) {
d["auip_wipo_sample[]"][i].checked = blnVal;
}
}
}

The problem for your variables is that you forgot to initialize $country and that you need to check with e.g. isset() or empty() if the $_POST global value "formSubmit" is available.
Example code here:
<?php
print_r($_POST);
$country = '';
if (isset($_POST['submitted']) && $_POST['submitted'] === 'submit')
{
$country = 'Pangea';
}
print $country;
if ($country == true)
{
print ' => country is true' . PHP_EOL;
}
else
{
print ' => country is false' . PHP_EOL;
}
?>
<!doctype html>
<html>
<head>
</head>
<body>
<form id="myForm" action="test.php" method="post">
<input type="submit" name="submitted" value="submit" />
</form>
</body>
</html>
Hope this helps you.

Going through your code I see somethings that I've tried to explain why they don't work:
Then of course you should not use mysql_* functions because they're deprecated. I don't understand where your call is to the js function, so I left that part out for now.
I hope this is of some help.
<?php
//connect to server
$connect = mysql_connect("localhost", "root", "") or die('no database');
//connect to database
//select the database
mysql_select_db("fak_databases");
//submit button
/* skip this part. Only relevant to check name of submit button when having more submit-buttons in same form
if($_POST['formSubmit'] == "Submit")
{
$country = $_POST['country'];
}
*/
//query the database
//if($country == TRUE) {
if (isset($_REQUEST['country']) { //do like this instead (because country can arrive from link or from form
$country = $_REQUEST['country'];
$order = "";
$sort = "asc";
//if(isset($_GET['orderby'])){ change to:
if(isset($_GET['orderby']) && isset($_GET['sort'])) {
$order = $_GET['orderby'];
$sort = $_GET['sort']; //You're getting the value from $_GET['sort'] but you never check if it is set (like you do with orderby)
//limiting the possible values of order/sort variables
if($order != 'wipo_applicant1_city' && $order != 'applicant1_addr1')$order = "applicant1_addr1";
if($sort != 'asc' && $sort != 'desc')$sort = "asc";
$sql = "SELECT wipo_applicant1_city, applicant1_addr1 FROM auip_wipo_sample WHERE applicant1_country='$country' ORDER BY ".mysql_real_escape_string($order)." ".$sort;
//here we reverse the sort variable
if($sort == "asc"){
$sort = "desc";
}
else{
$sort = "asc";
}
}
//} End of check isset($_GET['country']) should be move down to assure that $country is set
$sql = "SELECT wipo_applicant1_city, applicant1_addr1 FROM auip_wipo_sample WHERE applicant1_country='$country'";
$result = mysql_query($sql) or die('failed to run');
$num_rows = mysql_num_rows($result);
$row_counter = 0;
$icon = "";
echo "<table border=\"1\" cellspacing=\"0\">\n";
echo "<tr>\n";
// first column
echo "<th>";
$icon = "";
if($order == "wipo_applicant1_city"){
if($sort == "asc"){
$icon = "<img src=\"images/up.png\" class=\"arrowSpace\"/>";
}
if($sort == "desc"){
$icon = "<img src=\"images/down.png\" class=\"arrowSpace\"/>";
}
}
//print the result
//echo "<a href='showDB1.php?orderby=wipo_applicant1_city&sort=".$sort."'>City</a>".$icon; //orderby and sort is defined but not $_POST['country']
echo "<a href='showDB1.php?country=".$country."&orderby=wipo_applicant1_city&sort=".$sort."'>City</a>".$icon; //change to this instead so country is passed
echo "</th>\n";
// second column
echo "<th>";
$icon = "";
if($order == "applicant1_addr1"){
if($sort == "asc"){
$icon = "<img src=\"images/up.png\" class=\"arrowSpace\"/>";
}
if($sort == "desc"){
$icon = "<img src=\"images/down.png\" class=\"arrowSpace\"/>";
}
}
//echo "<a href='showDB1.php?orderby=applicant1_addr1&sort=".$sort."'>Address</a>".$icon; //orderby and sort is defined but not $_POST['country']
echo "<a href='showDB1.php?country=".$country."&orderby=applicant1_addr1&sort=".$sort."'>Address</a>".$icon; //change to this instead so country is passed
echo "</th>\n";
echo "</tr>";
//fetch the result
while($row = mysql_fetch_array($result))
{
if($row_counter % 2){
$row_color="bgcolor='#FFFFFF'";
}else{
$row_color="bgcolor='#F3F6F8'";
}
echo "<tr class=\"TrColor\" ".$row_color.">";
echo "<td>" . $row['wipo_applicant1_city'] . "</td>\n";
echo "<td>" . $row['applicant1_addr1'] . "</td>\n";
echo "</tr>";
$row_counter++;
}
Print "</table>";
} //End of check isset($_GET['country']) is moved to the end
?>

Related

Why can't I echo all variables correctly?

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 . "\">";

MySQL Error: Duplicate 'Candidate Name'

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 ******************************************************/
}
?>

PHP - Populating Display Input Data with MySQL Data from Table

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 />";
}
}
}

Invalid argument supplied for foreach() working locally but not remotely

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'];
}

mysql_fetch_array() expect parameter 1

I tried to show some data from database with select option from the first page
but I got two error when the page tried to retrieve the data from database
the errors are
mysql_num_rows() expects parameter 1 to be resource, boolean given
and
mysql_fetch_array() expects parameter 1 to be resource, boolean given
this is my code
<?php
//connect to server
$connect = mysql_connect("localhost", "root", "");
//connect to database
//select the database
mysql_select_db("fak_databases");
//submit button
if($_POST['formSubmit'] == "Submit")
{
$country = $_POST['country'];
}
//query the database
if($country == TRUE) {
$order = "";
$sort = "asc";
$sql = "SELECT wipo_applicant1_city, applicant1_addr1 WHERE applicant1_country='$country' FROM auip_wipo_sample";
if(isset($_GET['orderby'])){
$order = $_GET['orderby'];
$sort = $_GET['sort'];
//limiting the possible values of order/sort variables
if($order != 'wipo_applicant1_city' && $order != 'applicant1_addr1')$order = "applicant1_addr1";
if($sort != 'asc' && $sort != 'desc')$sort = "asc";
$sql = "SELECT wipo_applicant1_city, applicant1_addr1 FROM auip_wipo_sample WHERE applicant1_country='$country' ORDER BY ".mysql_real_escape_string($order)." ".$sort;
//here we reverse the sort variable
if($sort == "asc"){
$sort = "desc";
}
else{
$sort = "asc";
}
}
}
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
$row_counter = 0;
$icon = "";
echo "<table border=\"1\" cellspacing=\"0\">\n";
echo "<tr>\n";
// first column
echo "<th>";
$icon = "";
if($order == "wipo_applicant1_city"){
if($sort == "asc"){
$icon = "<img src=\"images/up.png\" class=\"arrowSpace\"/>";
}
if($sort == "desc"){
$icon = "<img src=\"images/down.png\" class=\"arrowSpace\"/>";
}
}
//print the result
echo "<a href='index.php?orderby=wipo_applicant1_city&sort=".$sort."'>City</a>".$icon;
echo "</th>\n";
// second column
echo "<th>";
$icon = "";
if($order == "applicant1_addr1"){
if($sort == "asc"){
$icon = "<img src=\"images/up.png\" class=\"arrowSpace\"/>";
}
if($sort == "desc"){
$icon = "<img src=\"images/down.png\" class=\"arrowSpace\"/>";
}
}
echo "<a href='index.php?orderby=applicant1_addr1&sort=".$sort."'>Address</a>".$icon;
echo "</th>\n";
echo "</tr>";
//fetch the result
while($row = mysql_fetch_array($result))
{
if($row_counter % 2){
$row_color="bgcolor='#FFFFFF'";
}else{
$row_color="bgcolor='#F3F6F8'";
}
echo "<tr class=\"TrColor\" ".$row_color.">";
echo "<td>" . $row['wipo_applicant1_city'] . "</td>\n";
echo "<td>" . $row['applicant1_addr1'] . "</td>\n";
echo "</tr>";
$row_counter++;
}
Print "</table>";
?>
the line got error are
$num_rows = mysql_num_rows($result);
and
while($row = mysql_fetch_array($result))
I think I already gave parameter in this line
$result = mysql_query($sql);
anyone know how to fix this?
thanks
try this
$sql = "SELECT wipo_applicant1_city, applicant1_addr1 FROM auip_wipo_sample WHERE
applicant1_country='".$country."'";

Categories