PHP & SQL match but script still doesn't work - php

I am having some issues for the last 5 hours. I've been trying to fix it and I can't seem to find a solution, so I hope you can help me!
So I have this vote.php script:
<?php
if(basename($_SERVER["PHP_SELF"]) == "vote.php") {
die("403 - Access Forbidden");
}
echo "<h2 class=\"text-left\">Vote</h2><hr/>";
$earnedpoints = false;
$insertnew = false;
$time = time();
$redirect = "";
$account = $mysqli->real_escape_string(preg_replace("/[^A-Za-z0-9 ]/", '', #$_POST['name']));
$siteid = $mysqli->real_escape_string(#$_POST['votingsite']);
$checkacc = $mysqli->query("SELECT * FROM accounts WHERE name = '$account'");
$countcheckacc = $checkacc->num_rows;
$row = $checkacc->fetch_assoc();
if($countcheckacc == 0 && isset($_POST['submit'])) {
$funct_error = "This account doesn't exist!";
}
if($row['loggedin'] > 0 && isset($_POST['submit'])) {
$funct_error = "This account is logged in!";
} elseif ($account == '' && isset($_POST['submit'])) {
$funct_error = 'You need to put in a username!';
} elseif(empty($_POST['votingsite']) && isset($_POST['submit'])){
$funct_error = "Please select a voting site";
} elseif(isset($_POST['submit'])) {
$checksite = $mysqli->query("SELECT * FROM ".$prefix."vote WHERE id = ".$siteid."");
$countchecksite = $checksite->num_rows;
if($countchecksite == 0 && isset($_POST['submit'])) {
$funct_error = "Invalid voting site.";
} else {
$result = $mysqli->query("SELECT *, SUM(times) as amount FROM ".$prefix."votingrecords WHERE NOT account='' AND NOT account='0' AND account='".$account."' AND siteid = '".$siteid."'") or die('Error - Could not look up vote record!');
$row = $result->fetch_assoc();
$sitequery = $mysqli->query("SELECT * FROM ".$prefix."vote WHERE id = '".$siteid."'");
$vsite = $sitequery->fetch_assoc();
$gvp = $vsite['gvp'];
$gnx = $vsite['gnx'];
$timecalc = $time - $row['date'];
if ($row['amount'] == '' || $timecalc > $vsite['waittime']) {
if($row['amount'] == '') {
$result = $mysqli->query("INSERT INTO ".$prefix."votingrecords (siteid, ip, account, date, times) VALUES ('".$siteid."', '".$ipaddress."', '".$account."', '".$time."', '1')") or die ('Error - Could not insert vote records!');
} else {
$result = $mysqli->query("UPDATE ".$prefix."votingrecords SET siteid = '".$siteid."', ip='".$ipaddress."', account='".$account."', date='".$time."', times='1' WHERE account='".$account."' AND siteid = '".$siteid."'") or die ('Error - Could not update vote records!');
}
$earnedpoints = true;
if ($earnedpoints == true) {
if ($account != '') {
$result = $mysqli->query("UPDATE accounts
SET $colvp = $colvp + $gvp,
$colnx = $colnx + $gnx
WHERE name='".$account."'") or die ('Error - Could not give rewards. Your site administrator needs to configure the NX and VP settings.');
}
$funct_msg = '<meta http-equiv="refresh" content="0; url='.$vsite['link'].'">';
$redirect = true;
}
} elseif($timecalc < $vsite['waittime'] && $row['amount'] != '') {
$funct_msg = 'You\'ve already voted for '.$vsite['name'].' within the last '.round($vsite['waittime']/3600).' hours!';
$funct_msg .= '<br />Vote time: '. date('M d\, h:i A', $row['date']);
} else {
$funct_error = 'Unknown Error';
}
}
}
if($redirect == true) {
echo $funct_msg;
} else {
if(isset($funct_msg)) {
echo '<div class="alert alert-danger">'.$funct_msg.'</div>';
}
if(isset($funct_error)) {
echo '<div class="alert alert-danger">'.$funct_error.'</div>';
}
$query = $mysqli->query("SELECT * from ".$prefix."vote");
if($query->num_rows == 0){
echo "<div class=\"alert alert-danger\">Your administrator has not added any voting sites yet!</div>";
} else {
echo "
<form method=\"post\">
<div class=\"form-group\">
<label for=\"voteSite\">Select Site:</label>
<select name=\"votingsite\" class=\"form-control\" id=\"voteSite\" required>
<option value=\"\" disabled selected>Select Site...</option>";
while($row = $query->fetch_assoc()){
echo "<option value=\"".$row['id']."\">".$row['name']."</option>";
}
echo "</select>
</div>";
if(!isset($_SESSION['id'])) {
echo "<input type=\"text\" name=\"name\" maxlength=\"15\" class=\"form-control\" placeholder=\"Username\" required autocomplete=\"off\"/><br/>";
} else {
echo "<input type=\"text\" name=\"name\" maxlength=\"15\" class=\"form-control\" placeholder=\"".$_SESSION['name']."\" value=\"".$_SESSION['name']."\" required autocomplete=\"off\"/><br/>";
}
echo "
<input type=\"submit\" name=\"submit\" value=\"Submit ยป\" class=\"btn btn-primary\"/>
</form>";
}
}
I have this in votingrecords table in SQL: ip, account, date, times, amount. It's correct.
The problem I'm having is that whenever I type my username to vote for the game, I'm getting this error message "Error - Could not look up vote record!".
Here's the code for this error:
else {
$result = $mysqli->query("SELECT *, SUM(times) as amount
FROM ".$prefix."votingrecords
WHERE NOT account=''
AND NOT account='0'
AND account='".$account."'
AND siteid = '".$siteid."'") or die('Error - Could not look up vote record!');
$row = $result->fetch_assoc();
$sitequery = $mysqli->query("SELECT * FROM ".$prefix."vote WHERE id = '".$siteid."'");
$vsite = $sitequery->fetch_assoc();
$gvp = $vsite['gvp'];
$gnx = $vsite['gnx'];
$timecalc = $time - $row['date'];
I hope you guys can help me, since I've tried everything and cannot get it to work

thanks for helping.
I got this issue fixed by executing this SET GLOBAL sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'; in MYSQL.
This would not happen if #RiggsFolly didn't tell me to use this code to display real useful errors, so thank you.
Thanks all!

Related

How can I show error message inside a form?

The page only show message when I click submit button, but now I want the message show inside the form after click submit button.How can I add some code or change the code following to make the message can run inside the form?
Here is my php code:
<?php
function topic_go($id){
echo "<meta http-equiv=\"refresh\" content=\"0;url=main_forum.php?act=topic&id=".$id."\">";
}
$id = $_GET['id'];
if(!$_SESSION['sign_in']){
$sql4= "SELECT * FROM categories WHERE level <".$_SESSION['userlevel']."+1";
$res4= mysql_query($sql4) or die (mysql_error());
$row4 = mysql_fetch_assoc($res4);
$sql5= "SELECT * FROM sub_categories WHERE sub_id ='".$id."'";
$res5 = mysql_query($sql5) or die (mysql_error());
$row5 = mysql_fetch_assoc($res5);
echo "<script type=\"text/javascript\">";
echo "alert('Please Login To Create Topic!');";
echo "window.location='main_forum.php?act=forum&id=".$row5['sub_id']."'";
echo "</script>";
}else{
if($id){
$sql="SELECT * FROM sub_categories WHERE sub_id = '".$id."'";
$res = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($res) == 0){
echo "The forum you are trying to create a topic on, does not exist!\n";
}else{
$row1 = mysql_fetch_assoc($res);
if ($row1['level'] == 1 && $admin_user_level == 0){
echo "You are not an administrator, you cannot post on this forum";
}else {
if (!$_POST['submit']) {
echo "<table bgcolor=\"#CFFAE4\" cellspacing=\"10\" align=\"center\">\n";
echo "<form method=\"post\" action=\"./main_forum.php?act=create&id=".$id."\">\n";
echo "<tr><td>Forum Sub Category</td><td><select name=\"cat\" style=\"font-size:16px;\">\n";
$sql2= "SELECT * FROM categories WHERE level <".$admin_user_level."+1";
$res2= mysql_query($sql2) or die (mysql_error());
while($row = mysql_fetch_assoc($res2)){
$sql3= "SELECT * FROM sub_categories WHERE sub_cid = '".$row['cat_id']."'";
$res3 = mysql_query($sql3) or die (mysql_error());
echo "<option value=\"0\">".$row['cat_name']."</option>\n";
while($row2 = mysql_fetch_assoc($res3)){
$selected = ($row2['sub_id'] == $id) ? " SELECTED" : "";
echo "<option value=\"".$row2['sub_id']."\"".$selected."> ".$row2['sub_name']."</option>\n";
}
}
echo "</select></td></tr>\n";
echo "<tr><td valign=\"top\">Topic Title</td><td><textarea name=\"title\" style=\"width:400px;height:50px;font-size:16px\"></textarea></td></tr>\n";
echo "<tr><td valign=\"top\">Message</td><td><textarea name=\"message\" style=\"width:500px;height:300px;font-size:20px;\"></textarea></td></tr>\n";
echo "<tr><td colspan=\"2\" align=\"right\"><input type=\"button\" onClick=\"history.go(-1);\" value=\"Back\" class=\"btnz btnz_color\"> <input type=\"submit\" name=\"submit\" value=\"Create Topic\" class=\"btnz btnz_color\"></td></tr>\n";
echo "</form></table>\n";
}else{
$cat = $_POST['cat'];
$title = $_POST['title'];
$msg = $_POST['message'];
if($cat && $title && $msg){
$sql = "SELECT level FROM sub_categories WHERE sub_id ='".$cat."'";
$res = mysql_query($sql) or die (mysql_error());
if(mysql_num_rows($res)==0){
echo "This forum sub category does not exist!\n";
} else{
$row = mysql_fetch_assoc($res);
if ($row['level'] == 1 && $admin_user_level !=1){
echo "You are not an admin therefore you cannot post a new topic!";
}else{
if (strlen($title) < 3 || strlen($title) > 1000){
echo "The title must between 3 and 1000 characters!\n";
}else{
if(strlen($msg) < 3 || strlen($msg) > 10000){
echo "The message must between 3 and 10,000 characters!\n";
}else{
$date = date("m-d-y") . " at " . date("h:i:s");
$time = time();
$sql2 = "INSERT INTO topics (topic_cid, topic_title, topic_uid, topic_date, topic_time, topic_message)
VALUES('".$cat."','".$title."','".$_SESSION['userid']."','".$date."','".$time."','".$msg."')";
$res2 = mysql_query($sql2) or die (mysql_error());
$tid = mysql_insert_id();
topic_go($tid);
}
}
}
}
}else{
echo "Please supply all fields!\n";
} }} }
}
}?>
Thank You For Helping!

Send message to a connected user

I want to send a message from a user (user A) to another user (user B) which those users are connected each other in the database. To be more specific.
We keep the connection of the users in a table in the database which we called friends. In this table we have two columns, username and friend.
I have the code in order to send data between the users but it doesn't perform any checking in order to see if the user A who wants to send a message to the user B are connected to each other. If the users are connected I want to allow them to send the message and if they are not I want to echo a notification that they are not allowed to send a message because they are not connected.
I can understand that I want an if condition where I perform the check to see if the users are connected and have the appropriate code below and if it is not connected then output the notification described above.
How can I create this checking?
I am using php and mysql
HERE IS MY CODE...
<?php
include_once 'header.php';
if (!$loggedin) die();
if (isset($_GET['view'])) {
$view = sanitizeString($_GET['view']);
} else {
$view = $username;
}
if (isset($_POST['text'])){
$text = sanitizeString($_POST['text']);
if ($text != ""){
$pm = substr(sanitizeString($_POST['pm']),0,1);
$time = time();
queryMysql("INSERT INTO messages VALUES(NULL, '$username', '$view', '$pm', $time, '$text')");
}
}
if ($view != "") {
if ($view == $username) {
$name1 = $name2 = "Your";
} else {
$name1 = "<a href='members.php?view=$view'>$view</a>'s";
$name2 = "$view's";
}
echo "<div class='main'><h3>$name1 Messages</h3>";
showProfile($view);
echo <<<_END
<form method='post' action='messages.php?view=$view'>
Type here to leave a message:<br />
<textarea name='text' cols='40' rows='3'></textarea><br />
Public<input type='radio' name='pm' value='0' checked='checked' />
Private<input type='radio' name='pm' value='1' />
<input type='submit' value='Post Message' /></form><br />
_END;
if (isset($_GET['erase'])) {
$erase = sanitizeString($_GET['erase']);
queryMysql("DELETE FROM messages WHERE id=$erase AND recip='$username'");
}
$query = "SELECT * FROM messages WHERE recip='$view' ORDER BY time DESC";
$result = queryMysql($query);
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j) {
$row = mysql_fetch_row($result);
if ($row[3] == 0 || $row[1] == $username || $row[2] == $username) {
echo date('M jS \'y g:ia:', $row[4]);
echo " <a href='messages.php?view=$row[1]'>$row[1]</a> ";
if ($row[3] == 0) {
echo "wrote: "$row[5]" ";
} else {
echo "whispered: <span class='whisper'>" . ""$row[5]"</span> ";
}
if ($row[2] == $username) {
echo "[<a href='messages.php?view=$view" . "&erase=$row[0]'>erase</a>]";
}
echo "<br>";
}
}
}
if (!$num) {
echo "<br /><span class='info'>No messages yet</span><br /><br />";
}
echo "<br /><a class='button' href='messages.php?view=$view'>Refresh messages</a>";
?>
</div><br /></body></html>
The checking system for my question is the below and it works..
<?php
include_once 'header.php';
if (!$loggedin) die();
if (isset($_GET['view'])) $view = sanitizeString($_GET['view']);
else $view = $username;
$result1 = mysql_num_rows(queryMysql("SELECT username,friend FROM friends
WHERE username='$username' AND friend='$view'"));
$result2 = mysql_num_rows(queryMysql("SELECT username,friend FROM friends
WHERE username='$view' AND friend='$username'"));
if (($result1 + $result2) > 1)
{
//REST OF THE CODE
}
?>
what we are doing is that for the result1 we are checking if the logged in username($username) is connected with the viewed profile ($view) and for the result2 we are doing vice versal, to be more specific we are checking in the result2 that if the username of the viewed profile($view) is connected with the ($username) then in the if statement we check that if those two result has more than one row in the table then they are both connected.
PS: sorry for my bad english

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

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

Categories