My code generates only one result e.g "admin", then generates error. Would you please tell me how can i fix this and show all the result.
while($row = mysqli_fetch_assoc($query)) {
$role = $row['userrole'];
Function RoleFunction($roles){
if ($roles==1) {
echo " Admin";
}
else {
echo " User";
}
}
$test = RoleFunction($role);
echo "<tr>";
echo "<td>".$test."</td>";
echo "</tr>";
}
Result : Admin
Fatal error: Cannot redeclare RoleFunction() (previously declared in E:\xampp\htdocs\meds\delete.php:50) in
E:\xampp\htdocs\meds\delete.php on line 50
Keep your function RoleFunction($roles) outside of loop.
function RoleFunction($roles){
if ($roles == 1) {
return " Admin";
}
else {
return " User";
}
}
while ($row = mysqli_fetch_assoc($query)) {
$role = $row['userrole'];
// Print the role
echo "<tr><td>".RoleFunction($role)."</td></tr>";
}
Try the above code. It should be working.
I thin this will work...
Function RoleFunction($roles){
while($row = mysqli_fetch_assoc($query)) {
$role = $row['userrole'];
if ($roles==1) {
echo " Admin";
}
else {
echo " User";
}
$test = RoleFunction($role);
echo "<tr>";
echo "<td>".$test."</td>";
echo "</tr>";
}
}
your function is in loop, it should be outside loop like this:
function RoleFunction($roles){
if ($roles == 1) {
return "Admin";
} else {
return "User";
}
}
while ($row = mysqli_fetch_assoc($query)) {
$role = $row['userrole'];
// Print the role
echo "<tr><td>".RoleFunction($role)."</td></tr>";
}
It will work for sure
Related
I want to Print some dynamically data from my function to passing string in function like this.
My Function
function mysql_funX_Repeter($query,$itemtemplet)
{
$this->mysql_funX_connect();
$result = mysql_query($query) or die("Repeter Query Error.");
if (!$result)
{
$message = 'ERROR:' . mysql_error();
return $message;
}
else
{
$newtempelt = str_replace("Eval", '$row', $itemtemplet);
while ($row = mysql_fetch_array($result))
{
echo $newtempelt;
}
}
}
Passing Value In Function
<ul>
<?php
$rptvalue="<li><a href=''>Eval['name']</a></li>";
$myFun->mysql_funX_Repeter("Select name from tbldemo",$rptvalue);
?>
</ul>
My Output
$row['name']
$row['name']
$row['name']
I want Output
raj
ram
prince
But it's Show me only variable but not show it's database value.
How to solve this...!!!
I would change a little bit your method.
function mysql_funX_Repeter($query,$itemtemplet)
{
$this->mysql_funX_connect();
$result = mysql_query($query) or die("Repeter Query Error.");
if (!$result)
{
$message = 'ERROR:' . mysql_error();
return $message;
}
else
{
while ($row = mysql_fetch_array($result))
{
echo "<li><a href=''>".$row[$itemtemplet]."</a></li>";
}
}
}
And of course, your method invokation:
<ul>
<?php
$rptvalue="name";
$myFun->mysql_funX_Repeter("Select ".$rptvalue." from tbldemo",$rptvalue);
?>
</ul>
And that's how I'd do it to avoid nasty evals. :)
function mysql_funX_Repeter($query,$itemtemplet)
{
$html='';
$this->mysql_funX_connect();
$result = mysql_query($query) or die("Repeter Query Error.");
$num_rows=mysql_num_rows($result);
if($num_rows){
while ($row = mysql_fetch_array($result))
{
$newtempelt = str_replace("Eval", $row['column_name'], $itemtemplet);
$html.="<li><a href=''>".$newtempelt."</a></li>";
}
}
return $html;
}
//calling method mysql_funX_Repeter
<ul>
<?php
$rptvalue="name";
echo $myFun->mysql_funX_Repeter("Select ".$rptvalue." from tbldemo",$rptvalue);
?>
</ul>
Developer My Problem Was Solved.
Thanks for Reply.
My Function
//This Repeter Function Created By Priyank Patel
function mysql_funX_Repeter($query,$itemtemplet)
{
$this->mysql_funX_connect();
$result = mysql_query($query) or die("Repeter Query Error.");
if (!$result)
{
$message = 'ERROR:' . mysql_error();
return $message;
}
else
{
preg_match_all('/{([^}]*)}/', $itemtemplet, $matches);
$select = '';
while($row = mysql_fetch_assoc($result)){
$aux = $itemtemplet;
for($i = 0; $i < count($matches[0]); $i++){
$aux = str_replace($matches[0][$i], $row[$matches[1][$i]],$aux);
}
$select .= $aux."\n";
}
mysql_close();
return $select;
}
}
Calling Style
<ul><?php $templet="<li>{name}</li>";echo $myFun->mysql_funX_Repeter("Select * from tbldemo",$templet);?></ul>
I used to print MySQL query results like this:
$query="SELECT fname,lname,email FROM users";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
$i=0;
echo '<table BORDERCOLOR=black>';
?>
<tr>
<th>Vardas</th><th>Pavarde</th><th>E-Mail</th>
</tr>
<?php
while ($i < $num) {
$field1=mysql_result($result,$i,"fname");
$field2=mysql_result($result,$i,"lname");
$field3=mysql_result($result,$i,"email");
echo "<td>";
echo $field1;
echo "</td>";
echo "<td>";
echo $field2;
echo "</td>";
echo "<td>";
echo $field3;
echo "</td>";
echo "</tr>";
$i++;
}
echo "</table>";
But this time I have to use something different , and I was wondering how can I print out my results when using the function/query shown below:
Query code (in 'class DB'):
function query($querytext) {
$rs = mysql_query($querytext, $this->_link);
if($this->_debug) {
$this->addDebugMessage("\t<tr>\n\t\t<td class=\"debug_nr\">".$this->_queryCount++."</td>\n\t\t<td class=\"debug_queInfo\"><b>Query: (".#mysql_num_rows($rs).")</b></td>\n\t\t<td>" . htmlspecialchars($querytext) . "</td>\n\t</tr>\n");
if(mysql_error() != '') {
$this->addDebugMessage("\t<tr>\n\t\t<td class=\"debug_nr\">".$this->_queryCount++."</td>\n\t\t<td class=\"debug_queInfo\"><b>Error #".mysql_errno($this->_link)." :</b></td>\n\t\t<td>" . htmlspecialchars(mysql_error($this->_link)) . "</td>\n\t</tr>\n");
}
}
if($rs) {
$num_rows = #mysql_num_rows($rs);
if($num_rows) {
if($num_rows > 0) {
$rsarray = array();
while($line = mysql_fetch_array($rs , MYSQL_ASSOC)) {
array_push($rsarray, $line);
}
mysql_free_result($rs);
return $rsarray;
} else {
return false;
}
} else {
if(mysql_affected_rows($this->_link) > 0) {
return true;
} else {
return false;
}
}
} else {
return false;
}
}
(in 'class User')
function findUser($phrase){
global $DB;
$results=$DB->query("SELECT * FROM users WHERE fname LIKE '%'$phrase'%' OR lname LIKE '%'$phrase'%' OR email LIKE '%'$phrase'%'");
return $results;
}
In index.php (what do I use to print this out?):
$USER->findUser("john");
or maybe it should be
$results= $USER->findUser("john);
OR
$results=DB->findUser("john");
Seems you have a typo
function findUser($phrase){
global $DB;
$DB->query("SELECT * FROM users WHERE fname LIKE '%'$phrase'%' OR lname LIKE '%'$phrase'%' OR email LIKE '%'$phrase'%'");
}
There is extra quotes in your query.
function findUser($phrase){
global $DB;
$DB->query("SELECT * FROM users WHERE fname LIKE '%$phrase%' OR lname LIKE '%$phrase%' OR email LIKE '%$phrase%'");
}
So my code get a value from previous page, compare it with a table field in the database and display success or failure. Here is the original code:
<?php
if ($_GET['q'] !='')
{
include('config.inc');
$foo = $_GET['q'];
$query= "INSERT INTO register(name) VALUES('$foo')";
$result = mysql_query("SELECT * FROM user_student");
while($row = mysql_fetch_array($result))
{
$id= $row['sid'];
if($id==$foo)
{
$res = mysql_query($query);
if ($res)
{
echo 'Insertion ok';
}
else
{
echo " ";
echo "Attendance already taken for $foo";
}
}
else
{
echo " ";
echo "Student $foo does not exist!!";
}
}
}
else echo "Invalid Command";
?>
Am having duplicating result e.g Student 1124 does not exist!! 10times. I've modify the code to:
while($row = mysql_fetch_array($result))
{
$id= $row['sid'];
if($id==$foo)
{
$res = mysql_query($query);
}
else
{
echo " ";
echo "Student $foo does not exist!!";
}
}
if ($res)
{
echo 'Insertion ok';
}
else
{
echo " ";
echo "Attendance already taken for $foo";
}
So i've placed the $res outside the loop to avoid duplication result but now it says: variable cannot be resolved Any suggestions?
A bit of changed version of CaldasGSM:
<?php
if (!empty($_GET['q']))
{
include('config.inc');
$foo = mysql_real_escape_string($_GET['q']);
$result = mysql_query("SELECT * FROM user_student WHERE sid = '{$foo}'");
$num_rows = mysql_num_rows($result);
if($num_rows > 0)
{
$res = mysql_query("INSERT INTO register(name) VALUES('$foo')");
if ($res)
{
echo 'Insertion ok';
}
else
{
echo " ";
echo "Attendance already taken for $foo";
}
}
else
{
echo " ";
echo "Student $foo does not exist!!";
}
}
else
{
echo "Invalid Command";
}
?>
maybe something like
<?php
if ($_GET['q'] !='')
{
include('config.inc');
$foo = $_GET['q'];
$result = mysql_query("SELECT * FROM user_student");
$bRecordExists = false;
while($row = mysql_fetch_array($result))
{
$id= $row['sid'];
if($id==$foo)
{
$bRecordExists = true;
break;
}
}
if($bRecordExists)
{
$res = mysql_query("INSERT INTO register(name) VALUES('$foo')");
if ($res)
{
echo 'Insertion ok';
}
else
{
echo " ";
echo "Attendance already taken for $foo";
}
}
else
{
echo " ";
echo "Student $foo does not exist!!";
}
}
else
{
echo "Invalid Command";
}
?>
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 Have a PHP file doing a query
function getFiles()
{
$solnid = $_GET[id];
$query = mysql_query("SELECT * FROM library WHERE libr_solutionId = '$solnid' AND libr_deleted IS NULL") or die(mysql_error());
$result = mysql_query($query);
if (mysql_num_rows($result)==0) {
echo "<br>No Related Links";
} else {
while($library = mysql_fetch_assoc($query)) {
echo "<span style=\"margin-bottom: 5px;\"><img src=\"images/icon-download-02.png\" align=\"absmiddle\" style=\"margin-right: 5px;\"><span>".$library[libr_c_title]."</span></span><br>";
echo "<br>";
}
}
}
I have tested the query in PHPMyAdmin and I get a result however when running the function in my page it only displays the 'No Related Links' statement any ideas anyone?
Here's the fixed code. :) The problem was that you used mysql_query on a Resource (the first mysql_query), and that will give 0 rows, or an exception..
function getFiles()
{
$solnid = $_GET['id'];
$result = mysql_query("SELECT * FROM library WHERE libr_solutionId = '$solnid' AND libr_deleted IS NULL") or die(mysql_error());
if (mysql_num_rows($result)==0) {
echo "<br>No Related Links";
} else {
while($library = mysql_fetch_assoc($result)) {
echo "<span style=\"margin-bottom: 5px;\"><img src=\"images/icon-download-02.png\" align=\"absmiddle\" style=\"margin-right: 5px;\"><span>".$library['libr_c_title']."</span></span><br>";
echo "<br>";
}
}
}
change your function to (change to lines)
function getFiles()
{
$solnid = $_GET[id];
$result = mysql_query("SELECT * FROM library WHERE libr_solutionId = '$solnid' AND libr_deleted IS NULL") or die(mysql_error());
if (mysql_num_rows($result)==0) {
echo "<br>No Related Links";
} else {
while($library = mysql_fetch_assoc($query)) {
echo "<span style=\"margin-bottom: 5px;\"><img src=\"images/icon-download-02.png\" align=\"absmiddle\" style=\"margin-right: 5px;\"><span>".$library[libr_c_title]."</span></span><br>";
echo "<br>";
}
}
}