broj1 356 Humble servant Featured Poster

Yes, but how do you determine the value of invst_id_ar and what is the range?

broj1 356 Humble servant Featured Poster

OK, but what is the logic behind it?

broj1 356 Humble servant Featured Poster

First start the table and add a header row:

<table >
<tr><th>Product ID</th><th>Items</th><th>Price</th><th>Date</th><th>Action</th></tr>

Then add the rows with data:

<?php
while($row = mysql_fetch_array($sql)){

    $id = $row["id"];
    $product_name = $row["name"];
    $details = $row["details"];
    $size = $row["size"];
    $price = $row["price"];
    $quantity = $row["quantity"];
    $date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));

    echo "<tr>";
    echo "<td>$id</td>";
    echo "<td>$product_name</td>";
    echo "<td>$price</td>";
    echo "<td>$date_added</td>";
    echo "<td><a href='inventory_edit.php?pid=$id'>edit</a> • ";
    echo "<a href='inventory_list.php?deleteid=$id'>delete</a></td>";
    echo "</tr>";
}
?>

</table>
broj1 356 Humble servant Featured Poster

OK, so you have repeating four inputs (one hidden) and they actually create arrays in $_POST elements, right? in $_POST array you get three elements which are also arrays and those arrays should have same number of elements. Now, to construct a query you should use common iterator for all four arrays, something like:

// count the elements in one of the arrays (ideally the count should be equal for all three arrays)
$count = elementCount($_POST['text1'])

// construct the first part of the query
$query = "INSERT INTO election (invst_id_ar , nomine_id, vote_gain, vote_gain_p, casted_d_t) VALUES ";

// now loop through all the arrays and add values to the query
for($i = ; $i < $count; $i++) {

    // first escape the values (you can do other checks here)
    $nd = mysqli_real_escape_string($_POST['nd'][$i]);
    $Votes = mysqli_real_escape_string($_POST['text'][$i]);
    $Votes_p = mysqli_real_escape_string($_POST['text1'][$i]);
    $id = mysqli_real_escape_string($_POST['invst_id'][$i]);

    // add to the query
    $query .= "('$id', '$nomineeid', '$voted', '$p_vote', NOW())";

    // if it is not the last element add comma at the end of value set
    if($i < $count - 1) {

        $query .= ',';
    }
}

The code is not tested but I hope you get the principle.

broj1 356 Humble servant Featured Poster

OK the processing code looks right but what is supposed to be the contents of the POST variables (what data are you asking a user to fill in)?

$cLists = $_POST['nd'];
$Votes = $_POST['text'];
$Votes_p = $_POST['text1'];
$id = $_POST['invst_id'];
broj1 356 Humble servant Featured Poster

What is supposed to be in these variables (I guess the output of the form)?

$cLists = $_POST['nd'];
$Votes = $_POST['text'];
$Votes_p = $_POST['text1'];
$id = $_POST['invst_id'];
broj1 356 Humble servant Featured Poster

You are actually not using the array_combine function correctly. This function's parameters are expected to be arrays but you are feeding it strings. What is the purpose of it?

broj1 356 Humble servant Featured Poster

I think the $nomineeid => $voted, $p_vote part in line 10 is not valid syntax.

foreach (array_combine($cLists, $Votes, $Votes_p) as $nomineeid => $voted, $p_vote){

The foreach construct is defined as

foreach (array_expression as $key => $value)

so in your case PHP expects a ) instead of a , after $voted. What do you actually want to achieve?

broj1 356 Humble servant Featured Poster

You are welcome. Please mark as solved. Happy coding.

broj1 356 Humble servant Featured Poster

Escape the values in the query using your databases's escape function. If you use mysqli the function is mysqli_real_escape_string (or mysqli::real_escape_string if you do it OOP way).

$query = "UPDATE room SET floor='" . mysql_real_escape_string($room->floor) . "' where id=room->id";
broj1 356 Humble servant Featured Poster

No. In my previous post I have put a debug code in each case statement. This way I can check which case statement gets executed. So please šut this same code in your script and check whether the switch is redirecting to appropriate pages. If yes we have to look for errors on redirected pages. If no, we have to see where the error occured before redirection.

broj1 356 Humble servant Featured Poster

This is interesting, thanx for sharing. But what were the requirements for this kind of script? Is this a part of a production application? And did you have to implement any security (so the whole world does not start sending thousands of pages to your printer)?

broj1 356 Humble servant Featured Poster

Looking at source of your page two errors show up in Firefox on Ubuntu:

  • the comment line <!----Car Image --> is not structured correctly (my FF says -- is not permitted withim a comment)
  • it also doesn't like the line <div class="ui-widget">. It is probably not allowed there considering the doctype you have (XHTML 1.0)

These are just guesses since I can not test it, due to not having a Mac at hand :-)

broj1 356 Humble servant Featured Poster

Before posting the pages I asked you in my post above try the corrected code. The difference is ony in that the code is wrapped withing jquery ready() method (and of course IIM's correction has been applied).

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
         // URL to open
        var myUrl = '';
        // set URL depending on screen size (800 here is just an example)
        if (screen.width <= 800) {
            myUrl = 'mySmallResolutionPage.php';
        } else {
            myUrl = 'myBigResolutionPage.php';
        }
        // load appropriate script into contentsDiv div
        $('#contentsDiv').load(myUrl);
    });
</script>

<!-- generated contents will get loaded here -->
<div id="contentsDiv"></div>

Please note that the php scripts have to return only the body of html, the index.php shall contain the <html></html>, <head></head> and <body></body> tags and appropriate stuff.

broj1 356 Humble servant Featured Poster

Can you post the latest code for index, mySmallResolutionPage and myBigResolutionPage pages please.

broj1 356 Humble servant Featured Poster

Ok, so is the problem solved now?

Another recommendation: try to mix php and html as little as possible. The code will be far more manageable. Happy coding.

broj1 356 Humble servant Featured Poster

The mysql_query function returns a resource not a row. The resource is a special php type that can be used to retrieve rows. You can use the mysql_fetch_row() function to fetch rows

while ($row = mysql_fetch_assoc($cat_name)) {
    echo $row['cat_title'];
}

Please note that $cat_name is a misleading name for a variable holding the resource result. $result would be more appropriate.

And another note which is being repeated quite often these days: try to switch to newer and safer mysqli extension and drop the old mysql which is deprecated as of PHP 5.5.0.

broj1 356 Humble servant Featured Poster

Itmeans that there is no value for the $Y variable which is basicaly the $_POST["Y"] variable. In other words posted data does not exist and the query inserts empty string (which is probably what you do not want). Where is it supposed to come form?

Good practice is to check for for submittion or existence first:

<?php
include "dbConfig.php";
if(isset($_POST["Y"])) {
    // you can escape here
    $Y=mysql_rel_escape_string($_POST["Y"]);
    // use escaped value
    $query="INSERT into tbl_subjectsenrolled (SubjectID) values ('$Y')";
    mysql_query($query) or die (mysql_error());
}
?>
pixelsoul commented: nice one +5
broj1 356 Humble servant Featured Poster

You need to use client side (which is most often javascript) to detect screen size. Have a look at this link:

http://www.javascriptkit.com/howto/newtech3.shtml

How to utilize that with php? Maybe using Ajax, something like this (I use jquery load here):

<script type="text/javascript">
    // URL to open
    var myUrl = '';
    // set URL depending on screen size
    if (screen.width <= 800) {
        url = 'mySmallResolutionPage.php';
    } else {
        url = 'myBigResolutionPage.php';
    }
    // load appropriate script into contentsDiv div
    $('#contentsDiv').load(myUrl);
</script>

<!-- generated contents will get loaded here -->
<div id="contentsDiv"></div>
broj1 356 Humble servant Featured Poster

And, oops, the mysql_real_escape_string function name is misspelled.

broj1 356 Humble servant Featured Poster

Insert a temporary debug code. It is simple but it often helps. Test the displayed query in phpmyadmin or post it here.

<?php
include "dbConfig.php";
$Y=$_POST["Y"];
$query="INSERT into tbl_subjectsenrolled (SubjectID) values ('".mysql_rel_escape_string($Y)."')";

// Temp DEBUG code
die($query);

mysql_query($query) or die (mysql_error());
?>
broj1 356 Humble servant Featured Poster

As IIM said change $_POST to $_GET at least for reading the ID (depending on the source of the data).

There is other thing I would like to point out. You are assigning your ID to the $id variable but:
1. you are not using that variable later on and
2. you are not cleaning and escaping the input. You open your database to attackers.

$id = isset($_POST['id']) ? $_POST['id'] : '';  

It is really recommended to validate, clean (or reject) and escape input, no matter wheter GET or POST.

$id = isset($_POST['id']) ? mysql_real_escape_string($_POST['id']) : '';
$confirmation = isset($_POST['confirmation']) ? mysql_real_escape_string($_POST['confirmation']) : '';
$kategori = isset($_POST['kategori']) ? mysql_real_escape_string($_POST['kategori']) : '';
...

// Use only cleaned and escaped variables from now on
broj1 356 Humble servant Featured Poster

the request seems like GET as it is appended in URL

@iim: Ups, you are right. I don't know what I was looking at.

broj1 356 Humble servant Featured Poster

On line 15 more appropriate check would be:

if (isset($_POST['id']) && is_int($_POST['id'])){

so you are checking whether $_POST['id'] exists at al and is integer.

broj1 356 Humble servant Featured Poster

It is hard to figure out from your post what exactly is the problem but looking at your query on line 6 this certainly won't work:

if ($ser<4) $sql .= " AND pulse_channel=$serv[] ";

You can't use $serv[] a query (which is basicaly a string). You will either have to decide which element to use or run foreach loop and use each value from the array depending of the logic you want to implement.

broj1 356 Humble servant Featured Poster

You should pass your getLink function connection parameters since it can not access variables out of it's scope:

 function getLink($serverName,,$userName,$userPassword,$nameOfDataBase){
    $link=@mysqli_connect($serverName,$userName,$userPassword,$nameOfDataBase);
    if(!$link){
        echo "connection Error".mysqli_connect_errno();
    }
    return $link;
}
broj1 356 Humble servant Featured Poster

You can store the value in a hidden input field in the form which will then be picked up when form is submitted.

<input type="hidden" id="hidden-date" />

And in the javascript I guess you change line 21 to:

document.getElementById('hidden-date').value = document.getElementById('time').innerHTML;
broj1 356 Humble servant Featured Poster

I actually wanted to ask if it's better to use echo followed by HTML table structure etc. That is separating HTML and PHP code, right?

Yes. Separating enables you to keep blocks of php code together, e.g the loops. If you have to produce html code within blocks then you echo them (such as table rows). I am glad that your code works now.

broj1 356 Humble servant Featured Poster

OK, we will have to do this in steps. First change the default redirection to logout.php. Then add some debug code in switch statement and login as administrator, encoder and nonexisting user. Please post the output for each login attempt.

switch($user_level) {

    case $administrator:

        // DEBUG
        die('REDIRECTING TO main.php');

        // redirect to the administrator page      
        header("location:main.php");
        exit();
        break;

    case $encoder:

        // DEBUG
        die('REDIRECTING TO mainEncoder.php');

        // redirect to the encoder page
        header("location:mainEncoder.php");
        exit();
        break;

    default:

        // DEBUG
        die('REDIRECTING TO logout.php');

        // if none of the allowed user levels are found
        // redirect to the page that unsets the session and redirects to logout page
        header('location:logout.php');
        exit();
        break;
}
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

I think it's got to do with the fact that Joomla is written following the MVC pattern. All the processing and database access is done somewhere behind (model / controller) and the result is displayed thorugh single index.php page (affected also by a template). On their site they say: Joomla! is always accessed through a single point of entry: index.php (see http://docs.joomla.org/Developing_a_Model-View-Controller_Component/1.5/Introduction).

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

You searched by: Business, Human. It does this regardless of whether the word is in the Key_Words field or not.

In the above code I made up two keywords for testing:

// you get users to supply keywords, probably using a form, I'll just make them up
// in this test case the user is searching by two keywords: Business and Human
$userKeywords = array('Business', 'Human');

You have to put the keywords from the search form into the userKeywords array.

I've already bought PHP + MYSQL for Dummies :)

OK, that is good for start. But later switch to advanced books. I used this one:

http://www.amazon.com/PHP-MySQL-Dynamic-Web-Sites/dp/032152599X

Also check out the phpacademy. A cool way to learn.

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

The checkbox, if checked, has a value in the $_POST array determined by a value attribute. If it hasn't been checked then it is not set in the $_POST at all. So you can code it like this:

<input type="checkbox" value="1" name="item_avai" />

and you check for it in the action page:

if(isset($_POST['item_avai']) && $_POST['item_avai'] == 1) {
    $item_avai = 1;
} else {
    $item_avai = 0;
}

$query_update .= "`item_avai`='" . $item_avai . "',";
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.