broj1 356 Humble servant Featured Poster

Another way of doing it:

Frst initialize the variables to empty string:

$search_policy = '';
$search_surname = '';
$search_name = '';

Then you assign a condition to any of the variables if $_POST element exists, as you have done it.

On lines 43 to 45 chremove the else bit from:

else {
    $sql = "SELECT * FROM tblclients WHERE clientID > 0".$search_policy.$search_surname.$search_name;
}

to:

$sql = "SELECT * FROM tblclients WHERE clientID > 0".$search_policy.$search_surname.$search_name;

That is how the conditions or empty strings will be added to the query.

@ahmedhamdy: your solution will work only if all three boxes have been filled-in and I am not sure if ngonix wants that.

broj1 356 Humble servant Featured Poster

Also a database offers better security of the data.

broj1 356 Humble servant Featured Poster

If the requirement is that the page does not change (reload) and you want to display a form, update a database and display a status of the operation, then you have to use ajax. This is how I would do it:

  • the form would be initially hidden
  • if user clicks Add news, the form gets displayed (you've got this covered already)
  • the button for submitting calls a validation function first to check for entered information
  • if the information is OK, the database gets updated through ajax call to a separate PHP page that handles the update
  • if the update is OK, the PHP returns success, otherwise it returns failure
  • the status gets displayed in another div using jquery:

    • if information was OK and update successful succes is displayed
    • if information is OK but update failed, some other message can be displayed
  • if information wasn't OK, the message to complete the information is displayed

It maybe sounds confusing but you have to structure the scripts appropriately and maybe put javascript/jquery functions in a separate file.

broj1 356 Humble servant Featured Poster

Display the queries and check them in phpmyadmin (and post here if you do not find an error). Insert this code after line 46 but before the closing curly bracket:

echo "SQL: $sql<br>SQL1: $sql1<br>SQL2: $sql2<br>SQL3: $sql3<br>SQL4: $sql4";
broj1 356 Humble servant Featured Poster

On line 14

('$_POST[title]',''$_POST[discription]','$_POST[content]')";

you have two single quotes so the query syntax is wrong. Remove one of them.

Edit: haven't noticed that LastMitch has already pointed that out, sory.

broj1 356 Humble servant Featured Poster

You can save values in a txt file, JSON format would be a good one. You can use json_encode and json_decode functions. Instead of JSON you can just serialize data into a txt file.

broj1 356 Humble servant Featured Poster

U R welcome :-)

broj1 356 Humble servant Featured Poster

You are welcome. Please mark this thread as solved. If you have more questions open a new thread. Happy coding.

broj1 356 Humble servant Featured Poster

The form does not have to be loaded from a separate php file. It can be in a div that is initially hidden (say the id is form-container) and when the user clicks the Add News Item link the div is shown using jquery show() method.

$(document).ready(function(){
    $("#news").click(function(){
        $("#form-container").show();
    });
});

Change the button in the form from type="submit" to type="button" since you do not want to submit the form (and go to the action page). Give the button an ID (say id="send-data") and with jquery call a function that will validate the form and with ajax call the php script for updating or display an error message in a error div.

broj1 356 Humble servant Featured Poster

I have a question though, what did you mean about the categories code?

Just an idea. One possibility would be that a user wants to see all categories, so chosing a category would be only an option. The default would be that no category is chosen. But it is your preference if category is required.

Also, should I stop using echo ERROR and just do die from now on and why?

In your original code you would never see the error message displayed since immediatelly after echoing it you would be redirected to index page. If you use die, redirection does not happen. I would do it differently. If an error occurs (which I guess is not often) I would redirect to a special error page with simple explanation and links to other pages.

broj1 356 Humble servant Featured Poster

Line 47:

$stmt->bind_param("ssi", $category, $title, $director, $year, $id);

You have declared only three types but you have five parameters. Try:

$stmt->bind_param("sssii", $category, $title, $director, $year, $id);

And change the line 54 to

die("ERROR: could not prepare SQL statement.");

so the script is stopped if error occurs (now you immediately get redirected to index).

broj1 356 Humble servant Featured Poster

Double quote is missing after the value attribute. Have you copied the code form my post correctly? It works in my browser, I have tested it.

broj1 356 Humble servant Featured Poster

Something is wrong in HTML. If you check the HTML code for the radio buttons. Can you have a look at the HTML code (right click in web browser and select View source or something similar) and post the code for radio buttons.

broj1 356 Humble servant Featured Poster

Let's see what gets POSTed over. Can you insert this code immediatelly after line 24 and post the result after submitting the form:

die(print_r($_POST, 1));

This will display values in $_POST and terminate the script.

broj1 356 Humble servant Featured Poster

Have you tried the code form my first post (the one immediately after your post)?

broj1 356 Humble servant Featured Poster

Is category a required information? If category has not been chosen (user wants to se all categories) you have to provide for that situation:

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

    $category   = $_POST['category'];

} else {

    $category = 'All';
}

// handle the all categories situation
...
broj1 356 Humble servant Featured Poster

Shouldn't you read the ID from URL ($_GET)?

$id         = $_POST['id'];

on line 26, should be

$id         = $_GET['id'];
broj1 356 Humble servant Featured Poster

You can create radio buttons with PHP. Put categories in an array, cycle through it, add code for radio buttons and check if current category matches the one from the DB:

<?php
// array of categories (you can always edit it and the radio buttons will change)
$categoriesArr = array('Action', 'Comedy', 'Drama', 'Horror', 'Thriller');

// add radio buttons via php and add checked attribute for the selected categpry
foreach($categoriesArr as $cat) {

    echo '<input type="radio" name="category" value="' . $cat  . '"';

    if($cat == $category) {

        echo ' checked="checked"';
    }

    echo ' />' . $cat;
}
?>

The code above should replace the code on lines 112 to 116.

broj1 356 Humble servant Featured Poster

Looks like the else statement on line 54 hasn't got a closing curly bracket. I you put one say on line 73 the error is gone. Double check though if that is the intended place for it.

broj1 356 Humble servant Featured Poster

OK. There are two things that vome to my mind:

  • there is some outbut (mybe a space or newline) before session_start(). Make sure session_start() on the very top of the script and nothing else is before it.
  • your php.ini has session.cache_limiter set up incorrectly, try setting it to:

    session.cache_limiter = public

(found this on google, not sure if it solves the problem of yours)

broj1 356 Humble servant Featured Poster

There is another issue with your code. If a user enters spaces or ampersands or < or > or similar unwanted characters in the input box you should not pass that to the URL unencoded so use at least encodeURIComponent function before sending data to ajax.

$.ajax({

    type: "POST",
    url: "edit.php",
    data: encodeURIComponent(dataString),
    success: function(){
    $('.success').fadeIn(200).show();
    $('.error').fadeOut(200).hide();
    }
}); 

On the PHP side decode it back (i.e. using urldecode) and escape it properly to avoid attacks to your database or browser.

OsaMasw commented: thanks +2
broj1 356 Humble servant Featured Poster

There are other small errors in the code as well so this is now the correct code (slightly reformated):

<script type="text/javascript">
$(function() {

    $(".editname").click(function() {

        var recordId = $(this).attr('id');
        var name = $('#tx_id-' + recordId).val();

        // tried to put # and nothing works
        var dataString = 'name='+ name + '&id=' + recordId ;

        if(name=='' || recordId=='' ) {

            $('.success').fadeOut(200).hide();
            $('.error').fadeOut(200).show();

        } else {

            $.ajax({

                type: "POST",
                url: "edit.php",
                data: dataString,
                success: function(){

                    $('.success').fadeIn(200).show();
                    $('.error').fadeOut(200).hide();
                }
            });    
        }

        return false;
    });    
});
</script>

The errors were in brackets, and the ID of input was misspelled (txt_id instead of tx_id).

OsaMasw commented: working as charm +0
broj1 356 Humble servant Featured Poster

My mistake - a typo in the jquery code. Change line 11 from:

var recordId = $(this.attr('id'));

to:

var recordId = $(this).attr('id');

Note the change in brackets :-).

broj1 356 Humble servant Featured Poster

Let me repeat to see if I understood:

You want to generate unique keys yourself (IOW mysql autoincrement is not OK for your purpose). What is the format of the key and what are the rules for constructing the key?

then the new one created key must be from deleted keys

If this is the requirement then you have to keep the list of the deleted keys. If you keep it in a database table then just query for first available key.

broj1 356 Humble servant Featured Poster

Just a note on quoting strings. It has nothing to do with the error you are getting, just a suggestion. Instead of:

echo "As \"" . $row["alias"] . "\"||";

you can do either:

echo "As \"{$row["alias"]}\"||";

or

echo 'As "' . $row["alias"] . '"||';

It is slightly more readable and easier to debug. But it is your choice what you prefer.

broj1 356 Humble servant Featured Poster

On line 5 you are assigning the same value to $result over and over again.

$result = mysql_query("SELECT * FROM tag WHERE point='$pagename'");

so while($row = mysql_fetch_array($result)) condition is always true (it is always first row of the table). I would remove line 5.

The $result on line 9n is also causing trouble. What is the goal here? Maybe you post the database structure.

IIM commented: Nice pin point +5
broj1 356 Humble servant Featured Poster

The trouble is in your first line:

// index.php
<?php
session_start();
ob_start();
?>

You use php comment outside of <?php ?> block so it is not treated as php code but as html code. That means that you send html before calling session_start() and ob_start() which is incorrect since both functions have to be started before ANY output is sent. Simply remove the first line or put it within a <?php ?> block.

<?php
// index.php
session_start();
ob_start();
?>
broj1 356 Humble servant Featured Poster
$query = "SELECT SUM(quanitity) FROM `tablename` GROUP BY `year`";

Backquotes might also be important if you use names that are same as mysql keywords.

LastMitch commented: Good Answer +11
broj1 356 Humble servant Featured Poster

Have a look at this article:

http://www.daniweb.com/web-development/javascript-dhtml-ajax/threads/447144/autoseggestion-styling

You will find a concept there. It is a bunch of texts to read but it is good if you get an idea how it goes. Then try to code it and when you have troubles come back here. Maybe it would be a good idea to start a new thread since this one has been marked as solved. If you start a new thread please PM me, otherwise I might not notice it.

Also have a look at these links for jquery plugins that do this functionality:

http://www.devbridge.com/projects/autocomplete/jquery/
http://www.daniweb.com/web-development/javascript-dhtml-ajax/threads/447144/autoseggestion-styling

broj1 356 Humble servant Featured Poster

So at the moment i am trying to make it easier for the user to fill in forms so that they don't have to manually type in the fields

Now you have an input box where only one name/surname can be displayed. But in cases like yours I think the practice is to display a list of matches which gets shorter the more characters you type in. So the principle is:

  • on keyup event you shoot the ayax and read the matches for whatever is currently typed in an input box
  • ajax returns an unordered list (<ul></ul>) of matches into a designated div
  • you use CSS to position the list directly under the textbox and shape it appropriately
  • usually the ajax does not get fired on first letter but once you have say three letters or more

I hope I guessed right what is your intention, please correct me if I am wrong.

broj1 356 Humble servant Featured Poster

You could use lenght property to check for the second element:

if(nameAndLastnameArray.length > 1) {
    // insert name into appropriate box
    document.getElementById("displayDiv1").value=nameAndLastnameArray[0];
    // insert lastame into appropriate box
    document.getElementById("displayDiv2").value=nameAndLastnameArray[1];
} else {
    // insert empty string into boxes
    document.getElementById("displayDiv1").value='';
    document.getElementById("displayDiv2").value='';
}

But I do not know whether this is the way you want to do it.

broj1 356 Humble servant Featured Poster

I guess because the nameAndLastnameArray[1] does not exist (is undefined) when removing. Can you describe what is the purpose of the page and the form.

broj1 356 Humble servant Featured Poster

You are returning only the name in a message not alsoo the lastname. Add lastname also and separate the name and lastname so you can distinguish them when returned from ajax cal, maybe with comma:

    ...
    while($nt=mysql_fetch_array($t)) { error_reporting(0);
        $msg.= $nt[name] . ',' . $nt[lastname];
    }
}
echo $msg;

On html page insert the name and lastname:

// split the returned string into array of name and lastname
nameAndLastnameArray = value=httpxml.responseText.split(',');

// insert name into appropriate box
document.getElementById("displayDiv1").value=nameAndLastnameArray[0];

// insert lastame into appropriate box
document.getElementById("displayDiv2").value=nameAndLastnameArray[1];
broj1 356 Humble servant Featured Poster

Are you sure the second and third SELECT keywords have to be there. Would this be OK:

$bquery="SELECT * FROM rt_booking WHERE rt_unit_id='".$_POST['unit_id']."' 
AND (UNIX_TIMESTAMP(str_to_date(rt_start_date,'%Y-%m-%d'))>=".$my11." 
OR UNIX_TIMESTAMP(str_to_date(rt_end_date,'%Y-%m-%d'))<=".$my22.")";
broj1 356 Humble servant Featured Poster

Put this temporary debug code on line 3:

die("UPDATE $title SET arole = CONCAT_WS(',', arole, '$name') WHERE op = '$name'";);

Your query will get displayed with actual values. Copy it to the SQL window of phpmyadmin and see what you get when you run it. If there are errors you will get error messages there that will help you solving the problem.

broj1 356 Humble servant Featured Poster

Sorry to keep running in circles but I am trying to get what is the purpose of all this. Please confirm that:

  • you read data about the courses from the courseinfo table and display information about one course (depending on the course ID)
  • you would like to save all of this same data about one course into batchinfo table which is another table in the same database

If this is true be aware that this is duplication of data and against the normalization rules. But you can do it. Please confirm that I see it correctly.

broj1 356 Humble servant Featured Poster

Repeating my question: what is the trigger to do insert? If there is no trigger other than displaying the table, then you can do it in the batchinfo1.php script. But this database would not be normalized in other words you will get duplicate values in the courseinfo and batchinfo tables which is not the right way of doing it.

broj1 356 Humble servant Featured Poster

I quickly put together this recursion function.

function assoc2indexedMulti($arr) {

    // initialize destination indexed array
    $indArr = array();

    // loop through source
    foreach($arr as $val) {

        // if the element is array call the recursion
        if(is_array($val)) {

            $indArr[] = assoc2indexedMulti($val);

        // else add the value to destination array
        } else {

            $indArr[] = $val;
        }
    }

    return $indArr;
}

Tested it on a small array, I hope it works OK on your array. If the array is large it might be an issue since it doubles the memory requirement.

broj1 356 Humble servant Featured Poster

Each input on your form has to have a unique ID so you can refer to it. Also edit links have to have uinque IDs. You can use an ID from the database data or something else.

<input name="tx_name" type="text" id="tx_id-<? echo $data['id']; ?>" size="35" value="<? echo $data['title']; ?>"/>

<a href="#" class="editname" id="<? echo $data['id']; ?>">Edit</a>

Now you can catch the onclick event of edit link and read record ID from it:

$(".editname").click(function() {

    var recordId = $(this.attr('id'));

    // use recordId to access input fields
    var inputValue = $(('txt_id-' + recordId)).val(); // or something like that
    ...

EDIT: I have done several edits in the code so make sure you refresh to the last version.

The code above might be a bit wobly but you get the principle. I haven't tested it.

broj1 356 Humble servant Featured Poster

It only ocurred to me after preparing the previous post: whay do you want to save data that is already in the database to another table? Are you sure your data is normalized properly? Or, maybe you could do it oin the batchinfo1.php script?

broj1 356 Humble servant Featured Poster

In the batchinfo1.php that generates the table, give the table an ID so you can refer to it later:

echo "<table id='result-table' border='1'>

You did not answer my question about what will triggers the saving of data into database. I assume here that it will be a submit button at the end of the table.

Add a submit button after the table code:

echo '<input type="button" value="Save" onclick="saveTableData()" />';

Add javascript code that will run onclick of a submit button (adapted from here). Another assumtion here is that you have only text in cells no other html elements.

function saveTableData() {

    // create an array that will hold values which you will pass to
    var resultArray = new Array();

    // get the table by it's ID
    var refTab = document.getElementById("result-table")

    // Loop through all rows 
    for(var i = 0; i < refTab.rows.length; i++) { 

        // one row
        var row = refTab.rows.item(i); 

        // loop through cells in a row
        for(var j = 0; j < row.cells.length; j++) { 

            // one cell
            var cell = row.cells.item(j);

            // add cell value to the result array
            resultArray[row][cell] = cell.firstChild.innerText);
        } 
    }

    stringify it so it can be POSTed
    var parameterString = JSON.stringify(resultArray);

    // do an ajax call to another php script that will store the data in the DB
    // using parameterString as a parameter 
    // (you will use json_decode($_POST['jsondata']) to decode it in php script)
    ...

}

I haven't tested the code but you will get the concept …

broj1 356 Humble servant Featured Poster

The query itself looks OK. Please double check if table name is file_records, and field names are also spelled correctly. Please paste the displayed query into the SQL tab of phpmyadmin and test if it works OK. And do not to remove the die() line.

Also change line 67 to include a check:

if(!mysql_select_db($MySql_databasename,$dbconn)) {
    die("Could not select database");
}

Do similar checks when connecting to the database and when performing queries. And temporary remove the @ form the mysql_query command on line 68 so you can see possible error messages.

broj1 356 Humble servant Featured Poster

Start learning quickly, you won't regret it if you want to stay longer in web development world. Start here, it is not that difficult.

broj1 356 Humble servant Featured Poster

I have actually used PEAR a lot but it was on Linux machine. The Windows part of installation instruction is http://pear.php.net/manual/en/installation.getting.php . I had no problems installing it and using it in Linux nd I think it should work equally fine in windows.

BTW if you are just after one or two PEAR packages you can always download it/them into some directora that is in the path and use it/them. But you loose the luxury of automatic updating, some of hierarchy etc.

broj1 356 Humble servant Featured Poster

If you ask me, none of the fields here are binary:

@mysql_query("INSERT INTO file_records (file_name, file_title, file_size, uploaded_date) VALUES ('$NewFileName', '$FileTitle',$FileSize,'$uploaded_date')");

file_name and file_title should be strings, file size could be integer, uploaded date should be integer (if timestamp) or date. But if you wanted to store binary file in database the table field should be declared binary or varbinary. The query itself does not change.

broj1 356 Humble servant Featured Poster

Put this code immediately after line 68:

die("INSERT INTO file_records (file_name, file_title, file_size, uploaded_date) VALUES ('$NewFileName', '$FileTitle',$FileSize,'$uploaded_date')");

It will display the query as it gets contructed using the variables. Paste it into phpmyadmin and check for errors. You can also post it here.

BTW: none of the data in the query is binary I guess. You are not inserting the file contents to database, are you (just looking at the title of the post)?

broj1 356 Humble servant Featured Poster

You can use header() function to redirect to some other page. Do it on the beginning of the script and before you output any html.

if($banned === true) {
    // redirect to a banned.php page
    header('location:banned.php');
    exit();
}

Banned visitors will immediately get redirected to the banned.php page without seiing any other contents.

broj1 356 Humble servant Featured Poster

It seems like there are no fields with those names in the pedagogu table. Can you check whether you have spelled the index names correctly and same as field names (sorry to bother you with one more check but nothing else seems to be incorrect).

You can also try to put this debug code right after line 9:

die(print_r($row, 1));

It will display the array for the first row. You can check indexes there.

broj1 356 Humble servant Featured Poster

I am not sure whether writing banned IP addresses in htaccess file is a good idea. You will need approprite rights to write into it and the file will grow with users visiting your site which might affect performance. Also maintaing the list (i.e removing duplicate entries) in the htaccess file might be a nightmare.

I would store IPs in a database and do a check everytime a visitor comes. If the IP is the database already, show one part of the contents (or redirect as jbeartrav suggested) otherwise show another part.

// check in the database if the IP is banned
if($banned === true) {

    echo 'You are not allowed to visit';
    exit();
}

// if not banned just display the normal contents and write the IP in the database

Mind you, relying on IP to ban people is not very reliable method anyway. IP's can change so you never know whether it is the same person with particular IP.

broj1 356 Humble servant Featured Poster

If I understood: you get data about courses with batchinfo1.php through ajax call. The result is displayed in a html table. Now you want to save some of this info into some other database table, right? Which data would you like to save (some of it or all of it)? The data is already in the database so it would be sensible to store only IDs or something like that. What is the trigger for saving (is it a submit button)?

I any case you would have to give some ID to each cell with the data so you can read it using getElementById(). So i.e. on click of a submit button you will read the data and shoot the ajax, calling another php script that will save the data.

That is all I can say at the moment since I do not have enough information. I am not even sure whether I got the problem right.