broj1 356 Humble servant Featured Poster

You have 5 rows of select element and checkboxes so you have to keep track of which row a user has selceted / checked. You can do this if you add row number to the name attributes. So for row No. 1 the attribute would be:

<select name="lang[1]">
<input name="speak[1]" type="checkbox" value="yes" />
...

The easiest way to keep the code manageable is to store languages into an array and then loop through this array and construct all the elements. here is my version of code:

// array of languages
$languages = array(1 => 'Hindi', 2 => 'English', 3 => 'Tamil', 4 => 'Telugu', 5 => 'Kannada');

// the form
// note the action has been set to # to test the output
// adapt this to your needs
echo '<form method="post" action="#">';

// table head
echo '<div align="center">
  <table width="434" border="0">
    <tr>
      <td>Languages Known</td>
      <td>Speak</td>
      <td>Read</td>
      <td>Write</td>
      <td>Delete</td>
      </tr>';

// table rows
for($i = 1; $i <= count($languages); $i++) {
    echo '<tr><td>';

    // select element
    echo '<select name="lang[' . $i . ']">';
    echo '<option value="0">- Select -</option>';
    foreach($languages as $key => $lang) {
        echo '<option value="' . $key . '">' . $lang . '</option>';
    }
    echo '</select></td>';

    // checkboxes
    echo '<td><input name="speak[' . $i . ']" type="checkbox" value="yes" /></td>';
    echo '<td><input name="read[' . $i . ']" type="checkbox" value="yes" /></td>';
    echo '<td><input name="write[' . $i . ']" type="checkbox" value="yes" /></td>';

    // delete button
    echo '<td><input type="button" name="button5" id="button5" value="Delete" onclick="delete(this)" /></td>';

    echo '</tr>';
}
echo '</table>';
// submit butoon …
broj1 356 Humble servant Featured Poster

OK, maybe I missunderstood your question. So, you want to display user data from the database (if the user is loged in) and user data shall be read from a databse (based on user_id stored in the session)? If this is true than you do not need ajax.

broj1 356 Humble servant Featured Poster

It is a lot of code here :-). Basically what you have to do is you have to read the data that is already in the database and check for it within the code to see which checkboxes you have to set. From the number of queries in the script I suspect there are many tables but it is not evident from the code. This is why it is hard to give you any examples of select statements.

Other notes:
- maybe you should try to reorganize your code (or approach) so you don't get code that is too hard to manage
- before inserting user supplied values into database you should validate/sanitize them otherwise you have a security issue here

I hope I got the question right :-)

broj1 356 Humble servant Featured Poster

This bit of code seems to be OK. Are you sure that this is the line that is causing the error? Sometimes an error can occur a number of lines before. Maybe you post more code.

broj1 356 Humble servant Featured Poster

It is called AJAX. Once the page is loaded it enables you to get some more data and display it in a chosen element in the page (a div for example). It uses an XMLHTTP or XHR Javascript object that all modern browsers support to make additional request.

It is a good idea to use Javascript libraries such as jquery ajax to use this functionality since the hardest parts (such as supporting a wide variety of browsers) has already been solved there.

broj1 356 Humble servant Featured Poster

Great. If you have troubles getting useful data out of the POST, let us know, we will help. Otherwise, if the problem has been solved please mark this thread as solved. Happy coding.

broj1 356 Humble servant Featured Poster

when i submit all the prices are added up , but it should only add the checked ones

This is because select sum(price) as totalamount from food selects from all the rows you have in the table. To get only the checked items you have to read them from the $_POST array after form is submitted. In order to have checkboxes registered in the $_POST array, you have to give them the name attribute. I suggest that each checkbox has the item's ID in the name so you will know which items were checked. Also you will want to take into account quantities to be able to get the total price. Something like:

// input for the quantity (fq + ID)
echo '<td width="2%" height="5"><input type="number" name="fq' . $row['food_id'] . '" value="1"></td>';
// checkbox for the food item (fi + ID)
echo '<td width="2%" height="5"><input type="checkbox" name="fi' . $row['food_id'] . '"></td>';

Now the $_POST array will contain all the checked items and their respecting quantities. With a bit of juggling you can get an array of the IDs of the items selected and construct a query:

$sql2 = "select sum(price) as totalamount from food WHERE food_id IN (" . implode(',', $itemsIDArray) . ')';

But as I said, you might want to take quantities into account.

broj1 356 Humble servant Featured Poster

On lines 26 and 27 you assign strings to $uname and $pword variables:

$uname = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_SPECIAL_CHARS);
$pword = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_SPECIAL_CHARS);

On lines 38 and 39 you assign values to the $_SESSION but now you treat the above strings as arrays:

$_SESSION['User'] = $uname['username'];
$_SESSION['Passw'] = $pword['password'];

To me logical code would be:

$_SESSION['User'] = $uname;
$_SESSION['Passw'] = $pword;

except if you had something else in mind?

broj1 356 Humble servant Featured Poster

What is the code in the welc.php?

Is $uname['username'] a username (usually just one word) or users real name (like first and last name)?

broj1 356 Humble servant Featured Poster

No worries, mate. If this is it, please mark it as solved.

broj1 356 Humble servant Featured Poster

aND WHY YOU jad used # on action what if we used <?php $PHP_SELF ?>

They both work since they both mean about the same thing. So it is fine if you use any of these two options.

Well need one more favor from you if you be so kinds engough and let me know where I was mistaken and how it worked

There were few issues:
- line 7: while($record6 = mysql_fetch_array($recordset6)) is not OK since you assign a row to a resultset.
- line 24 and below: you did not check if the form has been submitted, since only then you can do the reading of user data and displaying it. Before the form is submitted you basicaly display nothing about the user.
- line 44: the </form> closing tag should be somewhere on line 20
- the label tags should not enclose elements (at least I think so), but that should not stop the script to do its work anyway

Now you can style the form to look nicer :-)

broj1 356 Humble servant Featured Poster

An improvement: once you selected a value and the data gets displayed your select element is set to the last selected value.

while($row = mysql_fetch_array($recordset6)) {
    echo "<option value=", $row["uid"];
    if(isset($_POST['button']) && $row["uid"] == $_POST['select3']) {
        echo ' selected';
    }
    echo ">", $row["ulogin"], "</option>";
}
broj1 356 Humble servant Featured Poster

Yeah, I had a few errors (like int_val instead of intval function name) in the code, sorry. This should work:

<?php 
// check if form was submitted
if(isset($_POST['button'])) {
    // select user profile data
    // $uid is forced to the integer type to make sure no ugly data enters the database
    // you could also use mysql_real_escape_string() function
    // now read a record for a selected user ID and store values in variables
    $result3 = mysql_query("SELECT * FROM users WHERE uid='" . intval($_POST['select3']) . "'");
    $row3 = mysql_fetch_array($result3);
    $fname = $row3['fname'];
    $lname = $row3['lname'];
    $uaddress = $row3['uaddress'];
    $uphone = $row3["uphone"];
    $uemail = $row3["uemail"];
    $desig = $row3["udesignation"];
    $empstat = $row3["empstat"];
    $jdate = $row3["jdate"];
}
?>
<form method="post" action="#">
<label for="select3">Select User</label>
<select name="select3">
<?php
$recordset6 = mysql_query("SELECT uid, ulogin FROM users");

while($row = mysql_fetch_array($recordset6)) {
    echo "<option value=", $row["uid"], ">", $row["ulogin"], "</option>";
}
?>
</select><br>
<input type="submit" value="Show" name="button" class="button"><br>
</form>

<?php 
// here you display user data if exists
if(isset($_POST['button'])) {
    echo "$fname<br>$lname <br>$uaddress<br>$uphone <br>$uemail<br>$desig<br>$empstat<br>$jdate";
    // you can unset the post variable so you are back to initial state
    unset($_POST);
}
?>
broj1 356 Humble servant Featured Poster

You posted the database structure instead of data. But never mind I will make up the data and check the code.

broj1 356 Humble servant Featured Poster

Can you send me some data from the users table. In phpmyadmin run the following query:

SELECT * FROM users LIMIT 10

and paste result here so I can test with the real data.

The code I posted was not tested, more just to show the concept.

broj1 356 Humble servant Featured Poster

Failed to load resource: net::ERR_CACHE_MISS
this eror is coming up in the console

I doubt this has any connection with the script. See:
http://stackoverflow.com/questions/26408931/bizarre-error-in-chrome-developer-console-failed-to-load-resource-neterr-ca

broj1 356 Humble servant Featured Poster

Here you go. See the comments in the code. If anything is not clear, just ask.

<?php 
// check if form was submitted
if(isset($_POST['button'])) {
    // select user profile data
    // $uid is forced to the integer type to make sure no ugly data enters the database
    // you could also use mysql_real_escape_string() function
    // now read a record for a selected user ID and store values in variables
    $result3 = mysql_query("SELECT * FROM users WHERE uid='" . int_val($_POST['$uid']) . "'");
    $row3 = mysql_fetch_array($result3);
    $fname = $row3['fname'];
    $lname = $row3['lname'];
    $uaddress = $row3['uaddress'];
    $uphone = $row3["uphone"];
    $uemail = $row3["uemail"];
    $desig = $row3["udesignation"];
    $empstat = $row3["empstat"];
    $jdate = $row3["jdate"];
}
?>
<form method="post" action="#">
<label for="select3">Select User</label>
<select name="select3">
<?php
$recordset6 = mysql_query("SELECT uid, ulogin FROM users");
while($record6 = mysql_fetch_array($recordset6)) {
    echo"<option value=",$record6["uid"],">",$record6["ulogin"],"</option>";
}
?>
</select><br>
<input type="submit" value="Show" name="button" class="button" style="float:left;margin-left:25%;"><br>
</form>

<?php 
// here you display user data if exists
if(isset($_POST['button'])) {
    echo "$fname<br>$lname <br>$uaddress<br>$uphone <br>$uemail<br>$desig<br>$empstat<br>$jdate";
    // you can unset the post variable so you are back to initial state
    unset($_POST);
}
?>

It would be good idea to replace al mysql* functions with mysqli* functions. mysql extension is deprecated, it was replaced with mysqli. However, in future think of switching to PDO.

broj1 356 Humble servant Featured Poster

So if I understood it right, you want to select a user name and have profile of the selected user displayed on the same page. I did not quite understand though, whether you want a submit button or not (but that does not matter so much, since javascript can triger form submission instead of a submit button).

There are two approaches:

  1. The simple one - You select a user and the page reloads with the same form and with user data displayed
  2. The more advanced one - You select user and the page does not reload, only the element displaying user data gets updated using AJAX

It depends on the level of your familiarity with these things which one to chose. The second approach is used in modern web apps.

In the page you refer to as an example some other approach is used. All the values are being coded in the HTML page and Javascript selects the appropriate value of the second dropdown based on the value in the first dropdown. But with a database of users usualy this approach is not appropriate (especialy if you have a lot of users).

Nevertheless, I will try to find some time today to code an example for the first approach above. Meanwhile you can google a bit for ajax and check out jquery especialy the ajax part of it.

If you however wish to tahe the second approach, let me know and I'll prepare an example …

broj1 356 Humble servant Featured Poster

I have tried the while loop but still I am unsuccessfull

Can you specify in what way you were unsuccessful, eg. what was expected outcome and what really came out?

A few comments on your code:

  • You should enclose your form elements within <form> tags and set appropriate form attributes (method and action)
  • in the php part you should catch the submitted form data using something like if(isset($_POST['submit'])) and only then process the data
  • I presume there would be only one record in the recordset if you search by user ID, so while loop is unnecessary
  • I am not sure if is OK that form elements are enclosed within the <label> tags (but I might be wrong about that). It is still safer to use <label for="..."> way of coding it
  • I will repeat an old tune: sanitize the input form users before using it in a db query (google for sql injection)
  • think of switching from mysql extension and using something more modern (and secure) like pdo
broj1 356 Humble servant Featured Poster

Where does it stop? What is the error?

The query:

$sql = "SELECT mobno1,mobno2 FROM custreg";

presumably returns a set of rows, but

$data = $q->fetch(PDO::FETCH_ASSOC);

returns only one row. Is that what you aimed for?

Note, you have a line of code saying:

$message = urlencode($tempmsg);

But where is teh $tempmsg being defined?

broj1 356 Humble servant Featured Poster

Try using result->num_rows instead (it returns number of rows found):

if($result->num_rows == 0){
    echo "invalid username" ;
} else {
    echo "welcome";
}
broj1 356 Humble servant Featured Poster

Maybe line 23: while($row=$result->fetch_assco()){...

It should probably be:

while($row=$result->fetch_assoc()){...

assoc stands for associative; this method returns a row in an associative array where field names are keys.

broj1 356 Humble servant Featured Poster

Can you add a brief description on how you solved it.

broj1 356 Humble servant Featured Poster

Have you managed to correct the above error?

broj1 356 Humble servant Featured Poster

It is a lot of code but as it seems the $image[photos] is an array of photos that you should iterate through, something like:

foreach($cleaned_response as $image){
    foreach($image[photos] as $oneImage) {
        echo'<img height="100" width="100" src="'.$oneImage['fullsize'].'"/>'
    }
}
broj1 356 Humble servant Featured Poster

Just a few thoughts:

  • you should check if all the required values exist before using them in the query (otherwise the query might break)
  • you should sanitize the values before using them in the query (otherwise you could pass some nasty user supplied data to your DB server than can compromise security)
  • you should hash the password and store / use the hashed value (so users are ensured they have full control over their access)

This is example code (it can be improved, but is simplified to show what I meant):

// if any of the data is missing redirect to some error page or back to the form
if(
    !isset($_POST['username']) || empty($_POST['username']) ||
    !isset($_POST['password1']) || empty($_POST['password1']) ||
    !isset($_POST['email']) || empty($_POST['email'])
  ) {
      header("location: error.php");
      exit();
}
// sanitize the data
$username = mysqli_real_escape_string($_POST['username']);
// use crypt or similar to hash the passwords
$password1 = some_hashing_method_here($_POST['password1']);
$email = $password1 = mysqli_real_escape_string($_POST['email']);
...
broj1 356 Humble servant Featured Poster

If you want to sort using php then you have to:

  1. convert javascript array (of arrays) into php array using json_decode function
  2. sort the php array using array_multisort function

This is the code, see also comments in the code:

// this is original string representing a javascript array of arrays (note square brackets arround your string)
$jsonString = '[[1366754400000, 8], [1366840800000, 3], [1366927200000, 1], [1368482400000, 1], [1384383600000, 1], [1369951200000, 1], [1377554400000, 1], [1377813600000, 8], [1380232800000, 4], [1381960800000, 4], [1382914800000, 6], [1384297200000, 6], [1384383600000, 1], [1386716400000, 2], [1389049200000, 5], [1392764400000, 3], [1393196400000, 1], [1397599200000, 4], [1398636000000, 2], [1401141600000, 1], [1401746400000, 1], [1409954400000, 1], [1410386400000, 5], [1371420000000, 25], [1377122400000, 1], [1386889200000, 1]]';
// convert json into php array
$arr = json_decode($jsonString);
// prepare temporary arrays for sorting
foreach($arr as $key => $val) {
    $times[$key] = $val[0];
    $values[$key] = $val[1];
}   
// sort the array using temporary arrays
array_multisort($times, SORT_ASC, $values, SORT_ASC, $arr);
// check the sorted array
echo '<pre>' . print_r($arr, 1) . '</pre>';

You can convert sorted php array back to javascript using json_encode function so you can use it in your javascript library.

broj1 356 Humble servant Featured Poster

You have a space in your index name:

echo '<option value="'.$data2['level _name']...

The space is caused by a line break. Remove the linebreak and everything should be fine.

The error was not obvious until we looked at the HTML code :-)

broj1 356 Humble servant Featured Poster

The table structure and data looks OK. It is time to have a look a the generated HTML code. Can you post the HTML code for the group_level select element (right click -> View page source -> find the code for the select element in question or use Element inspector).

Mind you, how come you do not use level_id in the option values instead of level_name? This would be more appropriate.

broj1 356 Humble servant Featured Poster

Something like this might help:

$oldArray = array(
    'item-_token' => 'k4i2tQbZNuKnhV0vqbdBJ0XlwKzGLm09KA0pWa5n',
    'item-link' => array ('link 1', 'link 2', 'link 3'),
    'item-shop_name' => array('a', 'b', 'c'),
    'item-color' => array('blue', 'yellow', 'black')
    // ...
);

$newArray = array();

foreach($oldArray as $key1 => $arr1) {
    // do not know what to do with the item-_token element so skipped it
    if($key1 == 'item-_token') {
        continue;
    }
    foreach($arr1 as $key2 => $val2) {
        $newKey2 = $key1 . '-' . $key2;
        $newArray[$key2][$newKey2] = $val2;
    }
}

echo '<pre>';
echo print_r($oldArray, 1);
echo print_r($newArray, 1);
echo '</pre>';
broj1 356 Humble servant Featured Poster

As you can see there is no value for group_level.

  1. Have you selected any value?
  2. Is there a field level_name in the level table?

What is the output of the following queries:

SELECT * FROM `level`;

and

SHOW COLUMNS FROM `level`;

(copy each of the above two queries into phpmyadmin and post the output).

broj1 356 Humble servant Featured Poster

You can also put this code on line 58:

echo '<pre>', print_r($_POST, 1), '</pre>';

so the content of the post is displayed. Select values and post the displayed debug info here.

broj1 356 Humble servant Featured Poster

And did you select any level in the dropdown when you were testing?

broj1 356 Humble servant Featured Poster

As I said your select element might have no values or no value was selected. You can test for the former by setting a default value as per my post above (change the code on line 65 of your first post).

broj1 356 Humble servant Featured Poster

Have you checked that the select element (<select name="group_level">...) has any values? Change default value to something visible (like X) so you can check if it gets saved.

$group_level = isset($_POST['group_level']) ? $_POST['group_level'] : 'X';
broj1 356 Humble servant Featured Poster

Put the debug code after the else block:

if (empty($_GET['group_id']))
{
$sqlstr = "INSERT INTO `invoice`(group_id, group_date, group_package, group_level, group_teacher, group_payment) VALUES('".$group_id."','".$group_date."','".$group_package."','".$group_level."','".$group_teacher."','".$group_payment."')";
}
else
{
$sqlstr = "UPDATE `invoice` SET group_date='$group_date', group_id='{$_GET['group_id']}', group_package='$group_package', group_level='$group_level', group_teacher='$group_teacher' WHERE group_id='{$_GET['group_id']}'";
} 

die('<pre>' . print_r($sqlstr, 1) . '</pre>');
broj1 356 Humble servant Featured Poster

What is the output if you put this debug code on line 82:

die('<pre>' . print_r($sqlstr, 1) . '</pre>');
broj1 356 Humble servant Featured Poster

Also you can write some temporary debug code to print your query on the screen and then copy and paste it into phpmyadmin (or other DB tool) to check it against your data. Put something like this on line 82:

die('<pre>' . print_r($sqlstr, 1) . '</pre>');
broj1 356 Humble servant Featured Poster
  1. You are using double quoted strings so you can simplify things. Instead of:

    $sqlstr = "UPDATE invoice SET group_date='".$group_date."', group_id='".$_GET['group_id']."', group_package='".$group_package."', group_level='".$group_level."', group_teacher='".$group_teacher."' WHERE group_id='".$_GET['group_id']."'";

you can write it:

$sqlstr = "UPDATE `invoice` SET group_date='$group_date', group_id='{$_GET['group_id']}', group_package='$group_package', group_level='$group_level', group_teacher='$group_teacher' WHERE group_id='{$_GET['group_id']}'";

The query is far more transparent now and errors are easier to spot.

  1. Using unsanitized user suplied values in your queries is a bad security practice. Validate/sanitize $_GET['group_id'] variable before using it.

  2. Checking $_GET['group_id'] with if(empty($_GET['group_id'])) might not be enough. Maybe you should add an isset() check like:

    if(!isset($_GET['group_id']) || empty($_GET['group_id']))

but I am more or less guessing here since it depends on other code.

broj1 356 Humble servant Featured Poster

Make a file that will contain all your functions, something like functions.php. You can put it in a special folder if you wish (like lib or something). The include this file whenever you need to call any of contained functions. You use either include or require construct for that. The difference between the two is minimal, basicaly only in how they react if the file can not be found. See the manual at the above links.

There are also cousins include_once and require_once that make sure that each file is included only once. Namely, it may happen that with many include/require calls you might try to include the same file more than once and if that file contains i.e. function definitions you would get an error (since the same function would be declared more than once).

broj1 356 Humble servant Featured Poster

Your script might work if you change line 2 to:

if(isset($_POST['Submit']))

since you usualy check whether the form was submited (but this is more or less just a guess).

However, do take seriously above notes about security.

broj1 356 Humble servant Featured Poster

If no event has been selected from the dropdown, you are in trouble since $_POST['events'] possibly does not exist and you get a notice (the script obviously gets executed anyway). What you have to do is to check for existence and act appropriately:

if(isset($_POST['events'])) {
    $event = $_POST['events'];
} else {
    // do something (get user to provide the data or provide a default value yourself...)
}

You might use this technique for all fields that might be empty but are mandatory. or even better do a client side check first using javascript.

broj1 356 Humble servant Featured Poster
// initialize output array
$outputArray = array();
$tmpArray = explode("/", $aName);
foreach ($tmpArray as $tmpString) { 
    $tmpOneRow = explode("-", $tmpString);
    // add two elements to the output array
    $outputArray[] = $tmpOneRow[0];
    $outputArray[] = $tmpOneRow[1];
}
// check the result
print_r($outputArray);

Beware: no error checking in above example. You might want to check for existence of elements.

broj1 356 Humble servant Featured Poster

Maybe you post a little bit more code. At least to see where is the information about the ommittee member that has taken the book in.

broj1 356 Humble servant Featured Poster
broj1 356 Humble servant Featured Poster

It works perfectly well in my browser (Firefox 30 on Win7). Clicking on a View page source it shows 5 tabs.

broj1 356 Humble servant Featured Poster

The option that should be selected has to have a selected="selected" attribute. To find out which one it is, you do a check in each iterration. Suppose that com_FirstName is the criteria as in your example:

// committee member that has taken the book in
$comiteMemeber = 'John';
while($row_com = mysql_fetch_assoc($res_com)) {
    $dropdown .= "\r\n<option value='{$row_com['com_FirstName']}'>{$row_com['com_FirstName']}";
    // here you do the check
    if($row_com['com_FirstName'] == $comiteMemeber) {
        $dropdown .= ' selected="selected"';
    }
    $dropdown .= ">{$row_com['com_FirstName']}</option>";
    </option>";
}
broj1 356 Humble servant Featured Poster

Se the manual - the procedural style part. The mysqli_query expects two parameters, the link and the query. Similar goes for the mysqli_error. It expects the link in procedural version.

broj1 356 Humble servant Featured Poster

I tried that in begining, it execute 2 echo's for text and for = 0 so its like Points can't be text.Clean 0

What did you input to get these two echo statemens?

I tested my code and it works OK. It is important to have the exact series of if statements.

hey broj1, long time no seen, glad to see you!

:-) Thank you. Same here.

broj1 356 Humble servant Featured Poster

Why don't you do it simple way:

// first check if it is or isn't a number
if(!is_numeric($points)) {
    echo "Points can't be text";
// then try all possible values
} elseif($points == 0) {
    echo "Clean 0";
} elseif($points > 0 && $points <= 50) {
    echo "You did not pass";
} elseif($points > 50 && $points < 100) {
    echo "You passed test";
} elseif($points == 100) {
    echo "You finished with best result"; }
}

And beware: on line 20 you are using two variables for comparison: $points and $bodovi. Seems like a typo.