broj1 356 Humble servant Featured Poster

The subquery should be in parentheses. Also you have to add a WHERE condition to get only one value as a result of the subquery. You can get the username through session as I described in my previous post.

$SQL = "INSERT INTO tbl_userprofile (userid, name, surname, gender, nationality, address, mobile, department, email, question, answer)
(SELECT id WHERE username='$username'), '$name', '$surname', '$gender', '$nationality', '$address','$mobile', '$department', '$email', '$question', '$answer'
FROM tbl_user
WHERE username = '$username'";

To test the query add this temporary debug code just after the query:

// TEMP DEBUG
die($SQL);

This will display the final query and stop the script. You can now examine the query and copy/paste it into phpmyadmin to test how it works. You can also paste it here for us to check it.

broj1 356 Humble servant Featured Poster

Then on the first page save the username into session ($_SESSION array). On the second page read it form the session and use it.

First page:

session_start();
$_SESSION['username'] = $username;
...

Second page:

session_start();
if(isset($_SESSION['username'])) {
    $username = $_SESSION['username'];
    ...
} else {
    die('Error: Username does not exist.');
}
broj1 356 Humble servant Featured Poster

OK, but how do you know which user are you inserting data for? How is the sequence of inserting happening? Does the insert into tbl_userprofile come immediately after insert into tbl_user or is there any user interaction in between? Please describe the process.

broj1 356 Humble servant Featured Poster

Depends on what user data you know about the new user from the tbl_user table. Most probably it is the usernname:

$username = ...;

$SQL = "INSERT INTO tbl_userprofile (userid, name, surname, gender, nationality, address, mobile, department, email, question, answer) VALUES
((SELECT id from tbl_user WHERE username='$username'), '$name','$surname','$gender','$nationality','$address','$mobile','$department','$email','$question','$answer')";

I do not think you need quotes arround the subquery, but I am not 100% sure.

broj1 356 Humble servant Featured Poster

You do not need a WHERE clause when you insert a new record. All you need to add is a user ID:

// get user ID form somewhere
$userId = ...

// put it into the query
$SQL = "INSERT INTO tbl_userprofile (userid, name, surname, gender, nationality, address, mobile, department, email, question, answer) VALUES 
('$userId', '$name','$surname','$gender','$nationality','$address','$mobile','$department','$email','$question','$answer')";

You need a WHERE clause when doing a SELECT, UPDATE or DELETE.

broj1 356 Humble servant Featured Poster

You first have to insert new user data into tbl_user table, somehow creating fields (id could be autoincrement). Then use this user ID and add it to the query for the tbl_userprofile table.

broj1 356 Humble servant Featured Poster

In my example I used mysqli extension but you are using mysql exstension (see the query on line 19 of your code). You should actually use only one exstension in your script. I strongly suggest you switch to mysqli which is newer and has more features. Mysql exstension is old and has been deprecated in newest versions of PHP. So if you have reasons stay with mysql and change the escape statements to:

// escape the values and assign them to variables
$warranty = mysql_real_escape_string($_POST['warranty']);
$delivery = mysql_real_escape_string($_POST['delivery']);
$price = mysql_real_escape_string($_POST['price']);

and the error won't appear anymore. When you have chance switch to mysqli extension. And sory for the confusion I might have caused :-)

masterjiraya commented: he mixed 2 api scripts ( the one who asked it ) +4
broj1 356 Humble servant Featured Poster

As AHarrisGsy says you did not assign values from $_POST to variables you use in your query. So check for the existence of each of $_POST element, escape the values and assign them to variables. If any of the $_POST elements is missing then display an error message.

if(isset($_POST['warranty']) && isset($_POST['delivery']) && isset($_POST['price'])) {
    // escape the values and assign them to variables
    $warranty = mysqli_real_escape_string($_POST['warranty']);
    $delivery = mysqli_real_escape_string($_POST['delivery']);
    $price = mysqli_real_escape_string($_POST['price']);
} else {
    // if any of the values is missing display error message
    die('Please select all required fields!');
}
    // get username form somewhere (i.e. session)
    $username = $_SESSION['username'] // I am guessing this
    ...
    // now you can use variables in the query
    $sql = "INSERT INTO order SET username='$username', warranty='$warranty', delivery='$delivery', price='$price'";
broj1 356 Humble servant Featured Poster

To add a row at the end of the HTML table you can use Javascript and insertRow() and insertCell() methods. Create a function that will insert a row and four cells in that new row. Then make a link with an onclick event that will trigger inserting of the row. See example here.

To save the data in database use either Ajax as diprofinfiniti suggested or just process the form by submitting it usual way.

broj1 356 Humble servant Featured Poster

The basic principle is:

At login page you create a session variable to store login information when login is successfull. The login information might include the user rights level i.e.

if(<login successful and user level= admin>) {
    $_SESSION['user_level'] = 'admin';
}

On each secured page where you first check if the user_level exists and if it is appropriate. i.e on admin page you would check:

if(isset($_SESSION['user_level']) && $_SESSION['user_level'] == 'admin') {

    // do admin stuff here
    ...

} else {
    header('location:logout.php');
    exit();
}

If login information is not correct the user will be redirected to logout page that will destroy the session and clean up whatever needed and redirect to login page.

broj1 356 Humble servant Featured Poster

Try:

else if ($password !== $cPassword)
broj1 356 Humble servant Featured Poster

I guess your problem is not the session unsetting at all but the HTTP header is not redirecting as you are expecting. Can you post the whole logout.php and how you get to it (e.g. by clicking a link).

broj1 356 Humble servant Featured Poster

The solution for your requirement seems to be OK. But in some circumstances the result in line 5 returns FALSE which indicates an error when querying. You should change the code in line 5 to:

$result=mysql_query($statement) or die(mysql_error());

This way if there is an error when querying the error will be displayed and the script stopped. Now you can examine the reason for the error.

BTW: in future you might want to consider dropping the old and deprecated mysql extension and switching to newer mysqli extension or PDO.

broj1 356 Humble servant Featured Poster

Also have a look at Example 1 on PHP.net session_destroy page:

http://php.net/manual/en/function.session-destroy.php

broj1 356 Humble servant Featured Poster

try adding unset($_SESSION); after session_start()

I wouldn't recommend that. See note here. This will disable the registering of session variables through the $_SESSION superglobal.

broj1 356 Humble servant Featured Poster

I tested your code on my server and it works OK. Clicking on Back button always brings me to index.php. Make sure you have no html before the code you posted (not even a space). If you have any html before a header() function, the function will not work.

beginnerpals commented: did it, still not working :/ +0
broj1 356 Humble servant Featured Poster
public function getLastInsertId()
{
    // you can do checks first (has the query been successful etc)

    return $this->mysqli->insert_id;
}

It would be good idea to initialize the properties:

protected $mysqli = null;
protected $result = null;

I would also use more descriptive names. The connection class is not only doing the connection, it is also returning the data. $mysqli property would be better named $db so you can extend the class for other drivers (i.e Oracle). Otherwise you are just duplicating the functionalities of mysqli.

broj1 356 Humble servant Featured Poster

Change line 5 to:

if(isset($_POST['submit']) && isset($_POST['start']) {
    ...
broj1 356 Humble servant Featured Poster

Notice: Undefined index: start in C:\wamp\www\cinema3\movies\films\booking\book here1.php on line 7

This error says that index named start does not exist in some array (most probably $_POST). I expect it is this line that is causing troubles:

$start =mysql_real_escape_string($_POST['start']);

See my post above for the solution.

broj1 356 Humble servant Featured Poster

The problem is probably in this line:

$start =mysql_real_escape_string($_POST['start']);

$_POST['start'] is set if user selects one of the radio buttons (booking time). If user does not select any button you have to display an error message, but you have to test for it first:

if(isset($_POST['start'])) {
    $start =mysql_real_escape_string($_POST['start']);
} else {
    die( " please enter the time .<a href='../3D The Croods.php'>click here to choose time</a>");
}

And another thing: I thing it is not a good idea to have php script names with spaces in them.

broj1 356 Humble servant Featured Poster

No problem, happy coding :-)

broj1 356 Humble servant Featured Poster

It seems Ajax would be appropriate for this. So on selecting a dropdown the room number would be changed in database but the page would still display the table and the URLs with user IDs. Is this correct?

broj1 356 Humble servant Featured Poster

Just to make things more clear: does each row contain information for different user (user id) or are all rows for the same user?

broj1 356 Humble servant Featured Poster

And info on cookies and session from PHP's point of view:

http://php.net/manual/en/features.cookies.php

http://www.php.net/manual/en/book.session.php

broj1 356 Humble servant Featured Poster

Is it only that you do not want to to have a submit button or do you not want to reload the page?

In first case you can use onchange event of the select (dropdown).

echo '<select name="room" id ="rooms" onChange="this.submit()">';

The form wil get submitted once you select an option and you do not need a submit button.

In you do not want to reload the page then use Ajax as AHarrisGsy suggested. Ajax is simple to use if you use jQuery. See this link.

broj1 356 Humble servant Featured Poster

You are welcome. Please mark as solved. Happy coding :-)

broj1 356 Humble servant Featured Poster

Sory to come back so late, I was away. The trouble was that the select element (dropdown) was not constructed correctly. Correct code on line 58 is:

<option value="<?php echo $category ?>"> <?php echo  $category ?> </option>

You missed double quotes for the value attribute and forgot to echo the category.

broj1 356 Humble servant Featured Poster

Post the whole script, please.

My code was just an example. You should adapt it to your particular script.

broj1 356 Humble servant Featured Poster

You can also insert multiple sets of values in one query:

INSERT INTO table_name 
(column1, column2, column3)
VALUES 
(value1, value2, value3),
(value4, value5, value6),
(value7, value8, value9)
broj1 356 Humble servant Featured Poster

You should have defined action attribute in the <form> tag which is the name of the script that will process the data. The script should go something like this:

<?php
// if submited the value will be in the $_POST['expenses'] element of the $_POST array
// (provided that the method is POST, otherwise change it to $_GET).
// so check for the existence of $_POST['expenses'] (or $_POST['submit']) and use the value
if(isset($_POST['expenses'])) {

    $expenses = $_POST['expenses'];
}
?>
broj1 356 Humble servant Featured Poster

The code looks nice and clean. The only question I have is what is the purpose of code on line 52:

if($i <= $url_count - 1) {
    $query = 'INSERT INTO `ASX_PRICES` (`ASX_CODE`, `ASX_PRICE`, `DATE`) VALUES ';
}

The original purpose was to add comma between each set of values (but not at the last set of values, so you do not get an sql error). In your case it should throw an error in sql.

broj1 356 Humble servant Featured Poster

WHere do you keep the list of URL's? If it is a file or an array then do a while or foreach or for loop reading the urls, getting the value and add values to the insert query:

// your URLs (in an array in this example)
$url_list = array(
    'http://asx.com.au/asx/markets/priceLookup.do?by=asxCodes&asxCodes=ONT', 
    'http://...',
    'http://...',
);

// count of URLs
$url_count = count($url_list);

// temporary counter
$i = 0;

// start the query
$query = 'INSERT INTO ASX_PRICES (ASX_CODE, ASX_PRICE, DATE) VALUES ';

foreach($url_list as $url) {

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $var = curl_exec($ch);
    curl_close($ch);
    $first = stripos($var, '<th scope="row" class="row"><a href="' . $url . '"', 0) ;
    $second = stripos($var,'<td class="change indicator" nowrap>', 0);
    echo substr($var, $first, $second - $first);
    echo "<br />";

    // get the ASX_CODE and ASX_PRICE from the substring above (maybe using a regex)
    // and add to insert query
    $ASX_CODE = ...
    $ASX_PRICE = ...

    // get the date (wherever it comes from)
    $date = ...

    // add to the query
    $query .= "('$ASX_CODE', '$ASX_PRICE', $date)";

    // increase the counter
    $i++;

    // if it is not the last value, add the comma
    if($i < $count - 1) {

        $query = ', ';
    }
}

Not sure if I got what is your intention but I hope it helps.

broj1 356 Humble servant Featured Poster

Wrap the button group in a div and make that div hidden:

<div id="button-group">

...

</div>

The CSS:

#button-group {
    visibility:hidden;
}
broj1 356 Humble servant Featured Poster

Code for the last button:

<div class="buyOrSellBox">
<input id="memberRoleIntlBoth" value="both"
onclick="document.getElementById('userrole-error').style.display='none';changesubmitbtnname('yes');" 
name="userrole" style="border: 0px none ;" type="radio" 
<?
// the condition is:
// if $_REQUEST['userrole'] is not set (none of the radio buttons have been chosen)
// or the 'both' radio button has been chosen
// then make it checked
if(!isset($_REQUEST['userrole']) || (isset($_REQUEST['userrole']) && $_REQUEST['userrole']=="both")){
    echo 'checked="checked"';
}
?>
/>

I want to make this field "Hidden"

Which field do you want to make hidden - one button all the whole button group?

broj1 356 Humble servant Featured Poster

The manual for empty says:

Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.

The following things are considered to be empty:

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)

So 0 is empty (sounds a bit strange to me, we need to be careful with this function).

broj1 356 Humble servant Featured Poster

A few notes here:

  1. You mix GET and POST method. From URL it seems like your intention is to use GET, from the code it seems like you wanted to use POST; it is nothing wrong with mixing methods but do not do it if not realy needed since it is harder to control
  2. It is recommended to avoid $_REQUEST combined array. It is again not wrong if you use it but only if it is necessary and are careful. $_REQUEST contains data from $_GET, $_POST and $_COOKIE arrays and it might happen that you have same keys in them thus overwriting values.
  3. It is not recommended to use GET method for deleting. It is semantically wrong but more importantly the deleting URL gets cached and can do damage later on (intentionally or unintentionally).
  4. Escape values before using them in a query.

szabizs correctly spotted the error and suggested solution to existing code. I usually have to add my raving about security since this is my field of work :-) (and I had to learn it a hard way).

Szabi Zsoldos commented: That is correct, I've wanted just to help out him :) +3
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

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

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

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