broj1 356 Humble servant Featured Poster

Now, if I got it, then you have the number of comments for each post already in the $post['total_comments'] element. In this case you do not need the gather_comments function. Just use the $post['total_comments']:

<h4 style="text-decoration: none;">(<?php echo $post['total_comments']; ?> 
<?php
if($post['total_comments'] == 1) {
echo 'comment';
} else {
echo 'comments';
?>

Correct me if I am wrong.

broj1 356 Humble servant Featured Poster

I made a mistake, sory. The code in line 37 should be:

$sql .= $row < (count($parsedArray) - 2) ? ', ' : '';

I chnged the index names form $i to $row for more clarity but have forgoten to change it in this row. Sory for that.

Just to make sure how the logic goes, so you can check it:

The $parsedarray holds rows with data (say 5 for example) and the last row with Total information (6 all together) but we do not use the last row.

So count($parsedArray) equals 6 and indexes go from 0 to 5. But we need to proces only rows 1 to 5. (with indexes 0 to 4). Since $row represents the index and starts with 0, increasing by 1. So the logic is:

  1. process all rows except last (for($row = 0; $row < (count($parsedArray) - 1); $row++))
  2. if index is less than array lenght (e.g. 6) minus two (e.g. indexes 0 to 3) then add comma
  3. if index is not less than array lenght (e.g.6) minus two (e.g. so only the last index - 4) then do not add comma
broj1 356 Humble servant Featured Poster

The following line:

$sql .= $i < (count($parsedArray) - 2) ? ', ' : '';

should add a comma after a set of values only when the set of values is not the one before the last (the last row is total). Please check this logic against your data. Maybe the logic should be changed.

broj1 356 Humble servant Featured Poster

I already have questions that prevent me from carrying on :-)

In your html file there is code on line 34:

$posts = get_posts();

but function get_posts() is not defined in the comments.inc.php file. Is that OK? Can you post the code for this function. The reason for asking is that this function creates a $post array which is supposed to contain a 'total_comments' element (see line 44). If you already have total comments in the array you can use that for singular/plural logic.

Also, where do you get the $pid on line 44.

broj1 356 Humble servant Featured Poster

Again my error, sory. Line 27 should be:

    $sql .= "('$current', ";

Thnx, Squidge.

broj1 356 Humble servant Featured Poster

This is due to my error, sory. Change line 27 in my code to:

$sql .= '($current, ';

Sory for that, :-).

broj1 356 Humble servant Featured Poster

Line 22:

mysqli_fetch_assoc($ChangeDownloadSQL){

You should terminate it with ;

broj1 356 Humble servant Featured Poster

it doesnt work the table is empty wish i understood why :)

There can be many reasons. Please do echo the created query whichever method you are using to create it. Put the following debug code just before the echo 'salut'; (after line 39):

die($sql);

and post the output here (and of course test it in phpmyadmin).

broj1 356 Humble servant Featured Poster

OOps. Yes the VALUES keyword is missing, sorry. Change line 15 to

$sql = "INSERT INTO military VALUES ";
broj1 356 Humble servant Featured Poster

I have prepared an example using your code but stripping it down a bit to make it more understandable. I made up two test tables: countries (country_id, country_name) and operators (operator_id, fk_country_id, operator_name) so I could test the code. Replace the table and field names with your table definition. I am also using a mysqli for connection to the DB. Change connection and querying code to suit your needs. For more info see the comments in the code.

This is the HTML page with the dropdowns:

<?php 

// connect to the database
// replace this code with your code for DB connection
require('../common/dbConnMysqli.php');
$dbobj = new dbConnMySqli;
$db = $dbobj->getmysqliObject();

?>
<html>
<head>
<title><?php echo "DOUBLE SELECT TEST"; ?> :: Admin Login</title>
<link rel="shortcut icon" href="images/w_icon.gif">
<link rel="stylesheet" type="text/css"  href="stylesheets/shreeweb.css" >
<script  type="text/javascript" src="scripts/shreeweb.js"></script>
<script  type="text/javascript" src="scripts/sorttable.js"></script>


<!-- Include this link to be able to use jQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>


</head>  
<body>
<div class="main" align="center">

<form name="frmPrice" method="post" id="form1a">

<label for="cmbCountry">Country</label>
<select size="1" name="cmbCountry" id="cmbCountry" class="textbox"  
onchange="cmbCountry_selection_changed(this);">
<option value="0" selected="selected" disabled="disabled">-- Select Country --</option>

<?php 
// read countries from the DB for the first dropdown
$query = 'SELECT * FROM countries';
$res = $db->query($query);

// add options (countries) to the first dropdown
while ($row = $res->fetch_assoc()) {
    echo '<option value="' . $row['country_id'] . '">';
    echo $row['country_name'] . '</option>';
}
?>

</select>
<div id="operatorsDiv" style="display:inline-block;">
<label for="cmbOperator">Operator</label>
<select size="1" name="cmbOperator" id="cmbOperator" class="textbox">
<option value="0" disabled="disabled">-- Select country first --</option>
</select>
</div>

<label for="cmbGateway">Gateway</label>
<select size="1"name="cmbGateway" class="textbox">
<option value="0">Select Gateway</option>
</select>

<label …
broj1 356 Humble servant Featured Poster

No problem. I just started coding but will need structures of the Countries and Operators tables and some data for testing. You can get structure and data in phpmyadmin by executing the following query:

SHOW CREATE TABLE <table name here>

Please post the structure here. And tell me which extension do you use to connect to the database (mysql, mysqli, pdo...).

broj1 356 Humble servant Featured Poster

I have to go right now but will provide some code later tonight.

broj1 356 Humble servant Featured Poster

cmbCountry_selection_changed(this) is a javascript function that uses AJAX to:

  1. call the php script that will read the operators form the database (or with stored procedure); this function passes the chosen country usualy using POST HTTP method; the chosen county is read from DOM
  2. waits for the response form the php script (a html code for options) and injects the response into the second select element

The easiest way to do this is using jquery ajax functionality.

broj1 356 Humble servant Featured Poster

The form data is being sent to the database only when you execute a query. So after collecting the data first check the dates and only if within the range, connect to the database and execute the query.

if($sDate < $enDate && $sDate > $exDate) {

    // connect to the database and execute the query
    ...

} else {

    // do something else, i.e. redirect
    ...
}
broj1 356 Humble servant Featured Poster

Tnanx for posting the code. It seems that all the functionality is already there. The showAllCountry($Country) function obviously generates options for countries (even though I do not know why the argument $Country is needed) and on change the cmbCountry_selection_changed(this) javascript function is called that obviously returns the operators options.

The reason for code not working is hard to figure out from this. Have you copied the code from somewhere? The code includes the Customers class which you have not provided the code for. Also the code for the showAllCountry function has not been provided. It would be easier to help if you decided that you do this from scratch and not using some existing code without understanding it.

broj1 356 Humble servant Featured Poster

Sorry, but I am not sure if I understood your questions. Hope the following helps.

what i need to understand is how to get each set of those 24 result (0-23 incl.) into a row in the table of the database

If you are really sure that each set of results will contain 24 elements then you can just loop through them. But you have to have two loops: outer loop will loop through rows (which are arrays as I understand) and inner loop will loop through the elements of each row (which are field values as I understand). This concept has been shown in my above post. Here is the code again but with indexes for both loops changed to $row and $field so you know where you are and with omitted field names in the query

// begin the query (I will omit the field names sice you say they are always 24 values)
$sql = "INSERT INTO military ";

// outer loop iterates through rows
// the max condition is $row < (count($parsedArray) - 1) which omits the list row (which is total, right?)
for($row = 0; $row < (count($parsedArray) - 1); $row++) {

    // inner loop iterates through 24 field values
    for($field = 0; $field < count($parsedArray[$row]); $field++) {

        // read the current value (this is just for clarity)
        $current = mysql_real_escape_string($parsedArray[$row][$field]);

        // if first element of inner array, add starting parenthesis
        // if not first and not last element of inner array, add …
broj1 356 Humble servant Featured Poster

It would help if you posted the code you already have and table structures so we can build from there.

Basicaly what you do is:

  1. read the database to get the list of countries
  2. build the first drop down (html select element ) with options containing countries
  3. the drop down (select element) should have onchange event that calls a javascript (jquery) function that will use AJAX to fetch a list of operators for a chosen country
  4. a php script that will read the list of operators for a selected country form the database, process it and return it as html code for the second drop down list (select element)
  5. an empty div and an initial second drop down that will be replaced with the code returned from the above mentioned php script

This way a user will select a country and the second drop down will automaticaly get populated with a list of operators.

If you search DW for two dropdowns or two selects using ajax you might already find something useful since this topic is quite common here. And as said if you post the code you have so far and the table structure it will be easier to help.

broj1 356 Humble servant Featured Poster

Please post the content of the $array. Put this code on the beginning after if(isset($_POST['TextArea1'])){:

    // put this debug line here
    die(print_r($array, 1));

and post here the output.

broj1 356 Humble servant Featured Poster

Can you post the whole code you have. i will test it in my environment.

broj1 356 Humble servant Featured Poster

What is the error message?

broj1 356 Humble servant Featured Poster

Yes, the example I gave is just a generalized way of doing it. I presume you have field names in the $array[0], which is an array holding one row. So the following code extracts the field names for the first part of the query:

// add DB field names (assumming they are an array in the first element of the $array)
for($i = 0; $i < count($array[0]); $i++) {
    $sql .= "`{$array[0][$i]}`";
    // if it is not the last field, add comma
    // if it is the last field, add parentheses
    $sql .= $i < (count($array[0]) - 1) ? ', ' : ') ';
}

then you add the real values of the rows. Each row of values is within parentheses and separated by comma. The generalized example shows that. In reality your query should look like:

INSERT INTO military (`id`, `Name`, `Position`, ... etc ...) VALUES
('some value 1', 'some value 2', ... etc ...),
('some value 3', 'some value 4', ... etc ...),
('some value 5', 'some value 5', ... etc ...)

But I do not know the values so I am making them up.

broj1 356 Humble servant Featured Poster

You do not get any errors? What is your php.ini setting for error_reporting and display_errors? It should be set to on for development:

display_errors = on

You can temporary turn error reporting in the script by including this code on the very beginning:

error_reporting(E_ALL);
broj1 356 Humble servant Featured Poster

This should work if there are no glitches in the code. But you are sending a lot of insert statements to the DB server, which is not a critical issue but these days you try to avoid too many consecutive calls to the DB if you can do it in one call. It is up to you, though. Let us know how it works once the server is up and running.

It would be a good idea to at least escape the values so you do not expose the server to SQL injection attack.

BTW: do you not have a local environment for testing?

broj1 356 Humble servant Featured Poster

You actually do not have to mix the two code snippets. The first part is OK, it formats the data from the textarea and puts it in a two-dimesional array. In the second part of the code I suggested you just loop through the array of data and construct a multiple insert statement which you then send to the database in one go. Just replace the second part of your code with my code (and add the database connection code on the beginning) and it should work. The query you will get is something like:

INSERT INTO  military (`field1`, `field2`, `field3`, `field4`) VALUES
('value11', 'value12', 'value13', 'value14'),
('value21', 'value22', 'value23', 'value24'),
('value31', 'value32', 'value33', 'value34')

which is one long query but it get sent to the database only once.

broj1 356 Humble servant Featured Poster

I am not sure if I understood your problem correctly but there are some thoughts:

  1. Put the mysql_connect and mysql_select_db outside the loop, somewhere on the beginning; it is preferred to execute this code only once
  2. check for the existence of each $array element, since the data comes from textarea and is not quaranted that it will exist; use isset function: if(isset($array[0][0])) {$id = $array[0][0];} else {// set default value}
  3. use foreach loop to iterate through $array, it is more handy (but not necessary, really)
  4. construct one query that inserts multiple values (begin the query before the loop, add values within the loop, execute the query after the loop)
  5. switch to safer mysqli extension ASAP

Here is how to construct the query (see the comments):

// begin the query
$sql = "INSERT INTO military (";

// add DB field names (assumming they are an array in the first element of the $array)
for($i = 0; $i < count($array[0]); $i++) {
    $sql .= "`{$array[0][$i]}`";
    // if it is not the last field, add comma
    // if it is the last field, add parentheses
    $sql .= $i < (count($array[0]) - 1) ? ', ' : ') ';
}
// add the VALUES part
$sql .= 'VALUES ';

// add the values from the $array
for($i = 1; $i < count($array); $i++) {
    // each element of $array is also an array so loop through it
    for($j = 0; $j < count($array[$i]); $j++) {
        // check for the existence of the element …
broj1 356 Humble servant Featured Poster

There seem to be no syntax errors but this does not guarantee your code works. So make sure you have your php.ini set to display errors and post the errors that you get. Other tips:

  • Use meaningful names for variables; $x, $y etc do not tell much but are likely to confuse you
  • before using the array values that you have no guarantee they exist, chech if they are set using isset() function; this goes for the $_SESSION, $_POST (or $_GET), etc;
  • if($_POST) is meaningless check, check each element using isset(): if(isset($_POST['b1']))
  • Avoid using inline styles unless really necessary
  • create a function to connect to the database and put this function in safe area where it can not be read by web users and non privileged people; you do not want your password exposed
  • switch to mysqli or PDO since mysql is soon going to be history (deprecated)
broj1 356 Humble servant Featured Poster

OK, then we have to debug the function.

  1. It is advisable to include error checking with mysql functions (mysql_query, mysqli_fetch_row...). You have to decide how to handle the errors (i.e. the function returning false, stoping the script, custom error messages...).
  2. INclude the checking of the argument value
  3. You can temporary echo the query using die and test it in phpmyadmin
  4. You can echo the resulting row using a combination of die and print_r functions

So considering above, the function should look like:

function gather_comments ($pid){

    // check the argument
    if(is_numeric($pid)) && $pid > 0) {
        $pid = (int)$pid;
    } else {
        return false;
    }

    $sql = "SELECT COUNT(*) FROM `comments` WHERE `post_id`= $pid";

    // DEBUG
    // this is for debugging only, comment it out in production
    // this will display the SQL statement; copy it to phpmyadmin for testing
    die($sql);

    // query the database
    $res = mysql_query($sql);

    // include error checking when queryinig the database
    if(!$res) {

        // DEBUG
        // this is for debugging only, comment it out in production
        die(mysql_error());

        // if error when querying then return false
        return false;
    }

    // fetch the row
    $row = mysqli_fetch_row($res);

    // DEBUG
    // this is for debugging only, comment it out in production
    // this will display what the $row array contains and stop the script
    // the $row array should have only one element ($row[0]) - the count of found comments
    die(print_r($row, 1));        

    // include error checking when fetching the row
    if(!isset($row) || empty($row)) {

        // DEBUG
        // this …
broj1 356 Humble servant Featured Poster

Your function is not returning the number of comments but the resource (a special PHP type) for the query. And also the query has to be changed to:

$sql = "SELECT COUNT(*) FROM `comments` WHERE `post_id`= {$pid}";

The function should be something like:

function gather_comments ($pid){
    $pid = (int)$pid;
    $sql = "SELECT COUNT(*) FROM `comments` WHERE `post_id`= {$pid}";

    $res = mysql_query($sql);
    $row = mysqli_fetch_row($res)
    $comments = $row[0];

    return $comments;
}

The logic for displaying singular or plural should be simple:

// call the function only once so you do not shoor too many queries
$commentsCount = gather_comments($pid);

if($commentsCount == 1) {
    echo 'comment';
} else {
    echo 'comments;
}

If you retrieve comments earlier in the script (i.e. for displaying) the function is not necessary since you can just count the retrieved comments.

broj1 356 Humble servant Featured Poster

I perfer using a normal for, not a foreach.

Any reason for this?

broj1 356 Humble servant Featured Poster

$_COOKIE is associative array. If you want to turn it to numerically indexed you can use array_values() function. But you are loosing valuable information. You can list values this way:

foreach($_COOKIE as $value) {

    echo $value;
}
broj1 356 Humble servant Featured Poster

Then you might want to use a rich text editor like TinyMCE. It converts your textareas (or other elements) to WYSIWYG editor so users can draw tables, use lists, change fonts, colors etc.

broj1 356 Humble servant Featured Poster

The <textarea> tag should be be ended with </textarea> end tag. Anything between these two tags gets displayed, but as a plain text. I believe the html code (the table in your case) will be displayed just as plain text and not formatted as a table.

broj1 356 Humble servant Featured Poster

Have you taken into account the fact that the same visitor will have different session ID on each visit (on each session)?

broj1 356 Humble servant Featured Poster

I don't see any submit button. How do you submit the form?

You can change the hidden input into submit button. Change this code:

<input type="hidden" name="submitted" value="true" />

into this code:

<input type="submit" name="submitted" value="Submit" />
broj1 356 Humble servant Featured Poster

But this only add the last entry to the database!

In your last version the query is outside both foreach loops so it gets run only once with the last assigned values. Put the query inside the inner loop and also apply the sanitizing (mysql_real_escape_string function), like suggested in above posts (take security seriously).

It is a good practice to assign a query to a string before running it - this is how you can echo it and test it in phpmyadmin:

$query = "INSERT INTO links  VALUES (...)";
...

// temporary debug code will display the query and stop the script
// you can now examine the query and copy it into phpmyadmin for testing
die($query);

// run the query
mysql_query($query);
broj1 356 Humble servant Featured Poster

If you need to know only whether email exists or not, use COUNT(*) in your query and use fetchColumn() to get the number of rows found:

foreach($email as $em)
{
    $sql = "SELECT COUNT(*)
    from sf_guard_user sf,personal pi
    where pi.user_id = sf.id
    and sf.email_address = '$em'
    ";
    $query = $db->prepare($sql);
    $query->execute();

    // change this to suit your needs
    if($query->fetchColumn() > 0) {
        echo "#em already exists<br>";
    } else {
        echo "#em does not exist<br>";
    }
}
broj1 356 Humble servant Featured Poster

I am not sure whether I got exactly what you want but I can suggest you use a function that will return the ID formed as a string. Something like:

function getCustomID($id) {

    // check if ID is within the limits (you can go from a01 to z99 only)
    if($id < 1 || $id > 2574) {

        die("Value $id is out of limits!");
    }

    // get the alpha phart (the letter)
    // ascii code for the character a = 97
    $charIndex = ceil($id / 99) - 1 + 97;
    $alphaPart = chr($charIndex);

    // get the temporary number between 1 and 99
    $tempNum = $id % 99 == 0 ? 99 : $id % 99;

    // get the numeric part (just temporary number padded with 0)
    $numericPart = str_pad($tempNum, 2, '0', STR_PAD_LEFT);

    // return the string that represents the ID
    return $alphaPart . $numericPart;
}

And here is a little test of what the function does:

// test the function with some test data
$testArray = array(1, 2, 3, 99, 100, 101, 102, 197, 198, 199, 200, 205, 2088, 2574);
foreach($testArray as $patientid) {

    echo "<pre>$patientid: " . getCustomID($patientid) . "</pre><br>";
}
broj1 356 Humble servant Featured Poster

Hopefuly this resolves your issue. If yes, please mark as solved. If no, come back with more questions. Happy coding.

broj1 356 Humble servant Featured Poster

You can do multiple insertion with one query:

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

    // start the query
    $query = 'INSERT INTO links  VALUES ';

    // get number of elements in the array containing links
    $linksCount = count($_POST['alink']);

    // step through the array containing links
    for($i = 0; $i < $linksCount; $i++) {

        // add to the query if value exists
        if (($_POST['alink'] != '') {

            // escape the values (do not omit this!!)
            $alink = mysql_real_escape_string($_POST['alink']);
            $aname = mysql_real_escape_string($_POST['aname']);

            $query = "('', '$alink', '$aname'), ";
        }
    }

    // remove the trailing comma from the end of query
    $query = rtrim($query, ',');

    // run the query
    mysql_query($query);
}

And switch to newer mysqli as soon as you can :-)

broj1 356 Humble servant Featured Poster

If you want to have formatted text that user inputs and formats then the best option is to use ready made rich text editor. As I said TinyMCE is just one of them. It will offer your users plenty of possibilities to format the text (font, color, lists, tables etc.) and will generate safe html code for you to store in a database as i.e. text type field. You can retrieve that text later and display it formated or use it in any other way. If you plan to write this functionality yourself it will take a lot of effort.

broj1 356 Humble servant Featured Poster

See media rules @screen and @print (my first post).

broj1 356 Humble servant Featured Poster

Use a rich text editor. I use TinyMCE and it is one of the best in my opinion. But you have to be aware that there is some learning curve.

broj1 356 Humble servant Featured Poster

Again, you have to design the receipt using HTML + CSS. Also you have to build the logic to read the correct name from the db.

broj1 356 Humble servant Featured Poster

Can you explain more, please?

broj1 356 Humble servant Featured Poster

Your responsibility is to format the data read from the database, using PHP and HTML, into something that looks useful and appealing to the user. You can use tables, lists and other HTML elements and CSS. Regarding CSS you can use media rules: @screen for onscreen display in the browser and print for printing. You can also dive into CSS3 media queries for more.

And of course as LastMitch suggested, you can use PDF which will give you much more formating freedom.

broj1 356 Humble servant Featured Poster

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

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

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

// TEMP DEBUG
die($SQL);

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

broj1 356 Humble servant Featured Poster

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

First page:

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

Second page:

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

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

broj1 356 Humble servant Featured Poster

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

$username = ...;

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

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

broj1 356 Humble servant Featured Poster

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

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

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

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