Weel, it's time to check the UPDATE sql statement which I guess might be in update.php. Can you post it please.
BTW: I'll probably won't be able to reply sooner than tomorrow morning.
Weel, it's time to check the UPDATE sql statement which I guess might be in update.php. Can you post it please.
BTW: I'll probably won't be able to reply sooner than tomorrow morning.
You can do it using case statement:
if(!isset($_SESSION['access_level']) || $_SESSION['access_level'] < 180) {
header('location: logout.php');
} else {
switch($_SESSION['access_level']) {
case 220 : header('location:restricted_page1.php'); break;
case 200 : header('location:restricted_page2.php'); break;
case 180 : header('location:restricted_page1.php'); break;
default : header('location:logout.php');
}
}
I haven't noticed your question to me about access levels in one of your previous posts. Have you got those answers yet?
visitortimezone give Europe/Berlin, (India Standard Time) for localhost
VisitTime give 05:29:37 for 10 AM IST for localhost
Will this link help?
Tis is how I did it and it proved to be a good concept. I have defined access levels which were integers. The higher the level (value) the higher the privileges.
Between each level I had a space for new levels if I need them later. The access level is saved in the user database for each user.
access_level | description
--------------------------
220 | application admin (developes only)
200 | contents admin
180 | system admin
100 | regular user (edit, view)
60 | viewer (view)
0 | no access
As you can see I use unsigned integer for access level so it does not take much space in db. I have plenty of room below and above the range and also between access levels which proved good tactics since I had to add levels already. The access level gets stored in the session during login so all I have to do is to compare it with required level on the beginning of each page:
// example for checking a system admin's access level
if(!isset($_SESSION['access_level']) || $_SESSION['access_level'] < 180) {
header('location: logout.php');
}
In the above example only system admin and higher levels can access the page.
I also define constants to make the code more readable:
define('ACCESS_LVL_APPADMIN', 220);
define('ACCESS_LVL_CONTADMIN', 200);
define('ACCESS_LVL_SYSADMIN', 180);
define('ACCESS_LVL_REGUSER', 100);
define('ACCESS_LVL_VIEWER', 60);
define('ACCESS_LVL_NOACCESS', 0);
// example for checking a system admin's access level
if(!isset($_SESSION['access_level']) ||
$_SESSION['access_level'] < ACCESS_LVL_SYSADMIN) {
header('location: logout.php');
}
Classes are part of Object Oriented Programming concept (OOP). PHP first supported only traditional procedural programming style but with version 5 (and partly four) the OOP functionality was added. It has been mature for quite some time now and many functions have both versions (i.e. mysqli_query).
The benefit of OOP approach (or classes as you say) is easier maintenance, upgrading and better scalability of complex applications but provided that you design your classes appropriately. This takes practice to achieve. There is another benefit of being familiar with OOP in that many libraries and frameworks use OOP approach and it is good if you understand it well.
I have just noticed that you posted the structure and contents of the tables in your post, sory. You are missing the namn
column in the po
table. You are referring to the namn
column in the while loop.
And as Biiim said, associative indexes (keys) are case sensitive while mysql names are not. I would strongly suggest that you use always lowercase to avoid confusion. Also chose table names and field names carefully and make them descriptive for the same reason.
In most cases you need to declare a primary key (unique field) in a table so you can address particular records. If your data already has a field that is unique (such as social security number in the USA or enrollment number on universities) then you can use that, but you have to be sure it is unique (no two records can have the same value). If you haven't got such a field in your data then you usually let database create it for you by using autoincrement type of the field.
Did you maybe forget to declare the ID colums Autoincrement? That way you can leave the id values out and db will autogenerate them.
Edit: sory pritaeas, posted just seconds after you did :-)
You have to add a WHERE
clause to the query:
// first check if a querystring exists at all (avoiding errors)
if(isset($_GET['customer_name'])) {
// escape the value form the url (security)
$customer_name = mysql_real_escape_string($_GET['customer_name']);
// then use the value in WHERE statement
$sql="SELECT id,customer_name FROM Customers WHERE customer_name='$customer_name'";
}
And consider using mysqli instead of mysql.
One more thing: if password is incorrect, do not tell that to the user; if username is incorrect, do not tell that to the user. Allways tell them that login failed, but not the reason. This way you give no clue to potential attacker.
I am not sure whether I understood your question correctly but here we go: Setting an action attribute to another page is not a bad practice and I do not think it causes a lot of workload for the server. But you can have the action attribute set to the same page if you wish. In that case you have to check if the form was submitted on the beginning of the page. If yes, then you have to act appropriately (delete the record, redirect or display a message or whatever). But in your current case You have to check whether the query is OK so I suggest you do a little debugging. Change the deleteuserform.php page sligtly like this:
<?php
// this line is only for debugging, you will remove it later
die("Delete FROM Customers WHERE id = {$data['id']}");
mysql_query("Delete FROM Customers WHERE id = {$data['id']}");
?>
Now when you select an option from the drop down you will be redirected to the second page but the query will only get displayed and not executed. You can examine it and copy it to phpmyadmin and test it there.
I also suggest you state the form method explicitly to POST which is more appropriate for deleting.
<form action="deleteuserform.php" method="post">
On top of each page that uses session variables you have to put:
session_start();
It looks like it's missing on page 2.
More or less guessing:
On line 276 (reply code) you have:
$model_quote = printInvoice("Residential - Curbside/Garage", "S5-E", 119, $qts5e, $s5e_quote_residence, $total);
Shouldn't it be:
$model_quote = $model_quote . printInvoice("Residential - Curbside/Garage", "S5-E", 119, $qts5e, $s5e_quote_residence, $total);
Seems like you are loosing all previous information here. But I might be wrong since it is hard to figure this out from this amount of code.
To restate the above answers: the method $rtTransaction->getAddedOn()
presumably returns a unix timestamp which you want to convert to human readable date. If the displayed date is 1970-01-01
then the $rtTransaction->getAddedOn()
method has returned 0
which is a timestamp that translates to 1970-01-01
. As said above: investigate the $rtTransaction->getAddedOn()
since the error is quite possibly there. You can also post the method here.
1353658977
seem to be date in unix timestamp which converts to Fri, 23 Nov 2012 08:22:57 GMT
. If you get 1970-01-01
something must be wrong since the unix timestamp for this date is 0. If $rtTransaction->getAddedOn()
returns timestamp then it ovbiously returns 0.
On line 35 the each of the values should be enclosed in quotes, not the whole string $values
. Try this:
$values = "'" . implode("','", $escaped_values) . "'";
This code will produce a string: 'value1', 'value2' ..., 'valueN'
which you can safely use in your query (remove the quotes around $values):
$sql = "INSERT INTO name ($columns) VALUES ($values)";
Set up a web server, a database, maybe a PHP framework or libraries. Pick a good editor (a lot of people prefer Eclipse). Write a hello world or a phpinfo program and test if everything works together. Now you are ready to start thinking what would be a useful app for someone out there (or maybe yourself). Make design (on paper or in UML) and start coding it.
Once you query the database you can retrieve a row in either:
an array (associative: using mysql_fetch_assoc or enumerated using mysql_fetch_row or both using mysql_fetch_array) where keys are field names (or filed index) and values are the values you queried:
$myArray['username'] = 'broj1';
$myArray['password'] = 'IamNotTellingIt';
or
an object (using mysql_fetch_object) where property names are field names and propertiy values are the values you queried
$myObject->username = 'broj1';
$myObject->password = 'IamNotTellingIt';
So which one you use is just a matter of what you prefer to process when you use the values. I personally use the array functions.
Just a side note: mysql extension is becomming obsolete and will not be supported sometime in future. It is wise to start using the mysqli (improved) extension which has more features. So the above functions would be mysqli_fetch_assoc, mysqli_fetch_row, mysqli_fetch_array, mysqli_fetch_object.
If you want to use this function outside the object make it public.
public function getAktiva(){
return $this->aktivaLancar+$this->aktivaTetap;
}
This is usually the purpose of the get functions (getters): to get the data stored in protected or private variables.
mysqli_fetch_assoc function returns only one row. You use a while loop to go through all the rows (10 in your case) but the way you implemented your function this is not happening. If you want to use this function to return all results, you have to read all the rows within the function an return the array of rows not only one row (hopefuly you wont get to big resultsets).
To add a new fibonacci number on each refresh you should store each previous and current value in a session.
session_start();
// on the beginning you have 0 and 1
if(!isset($_SESSION['previous']) || !isset($_SESSION['current'])) {
$_SESSION['previous'] = 0;
$_SESSION['current'] = 1;
echo $_SESSION['previous'];
echo ' ';
echo $_SESSION['current'];
} else {
$current = $_SESSION['previous'] + $_SESSION['current'];
echo $current;
$_SESSION['previous'] = $_SESSION['current'];
$_SESSION['current'] = $current;
}
In the above output the values for category, collection and stone are missing (not set) and that is why the query can not get constructed correctly on line 55. The good practice is to check for existance of values of $_POST array before assigning them to variables. At the same time at least escape the values so you do not get SQL injection attack.
if(isset($_POST['model'])) {
$mod = mysqli_real_escape_string($_POST['model']); // example for mysql
} else {
$mod = '';
}
...
Another thing, I'm guessing, but I don't hink <input type="(float)number" name="price" /> is a valid markup
It definately isn't. This is HTML code and HTML does not have a cast function and casting number
attribute is not logical anyway. It must be a typo.
The number
attribute is HTML5 feature, it did not exist in (X)HTML 4.x.
foreach ($data1 as $in1 => $h1)
{
// temporary array for inner loop, needed for sorting
$count_arr_temp = array();
foreach ($data2 as $in2 => $h2)
{
$match = array_unique(array_intersect($h1, $h2));
// put count data in a temporary array
$count_arr_temp[] = count($match);
}
// sort temporary array
rsort($count_arr_temp);
// didplay sorted elements
foreach($count_arr_temp as $count) {
echo $count;
}
// add the delimiter
echo '||';
}
Your code seems to be allright. There are two things that come to my mind.
First one is to check whether the first block of the if
executes at all since maybe you are doing too little of checking of the $_POST values - namely you are not checking for the existence of elements (using isset
). I would do it this way:
if(isset($_POST['name']) &&
!empty($_POST['name']) &&
isset($_POST['email']) &&
!empty($_POST['email']) &&
isset($_POST['comments']) &&
!empty($_POST['comments'])
You can also test this with placing this code on line 15:
die('Howdy');
and see if it shows up.
The second thing to check is whether your mail server works. You can try that by sending a simple test mail in a debug script which would be something like:
<?php
if(mail(youremail@email.com , 'Mail test' , 'Testing mail')) {
echo 'Looks like it is working';
} else {
echo 'Something has gone wrong';
}
?>
Variable names can not contain spaces.
$fmcg application=mysql_real_escape_string($_POST['fmcg application']);
Replace spaces with underscores ($fmcg application -> $fmcg_application)
If I kept the checkbox style, is there a way to make it invisible until the user until they want to see them?
Make them hidden (style="visibility:hidden;")
and a button somewhere that says something like 'Display delete checkboxes' and a javascript (called by onclick event) to change the visibility of all checkboxes to visible.
Are you sure that you will get better user experience this way? If you let users delete each post without asking them for confirmation first thea are at risk deleting too many posts to quickly. If you ask them for consfirmation at each post they wish to delete you will make them click a lot (it is better to get the user click the checkboxes, press the delete button and ask for confirmation for all the selected posts to be deleted). This is just my opinion, others might dissagree.
If you want to use a link (or any html element) to trigger deletion you have two ways:
- using javascript onclick event and deleting with ajax call to a php script (recommended, but think about confirmation)
- using a querystring with the id of the post to be deleted (not recommended). This technique is highly discouraged since poses a big security issue. The query string is easily changed so deleting all posts is trivial.
There are many tutorials out there but they might vary in completeness since they often omit some parts to emphasizes others. But your question is spot on. If I got it right you are asking about what to do with the posted values to use them securely.
The trim is actually a good function to get rid of extraneous spaces in before and after the actual text since the user might not be aware of them and they might cause some trouble. But more important is to escape and sanitize the data sent form the form.
The functions you will use depend on the context the value goes to. If you intend to store the value to a database, you tipically escape it (e.g. using mysqli_real_escape_string). If the value goes to the URL then you use urlencode function. If you stick the value into html use htmlspecialchars function etc.
You also have php filters you can use or filter_var.
And also you can also add your custom validating functions (e.g. for checking local phone numbers).
use mysql_real_escape_string() function to escape characters in all input fields. Not just to enable people to enter quotes but also to prevent evil people to enter harmfull code.
$title = mysql_real_escape_string($_POST['title']);
$content = mysql_real_escape_string($_POST['content']);
$creator = mysql_real_escape_string($_POST['creator']);
Mind you the connection to mysql has to be established in order to use this function. BTW: It is recommended to switch to mysqli extension.
should i keep these in while loop??? to increment after every question?
I don't think so. Since every question is on separate page the the evaluation happens only once on each page (while the user is on that page).
and how i can get total number of questions from DB?
By querying questions using COUNT(*).
$query = 'SELECT COUNT(*) FROM questions';
If each user gets the same number of questions this is enough. If there are other conditions use WHERE clause like:
$query = 'SELECT COUNT(*) FROM questions WHERE courseid=' . $course_id;
You have to know total maximum score which is total number of questions * 10 (I guess). Then when you have a score at particular question you just divide it with the total and multiply by 100. The result is the total percentage.
// ie you have 20 questions
$total_questions = 20;
$points_for_one_answer = 10;
$total_score = total_questions * $points_for_one_answer;
$score_percent = $score / $total_score * 100;
echo "your current score is $score_percent %";
$score is current score and I guess it is kept in session. It would be a good idea to display the number of answered questions and number of all questions:
echo "You have answered $number_of _answered questions out of $total_questions.";
I was away until just now. OK, so you will try it other way. My suggestion is that you first outline the logic with comments like:
// check if the user is authorised, if not, redirect
// if first question read the first question, correct answer and possible answers
// otherwise read the next question, correct answer and possible answers
// if user submitted the answer to the previous question store the answer
// compare the answers
// if the answer was wrong notify the user
// display the page
// ...
Once you have logic done start coding. It will be easier that way and to upgrade logic later. And separate the logic and the html output as much as possible.
Yes, you are right. The questions are getting displayed on the same page. This is set in the action attribute of the form:
<form action='start-course-evaluation-action.php' method='post'>
and could as well be:
<form action='#' method='post'>
and the above code should be part of this script. You have to add logic to evaluate and/or save the answers to the current question (probbably save them permamnently in a database or temporary in a session upon each submit). The logic should be somewhere on the beginning of the script.
Assuming that id is an integer and autoincremented by the DB then the id fields probably increase with every new question and you can use this approach:
Whenever you read and display the question save the id in the session. If there is no id in the session you are displaying the first question otherwise you just go for the next question. Also save the id of the last question so you know when to stop. The rest is documended in the code below (it should be a part of start-course-evaluation-action.php script):
// start the session
session_start();
// if this is the first run of your script
// the id has not been stored in the session yet
if(!isset($_SESSION['current_id'])) {
// this query will select the question with
// the lowest id, presumably the first one
$query = 'SELECT * FROM questions ORDER BY id ASC LIMIT 1';
// read the row, display the question as in the form as above
// the form can have action set to self (#)
...
// store the current id in the session
$_SESSION['current_id'] = $row['id']
// read the last id so you know when to stop
$query = 'SELECT id FROM questions ORDER BY id DESC LIMIT 1';
...
// store the last id in the session
$_SESSION['last_id'] = $row['id'];
// if current id exists in the session you can go and display the next qestion
} else {
// this query will read the question just after the current id
// …
My opinion: making your own database class might be worth only if you are doing it in order to learn about database handling and OOP. If you need a good and verstaile db class there are many arround which have been developed by dedicated people/teams and through considerable amount of time spent. I use Pear MDB2 class which has thousands of lines of code and works very well (OK, it still has some shortcommings). It is good to have a look at the source code there and you will find many good ideas like transactions, prepared statements, quoting, escaping etc. It abstracts database functions so they are usable for many different databases (mysql/mysqli, mssql, oracle ...).
In that case first check whether the firstname/lastname pair already exist:
$fname = mysql_real-escape_str($_GET['fname']);
$lname = mysql_real-escape_str($_GET['lname']);
$check_qry = "SELECT COUNT(*) FROM students WHERE fname='$fname' AND lname='$lname'";
If this query returns 1 (or more) rows the firstname/lastname pair is not unique.
While we are at it, the editors play some part here, too. If you are on windows have a look at Notepad++ (http://notepad-plus-plus.org). It is nice free editor that higlights html, css, javascript, php and others and makes mistakes stand out so they are easy to spot and correct. I prefer coding html by hand (not with WYSIWYG editors) so I exactly know what is going on.
// if values exist in $_POST (or $_GET if you use it)
if(isset($_POST['product_id']) && isset($_POST['country_id'])) {
// product ID
$product_id = $_POST['product_id'];
// begin the query
$query = 'INSERT INTO countries_product (coutry_id, product_id) VALUES ';
// add coutry ID's
foreach($_POST['country_id'] as $country_id) {
$query = "($country_id, $product_id),";
}
// remove trailing comma from the query
$query = rtrim($query, ',')
// execute the query
...
}
Add a bit of security checks to this. If IDs are integers it is good to cast them to integers to avoid SQL injection attacks.
$product_id = (int) $_POST['product_id'];
or use is_numeric checks
if(isset($_POST['product_id']) && is_numeric($_POST['product_id']) && isset($_POST['country_id']) && is_numeric($_POST['country_id']) ) {
...
}
I can not comment on Flash since I have never used it on my sites. I had an odd bad experience with sites using Flash in past (see note below) but that does not mean that I can criticize it right away. I think it is a tool to use for some special group of customers (musicians use it often maybe, and artists due of many possibilities for rich visual content and interacion) but more important these days is progresive enhancement (supporting many browsers), SEO friendlines (search engines find you and rank you high), maintanability, scalability, which are quite harder to reach with Flash.
HTML5 and CSS3 are still finding their places in web browsers. Together with Javascript these technologies will enable much more riches and probably do what Flash already does today. I think it is worth learnig them since they are standardized and not proprietary - but this is my personal view, I do not want to start new war :-)
Just a note: last night I was going to check on http://www.felixbaumgartner.com/ how preparations go for the maddest skydive in human history and saw only a black screen in my Firefox on Fedora linux. I had to hack for next quarter of hour to access the content which is in Flash.
Hi Tomas and welcome.
The answer is: Java is not neccessary. To create a website, theoreticaly, HTML is enough. In practice CSS is a must also (to make page look nice and to de-couple contents and design) as well as Javascript (to do many client side things like form validation etc). Now, more complex web applications deal with data which will bring you to server side scripting and databases. Here, Java can be used a sa a server side tecnology, it is powerful and professional web server platforms exist. But I am not really knowledgeable here, I use PHP - avery popular server scripting language. Others are Ruby, ASP variations etc. On the database side MySql is very popular since it is opensource (free) and widely supported. But you are not limited to mySql if your company owns (or you are skilled in) some other DB system.
In other words: Java or not Java: there is a lot to learn (continously).
Have you tested what are the values are in the $_GET? Are they comming from a form or you construct a URL + query string some other way? You should always check for posted values:
if(isset($_GET['file']) && isset($_GET['image'])) {
$file = $_GET['file'];
$image = $_GET['image'];
} else {
// handle error as apprpriate for your app
// i.e die...
die('Error: File or image missing!');
}
OK, I get it. You want to sum the total price for a product coe and a selected date, I guess. The query should be something like:
$query = "SELECT *, SUM(total_price) AS sum_total_price FROM order WHERE date = '$date' GROUP BY product_code ";
As you can see you can get the result just by preparing appropriate query. You might want to ask also in a mysql forum here on DW if you need more complex queries.
If by email brodcast you mean sending mail to many recipients using php then look at swiftMailer.
@Bachov Varghese
Your solution is more elegant, good stuff. The query could be made in one go as well:
if($_POST['add_marks'] ==1)
{
include('includes/connect.php');
$bots =$_POST['bot'];
$mts=$_POST['mt'];
$eots=$_POST['eot'];
$insert = "INSERT INTO marks(beginning_of_term,mid_term,end_of_term) VALUES ";
foreach($bots as $key=>$bot)
{
$insert .= "('$bot','$mts[$key]','$eots[$key]'),";
}
insert = rtrim(insert, ',');
$execute_insert = mysql_query($insert);
}
I am not sure if I understand th question correctly:
- on a webpage you have a table of students with their name, reg. no, cals etc and three input fields do BOT, MOT and EOT marks
- you get student data (except for marks) from the students table
- input fields are initialy empty
- someone fills in the values for marks and you want to insert those marks into the marks table
If this is correct then first thing you have to enclose the whole table in form tags:
<form method="post" action="proces.php">
Then you have to correct the name attributes for input fields. They have to be unique and tied to a student. You can use regNo field for that. Also add a hidden field in each row that will hold the regNo:
<?php
// construct the name attributes for the current row
$bot_name = 'bot-' . $rows['regNo'];
$mt_name = 'mt-' . $rows['regNo'];
$eot_name = 'eot-' . $rows['regNo'];
// the name for the hidden field with the regNo
$reg_name = 'reg-' . $rows['regNo'];
?>
<!-- This is one row of a table -->
<tr bgcolor="<?php echo $bg; ?>">
<td><?php echo $rows['firstName']." ".$rows['lastName']." ".$rows['otherName']; ?></td>
<td><?php echo $rows['regNo']; ?></td>
<td><?php echo $rows['class']." ".$rows['stream']; ?></td>
<td><div align="center"><input type="text" name="<?php echo $bot_name; ?>" size="10" />
<input type="hidden" name="<?php echo $reg_name; ?>" value="<?php echo $rows['regNo']; ?>" /></div></td>
<td><div align="center"><input type="text" name="<?php echo $mt_name; ?>" size="10" /></div></td>
<td><div align="center"><input type="text" name="<?php echo $eot_name; ?>" size="10" />
</div></td>
</tr> …
a
and t
are format characters in the date function. If you want to use them as text (literally) you must escape each of them.
A suggestion regarding security: for operations that modify database rows (e.g. delete) it is a bit safer to use POST method instead of encoding IDs in the query string. The user could change the id of the records easily to delete other records.
if(isset($_SESSION['username']) && $_SESSION['username'] == $post['username']) {
echo '<form method='post' action='delete.php'>'
echo "<input type='submit' name='{$post['id']}' value='Delete' />";
echo '</form>';
...
}
Mind you, POST data can be easily forged, too, so it is important to check for the username also in the delete.php and edit.php scripts and employ other security measures.
Each post has to be associated with the user ID (the ID of the user that authored it). I presume user ID is also stored in the session. So when you display posts you check each post to whom it belongs and if it belongs to currently logged-in user also display delete button.