broj1 356 Humble servant Featured Poster

On your loging page you should start with

// start session
session_start();

// unset any session data until user submits valid username and password
unset($_SESSION);

Then when user enters a valid username (i.e johnybegoode) and password set session variables you need, such as

$_SESSION['username'] = 'johnybegoode';

Then on other pages for that user first check for valid username using the code from previous post

<?php 
session_start(); 

// say that user johnybegoode has successfuly logged in and $_SESSION['username'] was set
// to johnybegoode

if(!isset($_SESSION['username'] or $_SESSION['username'] !='johnybegoode')){
// re-direct ke index.php  

header("location:index.php");  
}  
?>

Then provide a logout link which points to the login page. When user clicks on it (logs out) the session is unset on the login page first.

Option 2: Your logout link can point to some other page (logout.php) where you can thank the user, unset session, do other cleanup, log the event etc and automaticaly redirect to login page.

Note: you can not unset session with javascript onclick directly, you have to use ajax and implement a javascript function that calls a php script that unsets the session but that is a more complex topic.

Even more important note: in this example there was nothing said about security. Make sure you do all the security exercises when dealing with input and session. See previous posts in this thread and other threads here and arround.

broj1 356 Humble servant Featured Poster

Sorry, my typing error. It should be:

if(!isset($_SESSION['username']) and $_SESSION['username'] !='guest'){

I usualy check code before I post but haven't done so this time.

broj1 356 Humble servant Featured Poster

One possible reason could be that you are only checking for the existence of username in the session but not the value of it. Try it this way:

<?php 
session_start(); 

// say that user johnybegoode has successfuly logged in and $_SESSION['username'] was set
// to johnybegoode

if(!isset($_SESSION['username'] or $_SESSION['username'] !='johnybegoode')){
// re-direct ke index.php  

header("location:index.php");  
}  
?>

Another reason could be that you do not unset $_SESSION upon unsuccessful login or upon logout.

broj1 356 Humble servant Featured Poster

The function session_is_registered() is deprecated (as the notice says) which means that it might be dropped in future and you are discouraged to use it. See http://php.net/manual/en/function.session-is-registered.php. Check the session variable instead, which has the same effect:

<?php 

session_start(); 

if(!isset($_SESSION['username']){
 
    //re-direct ke index.php
    header("location:index.php");
}

?>

.

broj1 356 Humble servant Featured Poster

The third block of code is OK, that is how you do it. Of course you can also have functions in a separate file like in your second block example in the fix_name.php file. Only the line 4 of the second block should be:

echo fix_name("costa playa");
broj1 356 Humble servant Featured Poster

See an example here:

http://www.daniweb.com/web-development/php/code/379236/page2

Have look at the last post with improved code (the code in the first post was criticised rightly for lack of security measures).

broj1 356 Humble servant Featured Poster

On Linux (maybe on Windows too) you can use mysqldump command to backup mySql database in a SQL script. Optionaly the script can be compressed (gzipped in this example).

// username, password, mysql host, database name
$dbuser = 'yourMysqlUsername';
$dbpw = 'yourMysqlPassword';
$dbhost = 'yourMysqlHost';
$dbname = 'yourMysqlDatabaseName';

// valid path to a directory where the database will be backed up
$backupPath = 'some valid path like /var/www/db_backup/';

// the name of the backup file
$backupFile = $backupPath . $dbname . '_' . date("Y-m-d-H-i-s");

// command for dumping database
$dbdumpcmd = "mysqldump --opt -v -h $dbhost -u $dbuser -p'$dbpw' $dbname";

// Option 1: a command to backup in a SQL file
$command = "$dbdumpcmd > $backupFile.sql";

// Option 2: a command to backup in a gzipped SQL file
$command = "$dbdumpcmd | gzip > $backupFile.gz";

// execute the command
system($command);
broj1 356 Humble servant Featured Poster
broj1 356 Humble servant Featured Poster

Just to help you a little bit here is the code for easier debugging:

<?php
$query = "SELECT * FROM tbl_users WHERE ex_date between now() and adddate(now(), INTERVAL 7 DAY) ORDER BY user_id ASC";
$result = mysql_query($query);

$num = mysql_numrows($result);

/* DEBUG CODE*/
echo "<p>Number of rows: $num</p>";
/* END DEBUG CODE*/

$i = 0;

while ($i < $num)
{
    $id = mysql_result($result,$i,"user_id");
    $email = mysql_result($result,$i,"login_email");
    $loginname = mysql_result($result,$i,"loginname");
    $ex_date = mysql_result($result,$i,"ex_date");
    $ex_date = date("d-m-Y", strtotime($ex_date) );

    //send email

    $to = "$email";

    $subject = "Expriy Notice";

    $from = "Admin";

    $msg = "Hello $loginname,<BR><BR>";
    $msg .= "Your Account will expire in 7 days. Your Expiry Date is $ex_date<br /><br />";
    $msg .= "Regards: <br /><br />Admin";
    $msg .= "Admin";

    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
    $headers .= "From: Admin\r\nReply-To:sammy@gmail.com" . "\r\n";

    /* DEBUG CODE*/
    echo "<p>Variable i: $i<br />";
    echo "Email: $to<br />";
    echo "Subject: $subject<br />";
    echo "Message: $msg<br />";
    echo "Mail code: mail($to,$subject,$msg,$headers)</p>";
    /* END DEBUG CODE*/

    // Temporarily commented out
    // $mailsend = mail($to,$subject,$msg,$headers);

    // Temporarily commented out
    // echo $mailsend ? "Email was sent :-)." : " Email sending failed.";

    $i++;
}
?>

It might help if you post what gets displayed in your browser.

broj1 356 Humble servant Featured Poster

Can you put the if block in the while loop (on the end of the loop), insert this code before the end line in if block and post the result:

echo "<p>Variable i: $i<br />";
echo "Email: $to<br />";
echo "Subject: $subject<br />";
echo "Message: $msg</p>";

Other remarks:

You should change the code on line 42 to

$msg = "Hello $loginname,<BR><BR>";

(no concatenation on the beginning of building up a message, oterwise the $msg will grow).

The quotes arround the mail function parameters are unnecesary (they cause unnecesary parsing of variables in strings).

All code could be in one block of <?php ?>

broj1 356 Humble servant Featured Poster

But was the list of emails correct (only the users that were supposed to get the mail)?

broj1 356 Humble servant Featured Poster

Also, what is the point in a condition in line 30

if($query == TRUE)

which is always true?

broj1 356 Humble servant Featured Poster

Your query should return only records for users whose expiry date is 7 days or less. That is why your mailing code should go into the while loop which steps through the result set. I suggest you check what your query returns. comment out lines 60 and 62 and add this code on line 63:

echo "$email<br />";

That should list emails that are supposed to get the message. Make sure that the query returns the emails you expect.

broj1 356 Humble servant Featured Poster

Apart from slight size increase you will get some redundancy since area code is stored in two fields (not a problem if area codes do not change, but you never know - from this perspective the tbl_id is better candidate for a foreign key) Your destination number could be without the area code, only the local phone number but I doubt you can change this now. You can add a foreign key with an UPDATE query so number of records should not be a problem if there arent too many area codes. You can prepare a php script to run the query.

broj1 356 Humble servant Featured Poster

If you add an area code as a foreign key to billing table then this query might help you:

SELECT `date`,`destination`,`callsec`,`tbl_cost`,`callsec`*`tbl_cost` AS price FROM `fees` RIGHT JOIN billing ON `tbl_code`=`tbl_code_fk`

Note that table names are omitted from the query for simplicity. Also a field name for date is maybe not a good idea since it is mysql function name and can cause errors.

broj1 356 Humble servant Featured Poster

If I get it right you have two tables for billing phone calls. The fees table has area codes and cost for each area code with tbl_id being primary key, the billing table holds data about calls made. The thing is that the tables are not linked with the same data, which means you should have a foreign key in the billing table (eg. tbl_id or tbl_code if it is unique). The area code (tbl_code) is actualy part of destination field but since it is not the same lenght in all records, you can't use a mysql SUBSTRING function to extract it. I would add a foreign key to the billing table (an area code if it is unique or tbl_id). Then the JOIN can be made.

broj1 356 Humble servant Featured Poster

I hope this is what you are looking for:

SELECT fees.tbl_cost FROM billing LEFT JOIN fees ON billing.tbl_code=fees.tbl_fee WHERE billing.tbl_code='011'
broj1 356 Humble servant Featured Poster

Introduce a foreign key in Table B which then have two fields: dst_code_fk with values 011, 012, 013... and fee with values 0.38, 0.55, 0.55... Then use join and if you want to find out a fee for dst_code 011 do it like this:

SELECT table_a.fee FROM table_a LEFT JOIN table_b ON table_a.dst_code=table_b.dst_code_fk WHERE table_a.dst_code='011'

The join type (left, right, inner, outer) depends of structure of your data. There are some nice examples of joins on the web.

broj1 356 Humble servant Featured Poster

I have prepared a tutorial with example on how to code a login page. It has been submited as a new thread to the tutorial section. It is not yet there though so I am posting the code here as well. Hope it will help you. It is well commented. Everyone is invited to comment on it and suggest improvements.

<?php
/*
Login script example
- displays a form for entering username and password
- checks wheter username and password exist in database and match
- if no match is found, clears the form and displays an error message
- if exactly one match is found, redirects user to another page

Tip: make page look nicer with some CSS

For this login example you will need working database (mySql used here), and
some test data as per instructions below (or you can use phpmyadmin or similar app)

Test data (2 users):

username 1: misterx
password 1: secretpassword1
hashed password1: (d5f835dbe946b420e1dacde0558078b4eee36745)

username 2: mistery
password 2: secretpassword2
hashed password2: (fd021e83bf64b46a2a7b707441dd167bc43749d4)

Prepare database 'mydatabase' with table 'user' and some test data

1. Use this or similar query to create database 'mydatabase'
CREATE DATABASE `mydatabase` ;

2.create DB user named 'testdbuser' with password 'verysecretdbpassword' and
 granthim privileges
CREATE USER 'testdbuser'@'%' IDENTIFIED BY 'verysecretdbpassword';
GRANT ALL PRIVILEGES ON * . * TO 'testdbuser'@'%'
IDENTIFIED BY 'verysecretdbpassword'
WITH GRANT OPTION MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0
    MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ;

3. Use this or similar query to create table 'users' in database 'mydatabase'
CREATE TABLE `mydatabase`.`users` …
broj1 356 Humble servant Featured Poster

Your code is stil not OK. The credentials validation part is missing. You must check wheter supplied username exists in the database, and wheter password is correct. If both these conditions are true, you set the login condition ($_SESSION='1'). The flag $is_valid is not necessary it was propsed just for clarity.

The logic baicaly is:
1. set the login condition ($_SESSION='0') to false (or 0 in your case), until you check that the user provided correct credentials
2. check for any input from user (line 4)
3. if input exists check if the credentials are OK
4. if credentials are ok, set the login condition ($_SESSION='1') and redirect the user to authorized page
5. if credentials are not OK, do something elese (error mesage, sign up form...)
6. display the table with the login form

I would like to give you an example but am a bit tight with time so I do not promis anything.

broj1 356 Humble servant Featured Poster

Change line 4 to

if(isset($_POST['Submit']) and !empty($_POST['Submit']))
broj1 356 Humble servant Featured Poster

Change your login page to something like:

<?php
// start a session (always first thing in a script)
session_start();
// initialize session variable with value for not valid login
$_SESSION['loggedin']='0'
// check for form submission (user clicked on submit button)
if($_POST['submit']) {
// check if username and password are OK (query a database)
// and set some flag if OK (i.e. $is_valid = true;)  else set it to false
// ...
// check the flag
if($is_valid) {
// now set the session
$_SESSION['loggedin']='1'
// and redirect to next page 
header("location:page_for_loged_users.php")
} else {
// if the flag is set to false, user credentials were wrong
// redirect to page with an error or with login form or whatever
header("location:page_for_signup_or_error.php")
}
}
?>
//your html code with a login table

There are of course other ways of doing it like doing it all on one page and when wrong credentials were submitted the html code displays an error otherwise a login form.

broj1 356 Humble servant Featured Poster

You should set $_SESSION='1' only after the successful login not in the beginning of the script.

broj1 356 Humble servant Featured Poster

When you click refresh the form data gets resubmited. What you should do is check in the backend system (i.e a database) wheter submited account already exists.

broj1 356 Humble servant Featured Poster

Possible cause might be an endless loop. Check your for and while loops wheter they end as intended.

broj1 356 Humble servant Featured Poster

The difference between exmples is:

The former is using object oriented programming aproach. $DB is an object and Query() is a method of that object. The later is classical procedural approach where mysql_query() is a function. Both do similar task I guess. You in general decide wheter to use object oriented programming or procedural.

Just a note: your question is about PHP and executing SQL statement on MySql database. JQuery, as faras I know, is a Javascript library and hasn't got much to do with PHP and MySql.

broj1 356 Humble servant Featured Poster

Your form has form elements with the same name in each row so $_POST array contains only the last set of values I guess. Try to enclose form elements that belong to one row in <form></form> tags (so each form has only one submit button).

broj1 356 Humble servant Featured Poster

Heredoc syntax is a way to use custom identifier to delimit strings in PHP. Usualy string are delimited with single or double quotes, but with heredoc you declare (name) an identifier. This way you do not have to escape single and double quotes anymore. Te rules for chosing identifier name are same as for other labels in PHP. You put identifier in the beginning (after <<<) to let PHP know that now this is the delimiter for the string and you put at the end to let PHP know where the end of the string is. The line with closing identifier shall not contain any other characters (even no indent) which could be the only drawback since it might spoil the look of your code :-).

I use heredoc when I have alot of single and double quotes in text so I do not have to wory about escaping the ones that normaly should be escaped. A simple example of is when generating HTML code with PHP and the code consists of events that call Javascripts function with parameters. Using single or double quotes you would code like this:

$htmlButton = '<input type="button" onclick="someJsFunction(\'parameter1\',\'parameter2\',\'' . $var_parameter3 . '\')" />';
$htmlButton = "<input type=\"button\" onclick=\"someJsFunction('parameter1','parameter2','$var_parameter3')\" />';

Using heredoc syntax you can code this way (maybe a bit cleaner):

$htmlButton = <<< HTMLCODE
<input type="button" onclick="someJsFunction('parameter1', 'parameter2','$var_parameter3')" />
HTMLCODE;

Note variables within heredoc get parsed as with double quoted strings.

There is also nowdoc syntax which is similar but behaves …