broj1 356 Humble servant Featured Poster

I think a little bit of optimization can be done using prepared statements:

...
// define the query with ? in places of variables
$query = "UPDATE registrar_grade_archive 
SET grade = ? 
WHERE student_id = ? 
AND subject_id = ? 
AND school_id = ? 
AND advisor_faculty_id = ? 
AND subject_handler_id = ?";

// prepare the query
$stmt = mysqli->prepare($query);

// loop through array of variables
foreach ($student_grades_boy as $key=>$data) {

    $student_id_B= $data['studnt_B_id'];
    $grade_B = $data['studnt_grade_B'];

     // bind parameters to the query for each loop
     // I assume here that all parameters are integers
     $stmt -> bind_param(
         "iiiiii",    // set parameter types (all integers here)
         $grade_B, 
         $student_id_B,
         $subject_id,
         $school_id,
         $faculty_id,
         $subject_handeler_id
     );

    // execute the query for this loop
    $result = $stmt -> execute();

    if(!$result) {

        die ('Error updating the database.');
    }
}

You get slighly better performance this way and quite a lot of security since prepared statements are great way of preventing injections.

Please note I have used the newer mysqli extension since the older mysql extension (which you are using) does not support prepared statements to my knowledge.

I haven't actually tested above code (since I am using PEAR MDB2 for cases like this) so please somebody have a look at it too and correct me if I am wrong.

broj1 356 Humble servant Featured Poster

The value you are getting is a Unix timestamp which is time expressed in number of seconds after 1.jan. 1970. You can convert from/to Unix time here. The fact is that php date function uses unix timestamp and has ways of converting it to variety of formats, as Bachov Varghese posted above. And be careful, mysql timestamp differs from unix timestamp so do not mix them.

Hope I added a bit of clarification, not confusion.

broj1 356 Humble servant Featured Poster

Good practice when working with processing forms is to check if the value has been entered first and then also clean the input using htmlspecialchars function (i.e. to prevent nasty users to inject scripts or html code in input box):

<!-- php file -->
<html>
<head>
<title>Reading Data from text fields</title>
</head>
<body>
<h1>Reading Data from text fields</h1>

<?php
if(isset($_POST['data']) && !empty($_POST['data'])) {
    // clean the input so it is safe to be inserted in html code
    $data = htmlspecialchars($_POST['data']);
    echo 'Thanks for Answering, ' . $data;
} else {
    echo 'You did not input anything!';
}
?>
</body>
</html>

To debug put this on first line of PHP code:

die(print_r($_POST, 1));

It will display all the values that have been sent over in a $_POST array and stop execution of script so you can do examination.

broj1 356 Humble servant Featured Poster

To give you some ideas:

  • as simplypixie said, use an autocrement type for the ID field in the database table; this way the IDs will get generated automatically, will be unique and you do not have to wory about them
  • when you fetch the data use mysqli_fetch_array function which fetches each row in an associative array so you can address each field by it's associative index which is the same as the field name
  • use newer mysqli extension instead of the older mysql exstension to deal with database

If you use a web form to fetch the data, users will usually input the name, nationality, profession or some similar data, not the ID. So the query will be something like:

// since the information comes from the untrusted source (a web form)
// you have to at least escape it using [mysqli_real_escape_string](http://php.net/manual/en/mysqli.real-escape-string.php)
$name = mysqli_real_escape_string($_POST['name']);

$query = "SELECT * FROM tablename WHERE name LIKE '$name'";

The fields in the form should have name attributes that are the same as field names in the table; that will make your life easier.

broj1 356 Humble servant Featured Poster

You construct links to files when displaying the table.

// path to pdf files (including backslash/slash)
$path = 'whatever/';

// the icon
$icon = '<img src="pathtotheicon" alt="PDF File">';

while ($row = mysql_fetch_array($result)) {

    $file = $row['file'];

    echo "<tr>";
    echo "<td>" . $row['name']."</td>";
    echo "<td >" . $row['email']."</td>";
    echo "<td >" . $row['apptype']."</td>";
    echo "<td >" . $row['description']."</td>";
    echo "<td >$icon <a href=\"$path{$file}\">" . $file . "</a></td>";
    echo "</tr>";
}

By clicking a link the user will be able to download (or open) the file.

broj1 356 Humble servant Featured Poster

OK, while typing the answer to your post, your question changed, so never mind my post above.

broj1 356 Humble servant Featured Poster
// check if form has been submitted:
if(isset($_GET['submit'])) {

    // establish a DB connection (assuming mysql)
    ...

    // check if the appropriate category has been selected
    // and escape it
    $category = mysql_real_escape_string($_GET['category'])

    // construct the query
    $q = "SELECT * FROM theTable WHERE category='$category'";

    // get the result
    ...

    // do whatever else is neccessary (handle errors, redirect?)
    ...
}

// put the html here including the form code
// decide what the action is (GET in this example)

To make form autosubmit google for form autosubmit. This is one link.

broj1 356 Humble servant Featured Poster

Sorry, my mistake in the post before your last question. If we want to use $style variable in the printf statement, the parameter should be enclosed in double quotes (and normal double quotes escaped):

printf("<tr><td align=\"center\" style=\"$style\">%s</td><td align=\"center\" style=\"$style\">%s</td></tr>", $fullname, $myrow['TotalPoints']);

One more edit: if the table borders are not collapsed it is better to aplly styles to <tr> tag as szabisz suggested:

printf("<tr style=\"$style\"><td align=\"center\">%s</td><td align=\"center\">%s</td></tr>", $fullname, $myrow['TotalPoints']);
broj1 356 Humble servant Featured Poster

The order of applying styles is something like:

  1. the browser default styles
  2. the styles in external css files (if exist) override browser default styles
  3. the styles in head head override previous two (if either exist)
  4. the inline declaration overrides any other (if any exist)
  5. the @important modifier overrides most if not all of others
broj1 356 Humble servant Featured Poster

szabizs gave you excellent example in his post above. I am merely adapting it to your code:

} else {

    // counter for rows
    $currentRow = 1;

    while ($myrow = mysql_fetch_array($pnts)) {
        $sql = "SELECT * FROM `Player` WHERE `PlayerID` = " . $myrow["PlayerID"];
        //echo $sql;
        $playerar = mysql_query($sql);
            if ($playerfetch = mysql_fetch_array($playerar)) {
            $fullname = $playerfetch["FirstName"] . " " . $playerfetch["LastName"];
        }

        // define style depending on which row we are in
        $style = $currentRow <= 6 ? 'border: 1px solid green;' : 'border: 1px solid black;';

        // print the row using appropriate style for cells (or you can use it for rows)
        printf('<tr><td align="center" style="$style">%s</td><td align="center" style="$style">%s</td></tr>', $fullname, $myrow["TotalPoints"]);

        $currentRow++;
    }
}
broj1 356 Humble servant Featured Poster

Is the problen a layout or the appearance of the form elements? I think you should experiment using css / tables. I also guess the outcome might depend on browser used.

broj1 356 Humble servant Featured Poster

First, I need the result of the function to first print out the results like so:

For this use the implode function:

echo implode(',', getArrayUsers($id));

The second part of the question I do not quite understand. Can you reword it?

broj1 356 Humble servant Featured Poster

Can you comment out the die statement on line 16 and insert this debug code after line 20 (in the beginning of the while loop):

if($vrow['added_on'] <= 0) {

    die($vrow, 1));
}

This will output the value of the $vrow in a case where $vrow['added_on'] equals 0 or less than 0. You have to investigate that row then. Please post the result here if you do not manage to debug the error yourself.

broj1 356 Humble servant Featured Poster

Enclose the datepicker in div tags with id (i.e. datepicker-wrap) and assign a function to a onclick event of the radio button

function toggleVisibility(id) {

    var element = documentGetElementByID(id);
    element.style.visibility = element.style.visibility == 'hidden' ? 'visible' : 'hidden';
}

Or you can use jQuery toggle method.

broj1 356 Humble servant Featured Poster

If the above code is html (not php) then you have to do it this way:

<input type='radio' name='choice_a' value='<?php echo $answer;?>'>
<input type='radio' name='$quiz_no' value='<?php echo $answer;?>'>

To pass this to another php file for checking / processing enclose fields in form tags and set action attribute (and add a submit button):

<form action="anotherfile.php" method="post">
<input type='radio' name='choice_a' value='<?php echo $answer;?>'>
<input type='radio' name='$quiz_no' value='<?php echo $answer;?>'>
<input type="submit" name="submit" value="Submit">
</form>
broj1 356 Humble servant Featured Poster

Can you post the whole code.

broj1 356 Humble servant Featured Poster

The simplest way of doing it would be using separate rules for printing using print media type.

broj1 356 Humble servant Featured Poster

Depending on how you intend to use the numbers they could be also in one two-dimensional array:

// using italian in this example since I do not speak marathi :-)
$number2words = array(
    1 => array('english' => 'one', 'italian' => 'uno'),
    2 => array('english' => 'two', 'italian' => 'due'),
    3 => array('english' => 'three', 'italian' => 'tre'),
);

echo '2 is ' . $number2words[2]['english'] . ' in english and ' . $number2words[2]['italian'] . ' in italian.';

If you have a big range of numbers then you have to make up some more clever logic to display numbers with words (like interpreting hundreds, thousand etc).

broj1 356 Humble servant Featured Poster

If I understand the question correctly you would like to suplement numbers with words in two languages. I would do that with arrays. If the range of numbers is not too big you can map numbers to words directly:

$englishWords = array(
    1 => 'one',
    2 => 'two',
    3 => 'three',
    1 => 'four',
    5 => 'five',
)

$marathiWords = array(
    1 => 'one in marathi',
    2 => 'two in marathi',
    3 => 'three in marathi',
)

echo '2 is ' . $englishWords[2] . ' in english and ' . $marathiWords[2] . ' in marathi.';
broj1 356 Humble servant Featured Poster

Do you do any checking on dates that come from the form i.e. are the dates in correct format or is date2 >= date1 etc? I suggest you put the debug code just after the SQL statement:

$vquery="SELECT * FROM rt_transaction WHERE added_on>=Unix_Timestamp(".$date1.") AND added_on<=Unix_Timestamp(".$date2.") AND rt_owner_id='".$_POST['owner']."'";

// DEBUG
die($vquery);

This code will display the query and stop the script. Please test the displayed query in phpmyadmin or mysql client (assuming you use mysql) or post it here.

broj1 356 Humble servant Featured Poster

If you want to secure the form field values during the transmission from the browser to the server you can use HTTPS.

broj1 356 Humble servant Featured Poster

What is the query that reads the values from the database? Does the value exist in the added_on column? Does any data for the query come from a form?

broj1 356 Humble servant Featured Poster

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.

broj1 356 Humble servant Featured Poster

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.

broj1 356 Humble servant Featured Poster

How can i use WHERE clause to get result.I required in a project

What is the SQL now, what are conditions?

broj1 356 Humble servant Featured Poster

How can i get result between two date from database where date is in unix timestamp

// result in seconds
$difference = $date2 - $date1

Convert seconds to whatever you want.

broj1 356 Humble servant Featured Poster

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)";
diafol commented: good spot +14
broj1 356 Humble servant Featured Poster

First test whether the form was submitted i.e by checking for the existence of $_POST['submit'] (or whatever you name the submit button).

if(isset($_POST['submit'])) {

    // do all the assigning of $_POST to variables here and querying

} else {

    // display the form or redirect to a page with the form here
}

You also can't be sure that all $_POST array elements contain values so you have to test each element. If any particular element has no value (i.e user did not fill-in all the fields in the form) then you have to either provide a default value or handle the error.

// example of providing default value
if(isset($_POST['subject'])) {
    $subject=$_POST['subject'];
} else {
    $subject = '';
}

// example of handling the error
if(isset($_POST['number']) && is_numeric($_POST['number'])) {
    $number=$_POST['number'];
} else {
    header('location:error.php');
}
// do this for each element of a $_POST array
...
broj1 356 Humble servant Featured Poster

There are many closing </a> tags without the opening <a> tag in your table cells. Has this error happened during the copy/paste operations? On line 61 you have a typo <td nowarp> should be <td nowrap>.

broj1 356 Humble servant Featured Poster

The javascript function ConfirmChoice() should should be somehow told the ID of the user to delete. It could be read from the chosen option of the select element. So the select element should be assigned an ID (for accessing with javascript) and the options have to have values:

<tr><td><select name="id" id="user-id">

while ($row4 = mysql_fetch_array($result1)) {
    // for readability I assigned $row4[ID] to $userID variable
    $userID = $row4[ID];
    echo "<option value='$userID'>$userID</option>\n";
}

In the function ConfirmChoice() you first read the chosen value of the select element and then add it to the url as a query string.

<script type="text/javascript">
function ConfirmChoice()
{
    // assign the select element to userSelectElement
    var userSelectElement = document.getElementById('user-id');

    // read the chosen value
    var userID = userSelectElement.options[userSelectElement.selectedIndex].value;

    answer = confirm("Do you really want to Delete?")
    if (answer !="0")
    {
        // add a querystring to the url
        location = "deleteuser.php?id=" + userID
    }
}

Then you have the userID in the $_GET['id'] (which you test for) and use it in your query.

But it is safer to use POST for deleting users instead of GET which means use form tags as R0bb0b suggested, set method to post and do not use javascript since I do not think it is necessary.

broj1 356 Humble servant Featured Poster

I am not sure if methods __sleep() and __wakeup() have any usability here. You are making a connection in the constructor already so why have another method to do it again? And what is the purpose of the __sleep() method?

broj1 356 Humble servant Featured Poster

The connect function lacks the connection functionality and lacks a returns statement. You should add a connect function mysql_connect which returns a valid link (or an error):

 private function connect()
{
    $this->link = mysql_connect($this->server, $this->username, $this->password);
    $result= mysql_select_db($this->db, $this->link) or die('sql error');
    return mysql_connect() or die('Could not connect: ' . mysql_error());
}

And a suggestion: it is recommended to use mysqli extension which is newer and better supported than mysql, which is going to be dropped at some stage.

broj1 356 Humble servant Featured Poster

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.

broj1 356 Humble servant Featured Poster

Also in the second link there might bi an error in the URL's directory:

<li class="menu"><a href="mew1/index.php">Hot</a></li>;

Didi you really mean mew1?

broj1 356 Humble servant Featured Poster

Welcome on DW from me too. There is a nice article here about how to participate on the forum (this or any other) to get the most out of it. We will be more than glad to help once we get a proper question.

broj1 356 Humble servant Featured Poster

This is not strictly a PHP question, maybe it would be better to seek help in HTML forum on DW. But anyway, html code seem to be OK. Check whether the paths in the href attribute are correct. What exactly does happen when you click on particular link?

broj1 356 Humble servant Featured Poster

When you use values from forms in your query best practices are:

  • check for existence of values
  • validate entered values for correct type/value
  • escape the values to prevent entering bad characters (like ')

    // check if there is a value in the request
    if(isset($_REQUEST['tid']) && !empty($_REQUEST['tid'])) {

        // cast to integer if you are expecting integer
        // escape if you are expecting string
        // $tenantID = (int) $_REQUEST['tid'];
        $tenantID = mysql_real_escape_string($_REQUEST['tid']);
    
        // then use the value in query
        $query_recTenantID = "SELECT * FROM md_tenant WHERE tenantID = ".$tenantID;
    
        // display the rows
        ...
    

    }

broj1 356 Humble servant Featured Poster

This has nothing to do with a type of for loop you use. The best thing to do is to use a CSS. To get table positioned in the midle just set left and right margins to auto:

echo "<table border='1' style='margin: 0 auto;' ><tr><th>Payment</th><th>Date of payment</th><th>Payment</th><th>Date of payment</th><th>Payment</th><th>Date of payment</th><th>Payment</th><th>Date of payment</th></tr>";

while ($row = mysql_fetch_array($result)){
    echo "<tr>";
    for($i=1;$i<9;$i++){
        echo "<td>".$row[$i]."</td>";
    }
    echo '<td><a href="apagar.php?id_dados='.$row['id_despesa_casa'].'">DELETE</A>';
    echo '<td><a href="editar.php?id_dados='.$row['id_despesa_casa'].'">EDIT</A>';
    echo "</tr>";
}
echo "</table>";

You could also do it in an external stylesheet which is usually recommended.

broj1 356 Humble servant Featured Poster

Unformated in what way? What is the result you would like to achieve?

broj1 356 Humble servant Featured Poster

Your approach is completely OK, I think most of people do it this way. You start a html table, display a header row and then loop through the resultset from a mysql query and display each row, adding a delete and edit links. The only thing that could be done in a safer way is the for loop which would be better if it was done with a foreach loop:

while ($row = mysql_fetch_array($result)){
    echo "<tr>";
    foreach($row as $field){
        echo "<td>".$field."</td>";
    }
    echo '<td><a href="apagar.php?id_dados='.$row['id_despesa_casa'].'">DELETE</A>';
    echo '<td><a href="editar.php?id_dados='.$row['id_despesa_casa'].'">EDIT</A>';
    echo "</tr>";
}

Why is the foreach loop safer? Well, mainly because you do not have to worry about how many fields you have in one row. The foreach will loop through all of them. When you use a for loop you have to know the number of fields so you can set the iterration count (from 1 to 8 in your case) which can lead to errors.

broj1 356 Humble servant Featured Poster

You have posted your post about the resolution of the problem just seconds before my post where I was trying (more or less blindly) to suggest how to go about it. Anyway, is your problem resolved now?

Next thing I will do in near future is starting to explore MVC (thanks also to your post). I already started trying Yii some time ago but haven't got far due to lack of time. Maybe I'll carry on with it from where I stopped.

broj1 356 Humble servant Featured Poster

I suppose it is time to start learning MVC approach ASAP :-).

So if you need to pass an array of strings over wouldn't it be ok if you build the $finalarray just as numeric array

foreach($disparray as $item)
{
    $finalarray[]=implode("|",$item);
}

and then you can use it as intended? I am not sure if that completely answers your question or solves the problem. Maybe MVC gurus on the form can help.

broj1 356 Humble servant Featured Poster

I am not familiar with Codeigniter but it seems that in the last foreach loop you are overwriting the same element ($finalarray["row"]) over and over again:

$finalarray["row"]=implode("|",$item);

I do not know what the end result should be. If it should be string then you should use concatenation. If on the other hand array is expected, you should change the associative index for each iterration or add numeric indices.

broj1 356 Humble servant Featured Poster

Please help me in understanding (action="?op=login") part

This means that the form will be submitted to the same page with the query string op=login appended to the URI. So if the page with the form is http://www.mydomain/login.php the action goes to http://www.mydomain/login.php?op=login, which in turn means that $_GET array will contain an 'op' element after the form submition

$_GET['op'] = 'login';

which you can test for and use in your code (which is actuall done on line 5).

broj1 356 Humble servant Featured Poster

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.

Zagga commented: Nicely explained +4
broj1 356 Humble servant Featured Poster

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.

broj1 356 Humble servant Featured Poster

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).

broj1 356 Humble servant Featured Poster

And what does the sanitize function do? Does it work correctly?

broj1 356 Humble servant Featured Poster

Another desperate try: have you tried to echo the query in the login function:

function login($username, $password)
{
    $user_id = user_id_from_username($username);
    $username = sanitize($username);
    $password = SHA1($password);
    $query = mysql_query("SELECT COUNT(user_id) FROM users WHERE userName = '$username' AND password = '$password'");

    // DEBUG
    die($query);

    return(mysql_result($query, 0) === 1) ? $user_id : false;
}

Does the query look OK (is user_id correct, is $password actually a hash)? Does the output query work OK in phpmyadmin if you copy it there?

broj1 356 Humble servant Featured Poster

I am not sure if this is important: sha1() function should be in lowercase. Can you try

$password = sha1($password);