broj1 356 Humble servant Featured Poster

Regarding the checkboxes (or tick boxes, as you call them):

when processing the posted values you have to check for an existence of a value of each checkbox. If the check box was not clicked, the value does not exist in the $_POST array.

if(isset($_POST['disabilities'])) {
    $disabilities = 'Yes';
} else {
    $disabilities = 'No';
}

Hope this helps.

Also see this link: http://www.html-form-guide.com/php-form/php-form-checkbox.html

broj1 356 Humble servant Featured Poster

If you want to use a php variable in html enclose it within the <?php ?> tags and echo it:

onclick="showRemarks(' <?php echo $activityid; ?>');" id="remarksadd"></img>
JayJ commented: Same solution as I offered :) +1
broj1 356 Humble servant Featured Poster

@estinah
Please start a new thread for your question. Post the code there you have so far.

broj1 356 Humble servant Featured Poster

Echo the problematic query that the second code generates and post it. Also enclose field names within backticks since there might be a possibility that the generated field name is a mysql keyword.

broj1 356 Humble servant Featured Poster

Hi folks. I have a strange thing happening here. I have a loop where counter gets incrememnted by 0.1 starting from 0 and up to 1. In each iterration I use the counter in an expression with modulo operator. I get incorrect result when the counter has values of 0.8 and 1. This is the code:

<?php
echo '<pre>';
for($i = 0; $i <= 1; $i += 0.1) {
    // result of an expression
    $result = ($i * 10) % 10;
    // display $i, the expression and the result of the expression
    // when $i equals 0.8 and 1 the result is incorrect!!!
    echo "i: $i  =>>  ($i * 10) % 10 = $result <br />";
}
echo '<pre>';
?>

and here is the output I get:

i: 0  =>>  (0 * 10) % 10 = 0 
i: 0.1  =>>  (0.1 * 10) % 10 = 1 
i: 0.2  =>>  (0.2 * 10) % 10 = 2 
i: 0.3  =>>  (0.3 * 10) % 10 = 3 
i: 0.4  =>>  (0.4 * 10) % 10 = 4 
i: 0.5  =>>  (0.5 * 10) % 10 = 5 
i: 0.6  =>>  (0.6 * 10) % 10 = 6 
i: 0.7  =>>  (0.7 * 10) % 10 = 7 
i: 0.8  =>>  (0.8 * 10) % 10 = 7 <-- this is incorrect
i: 0.9  =>>  (0.9 * 10) % 10 = 9 
i: 1  =>>  (1 * 10) % 10 = 9     <-- this is incorrect

Can anybody test this code and see if the result is the same. Any ideas why this?

diafol commented: Thanks for this +14
broj1 356 Humble servant Featured Poster

Seems like $row['teacher_id'] and $row['comment'] haven't got a value. Insert the following after the line 19:

if(!isset($row['teacher_id']) or empty($row['teacher_id']) or !isset($row['comment']) or empty($row['comment'])) {
    die('<pre>' . print_r($row, 1) . '</pre>');
}

and post the output.

(the code above will check if any of the suspicious values do not exist and will display the array with values of $row variable at that time in preformated html).

broj1 356 Humble servant Featured Poster

Firstly: you are mixing double quotes for PHP strings with double quotes for html attributes. Escape the later.
Secondly: composite variables in a string should be enclosed in curly braces to get parsed correctly.

$mesaj="<li><a href=\"{$db_field['Image']}\" class=\"pirobox\" title=\"{$db_field['Titlu']}\"><img src=\"{$db_field['Image']}\"/></a><p>{$db_field['Content']}</p><div class=\"button\"><pre><a href=\"index.php\">Read More</a><a href=\"{$db_field['Download']}\">Download</a></pre></div></li>";
broj1 356 Humble servant Featured Poster

An error could also be on line 13

$upperlimit = mb_substr($datecomponentsyear,0,10);

You should propbably use $upperlimit for calculating the upper limit:

$upperlimit = mb_substr($upperlimit,0,10);
Goldfinch commented: Thanks!, this post and the one before it were very helpful +0
broj1 356 Humble servant Featured Poster

Have an array with indexes the values and elements the words you want to represent the values:

$numbers_array = array('1' => 'one', '2' => 'two', '3' => 'three');
// wrap everything within form tags
echo '<form action="#" method="post">';

// use PHP to construct the select element
echo '<select name="numbers">';
foreach($numbers_array as $value => $text) {
    echo " <option value='$value'>$text</option>"
}
echo "</select>";
// submit button
echo "<input name="submit" value="Submit" />";
echo "</form>";

// check if submit button was pressed
if(isset($_POST['submit'])) {
    $chosen_value = $_POST['numbers'];
    // display chosen value and text
    echo $chosen_value . ' - ' . $numbers_array[$chosen_value];
}
nidhzee11 commented: thanks..plz solve this also +0
broj1 356 Humble servant Featured Poster

Or put a counter within a while loop and see how many rows you get (you might use PDO's number of rows function):

public function headLoad()
{

    // debug ceounter
    $i = 0;

    $cxn = $this->connection()->prepare("SELECT scriptCode FROM head_scrips WHERE active = '0'");
    $cxn->execute();
    $cxn->setFetchMode(PDO::FETCH_ASSOC);
    print "<script>";
    while($row = $cxn->fetch())
    {
        print $row['scriptCode'];

        // increase the counter
        $i++;
    }
    print "</script>";

    // print the counter
    echo "Number of rows: $i";
}
broj1 356 Humble servant Featured Poster

OK, but as I stated in my previous post please send the contents of the $_SESSION before the for loop (see above). Even better if you send the contents of the $_SESSION both before and after the foor loop so we can compare. Use the following code:

else if(isset($_REQUEST['command'])=='update'){

    // this will display the contents of the $_SESSION['cart'] before the update
    print_r($_SESSION['cart']);

    $max=count($_SESSION['cart']);
    for($i=0;$i<$max;$i++){
        $pid=(isset($_SESSION['cart'][$i]['productid']));
        $q=intval($_REQUEST['product'.$pid]);
        if($q>0 && $q<=999){
        $_SESSION['cart'][$i]['qty'] = $q;
    }

    // this will display the contents of the $_SESSION['cart'] after the update
    // and end the script
    die(print_r($_SESSION['cart'], 1));

    else{
        $msg='Some proudcts not updated!, quantity must be a number between 1 and 999';
    }
}
weirdCreature7 commented: thank you so much! :) +0
broj1 356 Humble servant Featured Poster

Your test should be within a loop where $i is defined:

for($i=0;$i<$max;$i++)

Otherwise you can not test for $_SESSION['cart'][$i]

weirdCreature7 commented: It is still not working I really dont understand it anymore :( please help me how will I do it! Thank you so much for the reply :) +0
broj1 356 Humble servant Featured Poster

OK so you want to drag the rows of displayed html table. This is a Javascript job. Have you checked the link pritaeas sent in above post? I think this is the answer for you (have a look at the code in the browser - you will find the css and javascript you need).

confstu commented: thanks once again, i will see pritaeas link and try it +0
broj1 356 Humble servant Featured Poster

mysql_fetch_array returns a row of the table in a form of an array. You actually are processing row by row already in the code:

while($row = mysql_fetch_array($result))

Within the above while loop you can do anything with the row or the fields of the row.

Can you please explain more in detail what you want to achieve (I hope I did not missunderstand your question).

broj1 356 Humble servant Featured Poster

Many developers (including myself) use Eclipse (http://www.eclipse.org/downloads/packages/eclipse-php-developers/heliossr2). Maybe a bit complicted to install and configure but powerful. Quite many also use Netbeans (http://netbeans.org/). I use it now and then at home and find it very good also.

Many text editors also provide syntax checking like Notepad++, KWrite, gedit (both Linux) etc. All the software I mentioned is free.

LastMitch commented: Thanks for the link & suggestion! +2
broj1 356 Humble servant Featured Poster

The following is my suggestion (maybe not perfect but works):

// first check if the form was submitted
if(isset($_POST['submit'])) {

    // initialize the array that will hold potential error messages
    $errors = array();

    // initialize variables (for filling-in fields in case of errors)
    $name = $_POST['name'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];

    // if the form was submitted do the validation, assign variables and prepare
    // potential error messages

    // Filter Email
    // you can also use the function from the saadi06 post above
    if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {

        $errors[] = 'E-mail is not valid';
    }

    // Filter name
    if(!filter_var($name, FILTER_DEFAULT)) {

        $errors[] = 'Name is not valid';
    }

    // Filter Phone (I doubt this is an appropriate filter for phone numbers)
    // you better make up a function for checking phone numbers in your country
    if(!filter_var($phone, FILTER_DEFAULT)) {

        $errors[] = 'Phone is not valid';
    }

    // comment text 
    $comment = $_POST['comment'];

    // if there were no errors (the errors array is empty) send the mail,
    // display the successful message and stop the script
    if(empty($errors)) {

        $from = 'From: Form Submission';
        $to = 'email@gmail/yahoo/etc.com';
        $subject = 'Form Has Been Submitted - FRONT PAGE';
        $body = " Form is Submitted by $name\n E-Mail: $email\n Phone: $phone\n Comments:\n $comment";

        // mail($to, $subject, $body, $from);

        die('<p>Message Sent Successfully!</p>');
    }
}

// start the form, method is post, action is # (same page)
echo '<form method="post" action="#">';

// add the input element for name
echo 'Name: <input type="text" name="name" value="' . $name . '" /><br …
broj1 356 Humble servant Featured Poster

Maybe have look at this: http://www.killerphp.com/tutorials/object-oriented-php/. Haven't checked it myself but looks like a simple introduction.

broj1 356 Humble servant Featured Poster

No problem, my friend. And please do not call me a guru since I am far far from that :-). You will soon get practice too.

If you find the answers helpful you can always vote (up arrow on the right side). If you think the post is really bad you can also downvote it (down arrow on the right side).

If this wrapps up this topic you can mark is as solved. If another problems arise just start a new topic.

broj1 356 Humble servant Featured Poster

This is the principle:

for($row=1;$row<=20; $row++){
    echo "<tr>\n";
    for($col=1;$col<=20; $col++) {
        $x=rand($min,$max);
        $random_array[$row][$col] = $x;

        if($x % 2 == 0) {

            $char = '*';
        } else {

            $char = '%';
        }

        echo"<td>$char</td>\n";
        // add value to the $temp_array
        $temp_array[] = $x;
    }
    echo "</tr>";
}
broj1 356 Humble servant Featured Poster

OK, I've done a bit of juggling and came up with the code below. Please note since you create a two-dimensional array you have to copy it to a one-dimensional temporary array so you can use the sort php function which works on one-dimensional arrays. See the comments in the code. I have renamed the variables you used but you can change them. Hope this is what you intended to get help with. If not then give more explanation.

<?php

$x=0;
$min=900;
$max=2000;

// initialize array of random values
$random_array = array();

// initialize temporary array for sorting
$temp_array = array();

// start html table for random values
echo "<table border=\"1\">";

// create $random_array with random numbers, display html table rows and
// store each value in onedimensional $temp_array for sorting
for($row=1;$row<=20; $row++){

    echo "<tr>\n";

    for($col=1;$col<=20; $col++) {

        $x=rand($min,$max);
        $random_array[$row][$col] = $x;

        echo"<td>$x</td>\n"; 

        // add value to the $temp_array
        $temp_array[] = $x;
    }

    echo "</tr>";
}

// end the html table
echo "</table>";

// sort the $temp_array (sort works on onedimensional arrays)
sort($temp_array);

// start a table for sorted values
echo "<table border=\"1\">";

// initialize counter that will be the $temp_array's key
$key = 0;

// display html table rows of sorted values
for($row=1;$row<=20; $row++){

    echo "<tr>\n";

    for($col=1;$col<=20; $col++) {

        echo"<td>{$temp_array[$key]}</td>\n";

        // increase the key
        $key++; 
    }

    echo "</tr>";

}

// end the html table of sorted values
echo "</table>";

?>
broj1 356 Humble servant Featured Poster

In the above code the variables $table and $y are undefined. What is the purpose of those?

Also you should not put the </table> tag within the foreach loop (see line 23). I am still looking at your code so more follows.

broj1 356 Humble servant Featured Poster

Add a variable that counts record and check in the loop whether is odd or even. If it is odd then you start the row and the cell, if it is even end the cell and the row of the table.

function getBookSeller ()
{
    $con = mysql_connect(server , userName , password ) or die('DataBase cannot connect. Reason: ' . mysql_errno());
    mysql_select_db(db_name) or die('Table cannot connect. ' . mysql_errno());
    $sql = "SELECT *
    FROM book_sellers";
    $result = mysql_query($sql, $con) or die('Query Error. ' . mysql_errno());
    $totalrows = mysql_affected_rows();
    $totalrows = ceil( $totalrows/2);
    //echo $totalrows;
    echo "<table width='600' border='1' cellspacing='2' cellpadding='3' bordercolor='#FFFFFF'>";
    echo "<tr align='center'>";
    echo "<td colspan='2' bordercolor='#000000' bgcolor='#9999CC'><b>Get
    your copy today</b></td>";
    echo "</tr>";
    while($row = mysql_fetch_array($result))
    {
        // initialize output string
        $output = "";

        // if the current record is odd (1,3,5...) then start the row and the cell
        if($current_record % 2 == 1) {

            $output .= "<tr bordercolor='#CCCCCC'><td>";
        }

        $output .= "<b>".$row["book_shop"]."</b><br><br>";
        $output .= "<b>Att: </b>".$row["name"]."<br>";
        $output .= "<b>Add: </b>".$row["address"]."<br>";
        $output .= "<b>Phone: </b>".$row["ph"]."<br>";
        $output .= "<b>Fax: </b>".$row["fax"]."<br>";
        $output .= "<b>Mobile: </b>".$row["mobile"]."<br>";
        $output .= "<b>Email: </b>".$row["email"]."<br>";
        $output .= "<b>Website: </b>".$row["website"]."<br>";

        // if the current record is even (2,4,6...) then end the cell and the row
        if($current_record % 2 == 0) {

            $output .= "</td></tr>";
        }
        echo $output;

        $current_record++;
    }

    // if the last row was odd then you have to end the row when out of the loop
    if($current_record % 2 == 0) {

        echo "</td></tr>";
    }

    echo "</table>";
}

To get the number of records in …

Biiim commented: good +5
broj1 356 Humble servant Featured Poster

Here are some hints:

  • when coding a form use name attributes that match column names
  • decide whether use post or get method (post is slightly more secure, get can be easily bookmarked or saved)
  • in any case clean the input before using it in a query (use at least escaping)
  • use SELECT query to search and WHERE condition to limit search for the fields that have entered search terms
  • decide if you allow partial matching of text fields (use % wildcards in a query)
  • decide if you allow ranges for numeric and date values
  • if you want to use full text search the table engine has to be of the correct type (MyISAM for mySql)
  • store search values so you can autofill-in the form after the search has been performed
broj1 356 Humble servant Featured Poster

OK, I am getting the picture. Let's make it step by step. Below is the code to display a form with three checkboxes and a submit button. If the form gets submited the script will read the events from selected tables and display those events. You can adapt this code to suit your requirements. Please note that I have changed the names of tables from table to calendar to make things clear and to avoid possible mistakes (I think it is not a good idea to use general terms or reserved words for variable names). See explanations in comments.

<?php
// if form was submitted and if array with calendar names exists and is not empty
if(isset($_POST['calendar']) && !empty($_POST['calendar']))
{
    // connect to the database
    $con = mysql_connect("","","");
    if (!$con)
    {
        die('Could not connect: ' . mysql_error());
    }
    mysql_select_db("", $con);

    // process selected tables (calendars)
    // - read events from each calendar
    // - display events for that calendar
    foreach($_POST['calendar'] as $calendar)
    {
        // query to read events from one calendar
        $q_select = "SELECT * FROM $calendar ";
        $result = mysql_query($q_select);

        // display calendar name
        echo "<h3>$calendar</h3>";

        // list of events (i.e from three columns, separated with a <br />
        // but you could display this in a html table)
        while($row = mysql_fetch_row($result))
        {
            echo "<p>{$row[0]}<br />{$row[1]}<br />{$row[2]}</p>";
        }
    }
}
?>

<form method="post" action="#">
<input type="checkbox" name="calendar[]" value="calendar_A" checked="checked"/>Calendar A<br />
<input type="checkbox" name="calendar[]" value="calendar_B"/>Calendar B<br />
<input type="checkbox" name="calendar[]" value="calendar_C"/>Calendar C<br />
<input type="submit" name="submit" value="Submit">
</form>
broj1 356 Humble servant Featured Poster

Where should the variable $one_table be drawn from? Does it somehow come from the form?

This is only my assumption since I still do not exactly understand what you want to do: in my previous post I gave you three posibilities to get the table names. For the example in that post I chose the last possibility - the user enters table names in the form, separated by space. So you end up with a string of table names and spaces between them. You use explode function to convert this string into an array. The array of table names is then processed in a foreach loop where $one_table represents the current table name when you loop through the array of table names (see http://php.net/manual/en/control-structures.foreach.php). The array can contain one or more table names.

In the insert function, I am hoping that $table_name will become a table such that I can enter it into this statement "SELECT FROM table_name". Does this happen on the previous step?

Really hard to answer since I do not understand how you want to use the table names.

In the VALUES '$categories', should it read something like this? - VALUES ('{$_POST['columnA']}', '{$_POST['columnB']}', '{$_POST['columnC']}')";

I do not know what the role of categories is here. Maybe you describe the whole concept, what you want to achieve, what is the expected input, the table structures etc. Only after realy understanding what you want to do I can give you useful …

broj1 356 Humble servant Featured Poster

If you want to let users create their own tables you must use input form fields (one for each table or one for many tables separated by some character such as space or colon). Then you have to store all table names in an array which you will use in foreach loop:

  • if you use checkboxes, then $_POST[checkbox_name] will already return an array
  • if you use an input form field you get each table name as a string and you have to build an array yourself
  • if you use one checkbox for table names separated by a space or colon (or other character) then you use explode function to create an array

If you let users choose their table names can be dangerous since they can unknowingly use mysql keywords. You can avoid that adding a prefix to each table. You might also make sure that different users do not use same names for table names.

The loop for inserting would be something like

<?php
// first check if the form was submitted
// and if it was process the queries
if(isset($_POST['Submit'])) {

    // check if any table names were entered
    if(isset($_POST['table']) and $_POST['table'] != '') {

        // security first: escape the string to avoid SQL injections
        $tables_string = mysql_real_scape_string($_POST['table']);

        // prefix for tables
        $prefix = 'usrtbl_';

        // create tables array (table names are separated by spaces in this example)
        $tables_array = explode(' ', $tables_string);

        // proces tables
        // the data for the fields is in the $categories variable …
broj1 356 Humble servant Featured Poster

First I have to correct myself, sorry. The $_POST array elements should be enclosed in curly brackets whenever they are in a double quoted string. So this is the correct code (changes only in lines 24 and 51):

// check if the form was submitted
if(isset($_POST['Submit'])) {

    // Please note: validating, sanitizing and escaping of input was
    // omitted in this example for clarity; please do not forget
    // to make the production version of the script secure

    // start the select query that will read from all three tables
    // the types of JOIN are just an example, use the join types
    // that suit your requrements
    $qry  = 'SELECT * FROM project_table AS prj ';
    $qry .= 'JOIN technology_table AS thn ON prj.project_id=thn.project_id ';
    $qry .= 'JOIN financing_table AS fin ON prj.project_id=fin.project_id ';

    // conditional operator in a SELECT statement
    // (it will be WHERE for first condition and will change to AND
    // for every next condition)
    $operator = 'WHERE';

    // check if project type was submited to be searched for
    if(isset($_POST['project_type']) and $_POST['project_type'] != '') {

        // add the search string to the SQL statement
        $qry .= "$operator project_type={$_POST['project_type']} ";

        // change the operator from WHERE to AND
        $operator = 'AND';
    }

    // check if technologies were submited to be searched for
    if(isset($_POST['technologies']) and $_POST['technologies'] != '') {

        // remove spaces that might follow commas
        $tecnologies = str_replace(', ', ',', $_POST['technologies']);

        // explode the string to an array (where commas are)
        // and add the elements …
broj1 356 Humble servant Featured Poster

The following is a simple example of how to build a SELECT query based on the values typed in a search form. Please note security stuff has ben omitted for clarity. Do not forget to apply security checks. See comments in the code.

// check if the form was submitted
if(isset($_POST['Submit'])) {

    // Please note: validating, sanitizing and escaping of input was
    // omitted in this example for clarity; please do not forget
    // to make the production version of the script secure

    // start the select query that will read from all three tables
    // the types of JOIN are just an example, use the join types
    // that suit your requrements
    $qry  = 'SELECT * FROM project_table AS prj ';
    $qry .= 'JOIN technology_table AS thn ON prj.project_id=thn.project_id ';
    $qry .= 'JOIN financing_table AS fin ON prj.project_id=fin.project_id ';

    // conditional operator in a SELECT statement
    // (it will be WHERE for first condition and will change to AND
    // for every next condition)
    $operator = 'WHERE';

    // check if project type was submited to be searched for
    if(isset($_POST['project_type']) and $_POST['project_type'] != '') {

        // add the search string to the SQL statement
        $qry .= "$operator project_type=$_POST['project_type'] ";

        // change the operator from WHERE to AND
        $operator = 'AND';
    }

    // check if technologies were submited to be searched for
    if(isset($_POST['technologies']) and $_POST['technologies'] != '') {

        // remove spaces that might follow commas
        $tecnologies = str_replace(', ', ',', $_POST['technologies']);

        // explode the string to an array (where commas are) …
broj1 356 Humble servant Featured Poster

http://www.w3schools.com/ is a great resource for a beginner. For filtering input values see http://www.w3schools.com/php/php_filter.asp.

dgibbons82 commented: Thank you once again. +0
broj1 356 Humble servant Featured Poster

You can also echo your query before submitting it. Put this on line 14 of the php file:

die($sql);

Now you can examine your query and test it in phpmyadmin.

dgibbons82 commented: Once again, thank you for explaining and showing me how to do it. I appreciate it. +0
broj1 356 Humble servant Featured Poster

Storing posted values in variables is not neccessary by itself but it helps clarity of your code. Compare the following two statements:

// $_POST array elements used 
$sql="INSERT INTO survey (first_name, last_name, ...)
VALUES
('{$_POST[first_name]}','{$_POST[last_name]}', ...);

// variables used
$sql="INSERT INTO survey (first_name, last_name, ...)
VALUES
('$first_name','$last_name', ...);    

The second version is far more readable and easier to debug (please note that you should wrap array elements in curly braces to get them parsed within double quotes since they are composite variables).

Far more important thing is to validate and sanitize the values you get from the user (through $_POST, $_GET, $_COOKIE arrays). The fact is that you can not trust the user input (you will hear this countless times in web development world). The user can input erroneus data and unintentionally break your application. Or even worse the user can intentionally input malicious data in your web form and do damage to your database and you / your client. A simple example is when user enters specially crafted SQL code in your name field and if you do not check it first you will include that SQL code in your query and send it to your database. i.e the malicious code can expose all your users and passwords or allow login without a password. So it is a really good idea to check whether values are what they are supposed to be and sanitize them (by casting integers, escaping strings, using php filters etc.)

So it is a …

dgibbons82 commented: This is an excellent explanation. Thank you. +0
broj1 356 Humble servant Featured Poster

And before inserting them, check the values and/or escape them.

$firstname = trim(mysql_real_escape_string($_POST['firstname']));
...
dgibbons82 commented: I was curious how to write an escape string. Thank you for showing me. +0
broj1 356 Humble servant Featured Poster

According to the PHP manual the only difference between && and AND is that && is higher in precedence and gets evaluated before AND, otherwise hey do the same thing (logical comparison). This should not affect your example since you use parentheses and ! has higher precedence anyway. Can you post the exact values that get you different results since this is interesting question for me, too.

broj1 356 Humble servant Featured Poster

Two things come to my mind:

Check if the allow_url_fopen in php.ini is set (see http://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen).

If you are on Windows make sure backslashes are escaped or use forward slashes (see http://php.net/manual/en/function.fopen.php).

broj1 356 Humble servant Featured Poster

I do not understand why you run the query if the field is blank. What is the $sql query? Maybe you should negate the condition (if $_POST['txtEmail'] is not empty then...):

if(!empty($_POST['txtEmail']))

You actually have to tell what to achieve or maybe post the whole script.

broj1 356 Humble servant Featured Poster

I am not sure whether I am on the same line but number of simultaneous connections probaly depends on the web server you are using and how it is configured. If you are using Apache maybe this is the starting point:

http://httpd.apache.org/docs/2.2/mod/mpm_common.html#maxclients

Interestingly there is a Web socket protocol but I am completely unfamiliar with it and can be of no help :-)

http://en.wikipedia.org/wiki/WebSocket

broj1 356 Humble servant Featured Poster

The code has errors. You are missing quotes arround strings in lines 6 and 7:

echo "<td>" . '<input name="txtf1" type="text" />' . "</td>";
echo "<td>" . '<input name="txtf2" type="text" />' . "</td>";

Since you do not know whether you are getting all the fields from the database as you would expect it is a good practice to first check for the existence of values first. And you can actually join some echo statements into one. Here is the optimized version:

while($row = mysql_fetch_array($result))
{
    // if $row['ID'] is set assign it to a variable
    // otherwise assign a default value to the variable
    if(isset($row['ID'])) {
        $id = $row['ID'];        
    } else {
        $id = 'Error: No ID!';
    }

    // use the variable directly in double quoted string
    echo "<tr><td>$id</td>";
    // use single quotes elsewhere so you can use double quotes for html attributes
    echo '<td><input name="txtf" type="text"></td>';
    echo '<td><input name="txtf1" type="text" /></td>';
    echo '<td><input name="txtf2" type="text" /></td></tr>';
}
Shougat commented: Thankyou +0
broj1 356 Humble servant Featured Poster

Use mysql_real_escape_string (provided that you use mySql):

$safe_short_description = mysql_real_escape_string("PG for Girls/Ladies/Women in Kasmiri Rd, heart of the Agra city with fully furnished, 2/3 times homely food and all basic amenities.");
$safe_long_description = mysql_real_escape_string("PG's for Girls/Ladies/Women in Kasmiri Rd, heart of the Agra city - Neat, clean & beautiful, PG's for girls/working ladies/women. Fully furnished with TV, refrigerators, geysers and all basic amenities; with We have well designed Girls & Boys PG?s in Kasmiri Rd, Agra with spacious rooms, adequate RO water supply, near bus stand, safe and secure, very well ventilated, environment around is quite peaceful, good location and more. With and without meals, single, double and triple sharing. Available in wide range rent according facilities and amenities.4 hrs power back up; completely homely environment with We have well designed Girls & Boys PG?s in Kasmiri Rd, Agra with spacious rooms, adequate RO water supply, near bus stand, safe and secure, very well ventilated, environment around is quite peaceful, good location and more. With and without meals, single, double and triple sharing. Available in wide range rent according facilities and amenities./3 times homely food.");

Your update syntax seem to be wrong, this is correct:

$query = "UPDATE onlinepg 
SET short_description='$safe_short_description', long_description='$safe_long_description'
WHERE pg_id=2002";

or do you want to do and insert maybe:

$query = "INSERT INTO onlinepg (short_description, long_description)
VALUES ('$safe_short_description', '$safe_long_description')";

Please note that mysql connection has to be established before using mysql_real_escape_string.

broj1 356 Humble servant Featured Poster

the <select> part it is echoing $one_date

This is due to my mistake. In line 32 double quotes should be used (to allow $one_date to be parsed):

echo ">$one_date</option>";

' selected="selected"'; part, could you explain this to me?

This is just a part of html syntax for select element. If an <option> has a selected="selected" attribute that option is selected. In the code above there is a foreach loop that creates <option> parts from an array (the $date_array in your case) for the select element. Within each iteration it checks whether the curent value of an array equals to the value read from the database. If it finds one the attribute selected="selected" is added to that option. Once it works OK have look at the HTML source in the browser.

See also http://www.w3schools.com/tags/tag_option.asp

broj1 356 Humble servant Featured Poster

I could not find any information on whether there are any restrictions for an option value attribute (<option value="any_restrictions_here?">) .I hope dots are permitted. I think browsers encode values to be safe for sending to a server.

broj1 356 Humble servant Featured Poster

A general answer:

  1. read the record that the user is about to change
  2. put each field value as a value of a html form field
  3. for select html elements (drop down as you call it) put a set of option in an array, loop through that array and on each loop compare a value of the element with the value of the field. If they are the same, set selected attribute for that option.

A simple example just to get the idea:

// a query to get the fields
$qry = "SELECT * FROM table WHERE record_id=$ome_id";

// run the query
$result = mysql_query($qry) or die('Some error occured.');

// an array with fields of the querried row
$row = mysql_fetch_array( $result );

// start the form
echo '<form method="post" action="some_page.php">';

// an example of input text element with the value from database field
echo '<input type="text" name="input_name" value="' . $row['field1'] . '" />';

// an example of select element with values from a $dates_array and a selected
// option from database field
$dates_array = array('1.4.2012','2.4.2012','3.4.2012','4.4.2012','5.4.2012',);

// begin the select element
echo '<select name="date_select">';
// loop through the dates_array and add options
foreach($dates_array as $one_date) {
    // start the option tag
    echo '<option value="' . $one_date . '"';
    // if current element of the date_array equals to the date, read from the
    // database, add selected attribute
    if($one_date == $row['date_field']) {
        echo ' selected="selected"';
    }
    // end the option, add the text value for the drop down, end the option …
Biiim commented: spot on +5
broj1 356 Humble servant Featured Poster

Try this query: SELECT DISTINCT date FROM product_data.

broj1 356 Humble servant Featured Poster

I think I found what is the problem. When you have text fields in csv they are supposed to be enclosed in double quotes and that is what Biiim and I were suggesting you. But when you add double quotes to text fields, the hidden input <inputname="csv_output"...> breaks since it also contains double quotes therefore the row is carried over incomplete through POST to the req_reportCSV.php file (in your browser have a look at source code for the main file - you will see errors). The solution is to use single quotes for input attributes like <inputname='csv_output'...> or to use single quotes for text delimiter in csv file.

The following is the code I tested on. Since I did not bother to set up a database I had to make up some test data which you can see in the beginning of the code. The last array (row) of the test data contains commas and it causes no errors.

Remove the test data and uncoment your code to deal with the database. You have to decide which fields are text fields and just surround them with $txt_delim. There are some comments within the code. I hope this will help you.

<?php
// some test data, delete this and read data from your database
$test_data = array(
        array(

        'reqid' => 'reqid1',
        'misRefId' => 'misRefId1',
        'name' => 'name1',
        'date_req' => 'date_req1',
        'cat_name' => 'cat_name1',
        'priority' => 'priority1',
        'detail' => 'detail1',
        'modSAP' => 'modSAP1',
        'req_symptom' => 'req_symptom1',
        'approval' => 'approval1',
        'status' => 'status1', …
broj1 356 Humble servant Featured Poster

If you have only drop down boxes (select elements in HTML terms) in your table, you can assign this function to the checkbox's onclick event:

function selectAll {
    // read all select elements
    var selectArray = document.getElementsByTagname('select');
    // loop thorugh the select elements array
    for(var oneSelect in selectArray) {
        // if you want i.e second option be selected, use index 1
        oneSelect.selectedIndex = 1;
    }
}

You can enhance this function by checking whether checkbox is in checked state or not. If you have other select elements on the page, you can use div or class. The above code has not been tested, it is just an idea.

broj1 356 Humble servant Featured Poster

I have not tried this but I think text fields should be put within text delimiters (usualy double quotes). Try changing your code this way:

$csv_output .= '"$row['misRefId']"' . ", ";
...

This way commas will be within double quotes as part of the text and wont be treated as a field delimiter. Be careful if you have double quotes in text. In that case you have to escape them.

broj1 356 Humble servant Featured Poster

This is because you have a return statement within a foreach loop so the loop gets executed only once. Try this way:

function t6($table)
{
    $rows = '';

    foreach ($table as $key => $value) {

        $rows .= "<tr><td>$key</td><td>$value</td></tr>\n";
    }

    return $rows;
}
broj1 356 Humble servant Featured Poster

I suggest you echo the query to see whether it is what you are expecting. Modifiy the part where you construct the query like this:

// put the query in a variable
$q = "UPDATE books SET Title ='$title_save', Price ='$price_save', Stock='$stock_save' WHERE Code= '$code'";

// submit query using the variable
mysql_query($q) or die(mysql_error(); 

// add this to display the query
die($q);

Now you will be able to see if the query gets constructed OK and you can copy it to phpmyadmin or mysql client and test it.

Two other notes:

  1. your form has no </form> tag. It should be after </table> tag.
  2. your form is missing an action attribute (I think it is required)
broj1 356 Humble servant Featured Poster

This is i.e enter_name.html with a form containing a text input element and a submit button

...
<form method="post" action="show_name.php">
<input type="text" name="entered_name" />
<input type="submit" name="submit" value="submit">
</form>
...

This is show_name.php that receives the post data and displays it; specific file is in the action of the form, specific div is below.

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

    echo '<div id="myname">';

    echo $_POST['entered_name'];

    echo '</div>';
}

This is basics, there is much more to it in practice (security, handling errors, some useful functionality etc)

broj1 356 Humble servant Featured Poster

Basicaly what you do you add a ceckbox to each row in the table, wrap the table in <form></form> tags, add hidden fields which hold the topics and add a submit button. Then you first check if the form has been submitted. If yes you process it (do the insert) and then as usually draw the table. See comments in the code (the code was not tested, but you will get the idea).

<?php

// do the connection stuff
$con=mysql_connect("localhost","root","");
if(!$con) {

    die('can not connect'.mysql_error());
}
mysql_select_db("test", $con );

// check if the form was already submitted, and process it, if it was
if(isset($_POST['submit'])) {

    // check if any of the checkboxes have been selected
    // (selected checkboxes will be returned in a $_POST['cbsave'] array,
    // if none was selected, $_POST['cbsave'] will not be set)
    if(isset($_POST['cbsave']) and !empty($_POST['cbsave'])) {

        foreach($_POST['cbsave'] as $id) {

            // check if an appropriate hidden field with the topic exists and
            // is not empty
            $topic_key = "topic_$id";
            if(isset($_POST[$topic_key]) and !empty($_POST[$topic_key])) {

                $new_topic = $_POST[$topic_key];

                // insert into others_2 table
                $sql = "INSERT INTO others_2 VALUES ($id, '$new_topic')";
            }
        }
    }
}

// select from others to fill the table
$others="others";
$sql="SELECT * FROM $others";
$result=mysql_query($sql);
$num = mysql_num_rows($result);

// commented this one out since it appears lower in the script!
// echo"<thead>
// <tr> <th>#</th> <th> id </th> <th>topic</th></thead>";
// echo"<tbody>";

// put whole thing in a form that has action set to itself (or other page if you wish)
echo '<form action="#" method="post">';

// …
don't give up commented: thank you +0
broj1 356 Humble servant Featured Poster

The easiest way to spot these kinds of errors is to look at the source code in the browser (in Firefox left click on the page and select View page source). Html errors are marked red.

beastpanda commented: you rock +0