broj1 356 Humble servant Featured Poster

Looking at your last version of the checklogin.php page you redirect administrator to main.php and user with no access (case: default) to the main.php page. Can you please clearly state what are names for the administrator page, encoder page and login page.

broj1 356 Humble servant Featured Poster

Onre of the things pixelsoul did in his post above is he separated html and php code to get more clarity. I also highly recommend this approach. If you mix html and php too much it is harder to spot the errors in the code.

Now, no matter which approach you take, if things still do not work please post a few rows of questions and answers tables, preferably as an SQL insert file. You can do this from phpmyadmin by selecting a table, chosing a Export menu and exporting with default options.

broj1 356 Humble servant Featured Poster

In checklogin.php on line 42 you assign a sesion variable the value read from the database:

$_SESSION['userlevel'] = $row['user_level'];

In main.php on line 8 you check for existence and value of session variable:

if(!isset($_SESSION['user_level']) || $_SESSION['user_level'] != 'administrator') {

The trouble is the indexes of the session variable are different. Once you use userlevel and another time you use user_level so the condition is true and you get redirected to the login page. The error might also originate from my examples since I do not know all the code. I strongly suggest that you use the same indexes for $row arrays, $_SESSION, $_POST and $_GET variables, and they should be same as the database column name. Otherwise you will get confused and errors like this will happen. The following is just an example:

Column name in the DB table: user_level
$row value for this column: $row['user_level']
a temporary variable: $user_level
$_SESSION variable: $_SESSION['user_level']
$_POST / $_GET variables: $_POST['user_level'] / $_GET['user_level']

As you see above you allways know that you are referring to user_level. Please correct the code as per above suggestion and test it. If it does not work, please post the code (the latest version). Sory to get you to post your code that many times, but it is the only way to go.

broj1 356 Humble servant Featured Poster

OK, I think I know the cause of the problem. The mysql_fetch_array returns array of arrays so each $q_id is an array, too. I think it should work if you change the line 32 like this:

$query_q = "SELECT q_qstn_no, q_text FROM question WHERE q_id='{$q_id[0]}'";

Let me know if this works.

broj1 356 Humble servant Featured Poster

Sory to be quiet such a long time, I was away.

$q_id_arr gives me the word 'Array'. Is that supposed to happen?

No that is not OK. Put this temporary debug code on line 27:

die(print_r($q_id_arr, 1));

This will display the content of the $q_id_arr array (array of all question IDs) and stop the script. Please post the output.

broj1 356 Humble servant Featured Poster

I tried the code but it seems that the case statement doesnt work, still no success on the program

Can you describe what does not work.

by the way what you mean php script not html page?do you mean that eventhough it's a html code but I will save it as .php?

Yes. And each page will have some code in it. At least the piece of code from my last post above to check the existence of session variables and user access level. Without this code nothing will work.

// start the session
session_start();

// on each page first do the checks if login is OK nad user has access rights
// (you can add other conditions here if needed)
// if login not OK ot user hasn't got access rights, redirect to the logout script
// this is an example for the administrator
if(!isset($_SESSION['user_level']) || $_SESSION['user_level'] != 'administrator') {

    // redirect to the page that unsets the session and redirects to login page
    header('location:logout.php');
}

// now carry on with the code for logged in user
...
broj1 356 Humble servant Featured Poster

but I used a while loop (line 29) fetching from table 'question'.

Sorry, I overlooked this. I see the problem. Your code is probably OK, only remove the code on line 57:

$id++;

You do not have to increment the question id since it is being read form the question table.

broj1 356 Humble servant Featured Poster

Where do you get the list of questions to be displayed? In any case it is probably an array of question ID's which you have to iterate through.

// array of question IDs to be displayed
// I just made them up for this example
$q_id_arr = array(1,2,3,4,5);

// loop through the array of question IDs
foreach($q_id_arr as $q_id) {

    // select the question
    $query_q = "SELECT q_qstn_no, q_text FROM question WHERE q_id='$q_id'";

    // read the question and display it
    ...

    // select the possible answers
    $query_a = "SELECT a_id, a_text, a_value FROM answer WHERE answer.q_id='$q_id'";

    // read and display the possible answers and radio buttons etc
    ...

}

And change the query for inserting answers so you do not insert into autoincremented field (once you have many records you wont be able to assure unique values yourself):

INSERT INTO `answer` (``q_id`, `a_text`, `a_value`) VALUES
(1, 'Data', 1),
(1, 'System data', 0),
...
atikah8890 commented: :) +1
broj1 356 Humble servant Featured Poster

Also writing to CSV is simple using the fputcsv function.

broj1 356 Humble servant Featured Poster

If you could change the format to CSV it would be much more manageable. You could then use the fgetcsv function which reads a line directly into an array without you doing any coding.

broj1 356 Humble servant Featured Poster

It is not the most elegant solution but here you go. I am not sure if the table is formatted correctly.

// explode by <br /> and remove <br /> at the beginning and end
$VisitorsArray = explode('<br />', trim($string, '<br />'));
$VisitorsArrayLength = count($VisitorsArray);
$Count = 1;

for($i = 0; $i < $VisitorsArrayLength; $i += 2) {

    echo "<tr>";
    echo "<td><strong>" . $Count++ . "</strong></td>";
    echo "<td><strong>Name</strong>: " . stripslashes($VisitorsArray[$i]) . "<br />";
    echo "<strong>Email</strong>: " . stripslashes($VisitorsArray[$i+1]) . "</td>";
    echo '</tr>';
}
broj1 356 Humble servant Featured Poster

The problem is that the format of the file and the code to convert it into an array do not match. What would you prefer: either change the format of the file to match the code or cgange the code to match the file structure?

broj1 356 Humble servant Featured Poster

I think the problem is in the text file. Can you post a few lines of it?

broj1 356 Humble servant Featured Poster

On line 8 you should probaly have a space before WHERE

$query_update .= " WHERE `item_id`=".$_POST["item_id"];

and the comma on line 7 should not be there (before the WHERE):

$query_update .= "`item_avai`='".$_POST["item.avai"]."'";

The easiest way to check is to insert a debug code between lines 8 and 9:

die($query_update);

which will display the query and stop the script. You can copy the query into phpmyadmin and test it there.

broj1 356 Humble servant Featured Poster

Also there are tags missing like <form>, closing </td> and </tr> and <table> </table> pair. But main error is as pixelsoul pointed the missing curly bracket.

broj1 356 Humble servant Featured Poster

phpacademy if you prefer watching videos.

You will also find tutorial for mysql there. PHP comes to it's power if you dynamicaly use data from a database (and mysql is most often used).

broj1 356 Humble servant Featured Poster

This is my version of the login script which is simplified, removing duplicate checks and queries and still does the same. See the comments in the code.

<?php
//start session on the beginning of the script
session_start();

$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="mysys"; // Database name
$tbl_name="tblusers"; // Table name
$encoder = "encoder";
$administrator = "administrator";
session_start();
//include 'functions.php';
//sec_session_start(); // Our custom secure way of starting a php session. 

$today = date('Y-m-d');

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$now = date('Y-m-d');

$expDate = strtotime(date("Y-m-d", strtotime($info['dateReg'])) . " + 30 days");

// read all the data about the user in one query
$sql="SELECT  * FROM $tbl_name WHERE user_id='$myusername' AND user_password='$mypassword' AND dateExp > '$now' ";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

// if result matched $myusername and $mypassword, table row must be 1 row
// this is when user was found
if($count == 1) {

    // assign all the data to the session variables
    // session variables that differ for each user level can be set
    // within the switch statement below
    $_SESSION['ip'] = UserIP();
    $_SESSION['userid'] = $row['user_id'];
    $_SESSION['fullname'] = $row['user_fname']." ".$row['user_lname'];
    $_SESSION['userlevel'] = $row['user_level'];
    $_SESSION['lastaccess'] = date("Y-m-d h:i:s A");

    // determine the user level
    $user_level = $row['user_level'];

    // redirect …
broj1 356 Humble servant Featured Poster

The checklogin.php is the page where you set up the session if login is successful. There are some issues on that page:

Do not use session_register function since it is already deprecated. See warning on http://php.net/manual/en/function.session-register.php: This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

Use assignments to $_SESSION array as already in your code but commented out:

$_SESSION['ip'] = UserIP();
$_SESSION['userid'] = $row['user_id'];
$_SESSION['fullname'] = $row['user_fname']." ".$row['user_lname'];
$_SESSION['userlevel'] = $row['user_level'];
$_SESSION['lastaccess'] = date("Y-m-d h:i:s A");

In the code you have some nested if and elseif conditions which has the following structure:

if($count == 1) {
    if($count2==1) {
    } else if($count == 1) {
        if($count==1) {
        } else {
        }
    }
} else {
    if($count == 0) {
    } else {
    }
}

Within the first block you check if $count == 1 three times which is unnecessary (you should do it only at top level). Please check if this is what you meant or is that an error.

This is enough for this post I will send you another one when I finish testing. Meanwhile please look at the code considering above notes.

broj1 356 Humble servant Featured Poster

Please post also the checklogin.php code which is where you are supposed to check credentials and set up the session and phpconfig.php (and remove any sensitive data from it!!).

broj1 356 Humble servant Featured Poster

Post the latest version of the code you have.

broj1 356 Humble servant Featured Poster

I would presume that the query:

$query_recTenantuser = "SELECT * FROM md_storage WHERE tenantID='".$tenantID."'"; 

will return just one row ($tenantID is probably unique), so in the select element (drop down) you will have only one option. That does not make senese. Correct me if I am wrong.

broj1 356 Humble servant Featured Poster

When user clicks on logout link it takes him to the logout script that has the code that Webville312 suggested in his post. The script does not do anything visual. It just destroys the session and redirects to the index page. We are assuming here that you keep the login information in the session. For really secure logout I would add a couple of statements, which just show what a vigilant person I am:

<?php

session_start(); // First initialize the current session

$_SESSION = array(); // initializes the session array to an empty array

unset($_SESSION); // unset the session array

session_destroy(); // Then destroy the session  

header('Location: index.php'); // redirect the user to the index page 

exit(); // terminate the script

?>
broj1 356 Humble servant Featured Poster

And an excellent resource for web apps security is OWASP and their Top 10 cheat sheet. Go through their list.

cereal commented: good suggestion! ;) +10
broj1 356 Humble servant Featured Poster

You are welcome. Please mark as solved if there are no questions. Happy coding.

broj1 356 Humble servant Featured Poster

Here is corrected / rearranged code. Please see the comments within the code.

<?php 
// !!!!!!!!!
// this is my stuff to connect to the DB
// please use your DB connection code here
include '../common/connect.php';
$link = dbConnect();

// variables for filling-in the form fields
$policyNum = '';
$surname = '';
$name = '';

// changed the $_REQUEST to $_POST to avoid possible clashes if you decided to
// also use $_GET in future
// OK; lest's check if the user clicked on submit button
// please note name and ID of the button were changed to 'submit' to avoid confusion
if(isset($_POST['submit'])) {

    // initialize variables that represent conditions
    $search_policy = '';
    $search_surname = '';
    $search_name = '';    

    // isset function is also used in checking for the existence of data in $_POST
    if (isset($_POST["policyNum"]) && $_POST["policyNum"] != '') {
        $policyNum = mysql_real_escape_string($_POST["policyNum"]);
        $search_policy = " AND (policyNumber LIKE '%$policyNum%')";
    }

    if (isset($_POST["surname"]) && $_POST["surname"] != '') {
        $surname = mysql_real_escape_string($_POST["surname"]);
        $search_surname = " AND (lastName LIKE '$surname')";
    }

    if (isset($_POST["name"]) && $_POST["name"] != '') {
        $name = mysql_real_escape_string($_POST["name"]);
        $search_name = " AND (firstName LIKE '%$name%')";
    }

    $sql = "SELECT * FROM tblclients WHERE clientID > 0".$search_policy.$search_surname.$search_name;   

    $sql_result = mysql_query($sql) or die (mysql_error());

    // now echo the code for the table heading
    // echo table head
    echo '<table width="700" border="1" cellspacing="0" cellpadding="4">';
    echo '<tr><td width="90" bgcolor="#CCCCCC"><strong>Policy No.</strong></td>';
    echo '<td width="95" bgcolor="#CCCCCC"><strong>Name</strong></td>';
    echo '<td width="159" bgcolor="#CCCCCC"><strong>Surname</strong></td></tr>';

    // if there are any rows, echo each of them
    if (mysql_num_rows($sql_result)>0) {

        while …
broj1 356 Humble servant Featured Poster

Now another small issue is that i do not want the table to show by default & i want it to show only after i enter values in textboxes and press the search button

You can achieve that by placing the whole php block on the beginning and wrapping it in aanother if condition checking for whether the button has been pressed. Within that block you construct the table.

I will try to prepare a code and show it in next post so you can experiment on your own in the mean time.

broj1 356 Humble servant Featured Poster

Another way of doing it:

Frst initialize the variables to empty string:

$search_policy = '';
$search_surname = '';
$search_name = '';

Then you assign a condition to any of the variables if $_POST element exists, as you have done it.

On lines 43 to 45 chremove the else bit from:

else {
    $sql = "SELECT * FROM tblclients WHERE clientID > 0".$search_policy.$search_surname.$search_name;
}

to:

$sql = "SELECT * FROM tblclients WHERE clientID > 0".$search_policy.$search_surname.$search_name;

That is how the conditions or empty strings will be added to the query.

@ahmedhamdy: your solution will work only if all three boxes have been filled-in and I am not sure if ngonix wants that.

broj1 356 Humble servant Featured Poster

Also a database offers better security of the data.

broj1 356 Humble servant Featured Poster

You can save values in a txt file, JSON format would be a good one. You can use json_encode and json_decode functions. Instead of JSON you can just serialize data into a txt file.

broj1 356 Humble servant Featured Poster

You are welcome. Please mark this thread as solved. If you have more questions open a new thread. Happy coding.

broj1 356 Humble servant Featured Poster

I have a question though, what did you mean about the categories code?

Just an idea. One possibility would be that a user wants to see all categories, so chosing a category would be only an option. The default would be that no category is chosen. But it is your preference if category is required.

Also, should I stop using echo ERROR and just do die from now on and why?

In your original code you would never see the error message displayed since immediatelly after echoing it you would be redirected to index page. If you use die, redirection does not happen. I would do it differently. If an error occurs (which I guess is not often) I would redirect to a special error page with simple explanation and links to other pages.

broj1 356 Humble servant Featured Poster

Line 47:

$stmt->bind_param("ssi", $category, $title, $director, $year, $id);

You have declared only three types but you have five parameters. Try:

$stmt->bind_param("sssii", $category, $title, $director, $year, $id);

And change the line 54 to

die("ERROR: could not prepare SQL statement.");

so the script is stopped if error occurs (now you immediately get redirected to index).

broj1 356 Humble servant Featured Poster

Double quote is missing after the value attribute. Have you copied the code form my post correctly? It works in my browser, I have tested it.

broj1 356 Humble servant Featured Poster

Something is wrong in HTML. If you check the HTML code for the radio buttons. Can you have a look at the HTML code (right click in web browser and select View source or something similar) and post the code for radio buttons.

broj1 356 Humble servant Featured Poster

Let's see what gets POSTed over. Can you insert this code immediatelly after line 24 and post the result after submitting the form:

die(print_r($_POST, 1));

This will display values in $_POST and terminate the script.

broj1 356 Humble servant Featured Poster

Have you tried the code form my first post (the one immediately after your post)?

broj1 356 Humble servant Featured Poster

Is category a required information? If category has not been chosen (user wants to se all categories) you have to provide for that situation:

if(isset($_POST['category'])) {

    $category   = $_POST['category'];

} else {

    $category = 'All';
}

// handle the all categories situation
...
broj1 356 Humble servant Featured Poster

Shouldn't you read the ID from URL ($_GET)?

$id         = $_POST['id'];

on line 26, should be

$id         = $_GET['id'];
broj1 356 Humble servant Featured Poster

You can create radio buttons with PHP. Put categories in an array, cycle through it, add code for radio buttons and check if current category matches the one from the DB:

<?php
// array of categories (you can always edit it and the radio buttons will change)
$categoriesArr = array('Action', 'Comedy', 'Drama', 'Horror', 'Thriller');

// add radio buttons via php and add checked attribute for the selected categpry
foreach($categoriesArr as $cat) {

    echo '<input type="radio" name="category" value="' . $cat  . '"';

    if($cat == $category) {

        echo ' checked="checked"';
    }

    echo ' />' . $cat;
}
?>

The code above should replace the code on lines 112 to 116.

broj1 356 Humble servant Featured Poster

There is another issue with your code. If a user enters spaces or ampersands or < or > or similar unwanted characters in the input box you should not pass that to the URL unencoded so use at least encodeURIComponent function before sending data to ajax.

$.ajax({

    type: "POST",
    url: "edit.php",
    data: encodeURIComponent(dataString),
    success: function(){
    $('.success').fadeIn(200).show();
    $('.error').fadeOut(200).hide();
    }
}); 

On the PHP side decode it back (i.e. using urldecode) and escape it properly to avoid attacks to your database or browser.

OsaMasw commented: thanks +2
broj1 356 Humble servant Featured Poster

There are other small errors in the code as well so this is now the correct code (slightly reformated):

<script type="text/javascript">
$(function() {

    $(".editname").click(function() {

        var recordId = $(this).attr('id');
        var name = $('#tx_id-' + recordId).val();

        // tried to put # and nothing works
        var dataString = 'name='+ name + '&id=' + recordId ;

        if(name=='' || recordId=='' ) {

            $('.success').fadeOut(200).hide();
            $('.error').fadeOut(200).show();

        } else {

            $.ajax({

                type: "POST",
                url: "edit.php",
                data: dataString,
                success: function(){

                    $('.success').fadeIn(200).show();
                    $('.error').fadeOut(200).hide();
                }
            });    
        }

        return false;
    });    
});
</script>

The errors were in brackets, and the ID of input was misspelled (txt_id instead of tx_id).

OsaMasw commented: working as charm +0
broj1 356 Humble servant Featured Poster

My mistake - a typo in the jquery code. Change line 11 from:

var recordId = $(this.attr('id'));

to:

var recordId = $(this).attr('id');

Note the change in brackets :-).

broj1 356 Humble servant Featured Poster

Just a note on quoting strings. It has nothing to do with the error you are getting, just a suggestion. Instead of:

echo "As \"" . $row["alias"] . "\"||";

you can do either:

echo "As \"{$row["alias"]}\"||";

or

echo 'As "' . $row["alias"] . '"||';

It is slightly more readable and easier to debug. But it is your choice what you prefer.

broj1 356 Humble servant Featured Poster

On line 5 you are assigning the same value to $result over and over again.

$result = mysql_query("SELECT * FROM tag WHERE point='$pagename'");

so while($row = mysql_fetch_array($result)) condition is always true (it is always first row of the table). I would remove line 5.

The $result on line 9n is also causing trouble. What is the goal here? Maybe you post the database structure.

IIM commented: Nice pin point +5
broj1 356 Humble servant Featured Poster

You could use lenght property to check for the second element:

if(nameAndLastnameArray.length > 1) {
    // insert name into appropriate box
    document.getElementById("displayDiv1").value=nameAndLastnameArray[0];
    // insert lastame into appropriate box
    document.getElementById("displayDiv2").value=nameAndLastnameArray[1];
} else {
    // insert empty string into boxes
    document.getElementById("displayDiv1").value='';
    document.getElementById("displayDiv2").value='';
}

But I do not know whether this is the way you want to do it.

broj1 356 Humble servant Featured Poster

I guess because the nameAndLastnameArray[1] does not exist (is undefined) when removing. Can you describe what is the purpose of the page and the form.

broj1 356 Humble servant Featured Poster

You are returning only the name in a message not alsoo the lastname. Add lastname also and separate the name and lastname so you can distinguish them when returned from ajax cal, maybe with comma:

    ...
    while($nt=mysql_fetch_array($t)) { error_reporting(0);
        $msg.= $nt[name] . ',' . $nt[lastname];
    }
}
echo $msg;

On html page insert the name and lastname:

// split the returned string into array of name and lastname
nameAndLastnameArray = value=httpxml.responseText.split(',');

// insert name into appropriate box
document.getElementById("displayDiv1").value=nameAndLastnameArray[0];

// insert lastame into appropriate box
document.getElementById("displayDiv2").value=nameAndLastnameArray[1];
broj1 356 Humble servant Featured Poster

Are you sure the second and third SELECT keywords have to be there. Would this be OK:

$bquery="SELECT * FROM rt_booking WHERE rt_unit_id='".$_POST['unit_id']."' 
AND (UNIX_TIMESTAMP(str_to_date(rt_start_date,'%Y-%m-%d'))>=".$my11." 
OR UNIX_TIMESTAMP(str_to_date(rt_end_date,'%Y-%m-%d'))<=".$my22.")";
broj1 356 Humble servant Featured Poster

Put this temporary debug code on line 3:

die("UPDATE $title SET arole = CONCAT_WS(',', arole, '$name') WHERE op = '$name'";);

Your query will get displayed with actual values. Copy it to the SQL window of phpmyadmin and see what you get when you run it. If there are errors you will get error messages there that will help you solving the problem.

broj1 356 Humble servant Featured Poster

I quickly put together this recursion function.

function assoc2indexedMulti($arr) {

    // initialize destination indexed array
    $indArr = array();

    // loop through source
    foreach($arr as $val) {

        // if the element is array call the recursion
        if(is_array($val)) {

            $indArr[] = assoc2indexedMulti($val);

        // else add the value to destination array
        } else {

            $indArr[] = $val;
        }
    }

    return $indArr;
}

Tested it on a small array, I hope it works OK on your array. If the array is large it might be an issue since it doubles the memory requirement.