adam.adamski.96155 43 Junior Poster

Yep, that's works :D
I've used this for years but always hated it because I didn't understand it. Now I guess that although the original function returns false, there is nowhere calling for a return value as there would be if you wrote:
$bool = doFunction(this); if ($bool){...
so by writing:
return doFunction()
The 'return false' returned from the function has some where to return to?

adam.adamski.96155 43 Junior Poster

I tested without return false; initially. The alert alerted and the colours coloured, and when I clicked 'OK', the form went a head and submitted anyway, in FF, Chrome and IE. Yet when I added return false;, it stopped the form submitting, also in all three browsers. There is probably a proper way of acheiving this, and I would like to know what it is :D

adam.adamski.96155 43 Junior Poster

I once put all the UK postcode blocks with their accompanying longitudes/latitudes and northings/westings into a MySQL database, I dont remember exactly how many records, but I think it was more than 20,000. I set up a script that would insert 10 to each query, and 100 queries, and the page would then reload and go on with the next 100X10 block. The whole thing took over 15 mins to complete, but it was all there at the end of it.
Would you really need to recreate the whole database everytime? Could you not only take the new entries to the CSV file since your last update? Maybe check DB for last entry, search CSV for that entry, and grab all previous lines and insert them to DB? How many entries are likely to have backlogged between each user visit? Could the user visit itself not trigger the update process? How often is the CSV file written to? Is data being overwritten or appended?
I love challenges like this, ones you can get your teeth into, rather than making a few bits of text dance :D

adam.adamski.96155 43 Junior Poster

I see the problem:
function validateForm(Qform) expects a parameter passed with the function call, but you pass nothing:
onSubmit="validateForm();
change it to:
onSubmit="validateForm(this); return false;"
and it should work okay.

adam.adamski.96155 43 Junior Poster

but i want to show the error in such a way that name of the tables couldn't be shown...

Is that all?

$query = mysql_query("DELETE FROM table_2 WHERE tchr_id='".$id."'") or die("Oops, we have a problem, please contact the administrator.");

Change message to suit.

adam.adamski.96155 43 Junior Poster

@diafol Haha! Looking at your funny man links, I guess it could be 'David Hill' with a Welsh accent. I had not heard of Vanilla JS and was impressed with the performance stats, but as you mentioned, cross browser compatibility is a real pain with Javascript and jQuery separates the developer from this concern. Also, the jQuery UI looks like it will speed development of User Interfaces like the one I need to administer my quotes database.

adam.adamski.96155 43 Junior Poster

@dafodil It's high time I learnt jQuery!
I sussed the issue was not the duplicate name, but rather the use of:
div.innerHTML += "<textarea name='new_quote[]' />";
as when it grabbed the existing html it was collecting the textarea but not the user-added input. This was solved by adding a new textarea to the DOM rather than the above method, and I googled some jQuery assistance:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(function(){
            $("#button_add_input").click(function(event){
                var textArea = "<textarea name='new_quote[]' />";
                $("#div_quotes").append(textArea);
                $("#div_quotes").append("\n<br />");
            });
        });

And the button to add a text area needed an id: <input type="button" value="Add Text Area" id="button_add_input">
I looked for a way to add the textarea without specifying the html as in something like $("#div_quotes").append(html.textarea), but could not find how to reference a textarea directly, so just added the HTML instead.

adam.adamski.96155 43 Junior Poster

I have the same requirement so I wrote a few lines that would demonstrate the answer to your question and give me a base to work from.

<?php
if (isset($_POST['submitted'])){
    print_r($_POST);
}
?>
<html>
<head>
    <script type="text/javascript">
        function addTextArea(){
            var div = document.getElementById('div_quotes');
            div.innerHTML += "<textarea name='new_quote[]' />";
            div.innerHTML += "\n<br />";
        }
    </script>
</head>
<body>
<form method="post">
<input type="text" name="text_new_author" /><br />
<div id="div_quotes"></div>
<input type="button" value="Add Text Area" onClick="addTextArea();">
<input type="submit" name="submitted">
</form>
</body>
</html>

I thought I would need to keep a total of how many text areas had been added to allow them to have an individual name; area_1, area_2, area_3 etc. However adding [] to the textarea name and using the same name creates an array of values, so no values are lost and a unique name is not needed, print_r($_POST) produces:
Array ( [text_new_author] => New Author [new_quote] => Array ( [0] => New quote 1 [1] => New quote 2 [2] => New quote 3 ) [submitted] => Submit Query )
But this solution causes another problem; if the user adds a new quote and then clicks the 'add text area' button the text entered into the first textarea disappears. I presume this is because a new textarea with the same name is added to the DOM, so maybe I will need a unique name for each added textarea after all :)

adam.adamski.96155 43 Junior Poster

$alert_error = "<script type=\"text/javascript\"> alert('".mysql_error()."') </script>";
In the above line you are referencing 'mysql_error()', but it doesn't exist yet because you did not run the query that produces the error.
Also, you wanted Javascript to alert the value of 'mysql_error()':

if (!$query = mysql_query("DELETE FROM abc WHERE id ='$id'")){
    echo "<script type=\"text/javascript\"> alert('".mysql_error()."') </script>";
    }

The above works when I test it.

adam.adamski.96155 43 Junior Poster

Hey GraficRegret, welcome to Daniweb :)
Your description sounds like a typical use of PHP and MySql, but what help do you specifically need? Is there some code you need some assistance with? Are you looking for general considerations and tips from those who already walked that road?

adam.adamski.96155 43 Junior Poster

There are probably better ways, but I would make a temporary database with mysql and store them in there for easier manipulation. I would write a script to insert a few hundred at a time, and add the records gradually to avoid PHP execution limit, with an echo for every insert to show me that it is still running.
Then I would run the query:
"SELECT * FROM table ORDER BY column ASC, limit 10"

adam.adamski.96155 43 Junior Poster

Hey that's plenty info.
The line needs to be in the while loop (it will change every time), so put it under the line:

while($row = mysql_fetch_array($result)){
    $total = ( $row['field3'] - ($row['field1'] / $row['field2']) );
    //then in the place you want the total to show:
    echo "<td>".$total."</td>";

This presumes your column names really are 'field1', 'field2' and 'field3', if not adjust accordingly. Diafol's idea was good too, well worth investigating, but you would need to show your existing query for instruction on that front.

adam.adamski.96155 43 Junior Poster

Probably can help, but need to see the rest of your code to understand why there is an error.

adam.adamski.96155 43 Junior Poster

This is simple maths, use parentheses to force calculations in correct order:
field3 minus (field1 divided by field2)

$result = ( $row['field3'] - ($row['field1'] / $row['field2']) );
echo "<td>".$result."</td>";
adam.adamski.96155 43 Junior Poster

$check= mysql_query("SELECT FROM accounts WHERE (email='".$email."')");
Select what from accounts? ALL, Id etc? I guess error checking the query would have given an error.

adam.adamski.96155 43 Junior Poster

It may well be possible to get all the things you want in one query, using the Join technique, but that is for someone else to tell you, have a look here :D
As for looping through the way you mentioned:

<?php
$cityArray = new array();
$sql = "SELECT city from table where radius <20miles";
if(!$res = mysql_query($sql)){
    echo mysql_error(); die();
} else {
    while ($row = mysql_fetch_assoc($res)){
        $user_sql = "select users from table where city='".$row['city']."'";
        if(!$user_res = mysql_query($user_sql)){
            echo mysql_error(); die();
        } else {
            while($user_row = mysql_fetch_assoc($user_res)){
                $cityArray[$row['city']] = $user_row['users'];
            }
        }
    }
}
//Now you have an array called $cityArray, the key being the city, the value being an array of users in that city:
foreach ($cityArray as $city => $userArr){
    echo "The city of $city has count($userArr) users living there:\n<br />";
    foreach($userArr as $user){
        echo $user."\n<br />";
    }
}

We really should be moving onto PDO or mysqli now:
Using PHP/PDO with error checking
Using PHP/MySQLi with error checking

I haven't tested the above code, so it may have a typo or two, but I hope it helps you to understand. :D

adam.adamski.96155 43 Junior Poster

I will show you what I mean:

A standard select menu...

<select id="select" onchange="alertSelected(this)">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

...will have the select declaration:
<select id="select">
...and will also have some options:

<option value="1">One</option>
<option value="2">Two</option>

Without the options we can't 'select' one and send that selection in the ajax request.
As an example, we will only alert the selected value using a JS function:

function alertSelected(el){
    var selected = el.options[el.selectedIndex].value; 
    alert(selected);
}

I am running this exact code in my browser and it is alerting the selected value when I choose an option. We need to do the same with your code, which means seeing the structure of the '<option>'s. The way to acheive this is to let the page load, then view the source of the page (standard procedure), then look through the source for the section where the options are set.
You can copy that code and paste it here (hopefully) :)

adam.adamski.96155 43 Junior Poster

If I could see how the options are formed, I could be certain how to proceed, but without seeing I can still make a guess.

change your select declaration to this:
<select name="users" onchange="showUser(this)"

...then add this line:
q_str = str.options[str.selectedIndex].value;
...above the line:
xmlhttp.open("GET","testtwopart1.php?q="+q_str,true);
notice that 'str' was changed to 'q_str' in the line above.

There is a special way of finding out which option was selected and your script wasn't configured to discover it. showUser(this) passes the element itself to the function (this element) and str.options[str.selectedIndex].value gets the value of the selected option. Theoretically, you could send the selected option straight to the function but it would get messy in those parenthesis:
showUser(this.options[this.selectedIndex].value)

If it doesn't work now, I need to see the structure of the select element, specifically the options... yes I know they are pulled from the src file, but they must still exist in the page when it is loaded or there could be no 'onchange' taking place. Right-click and view source to see them.
Good luck :)

adam.adamski.96155 43 Junior Poster

<option="1">1</option>
I need to see this part.
You can view source when the page has loaded and copy/paste here.

adam.adamski.96155 43 Junior Poster

Can you copy the structure of the select list from the source when the page has loaded and post a few lines here?

adam.adamski.96155 43 Junior Poster

It's this line:
xmlhttp.open("GET","testtwopart1.php?q="+str,true);
str is undefined.
utrivedi suggested changing line 35:
<select name="users" onchange="showUser(this.value)"
I agree with him.

You could alert the value of str before you send the ajax request, to make sure it is formed properly.

adam.adamski.96155 43 Junior Poster

@xbat, from what I can see, 'q' is not defined in your JS code, it is not even referenced, so it can't be JS that's giving the error. The only way I can understand this undefined error regarding 'q' is the processing page, testwopart1.php.
The beginning of the script (testwopart1.php), references $_GET['q'] and if this variable is not defined, you will get an error of type notice concerning an 'undefined key'. Veedeeo's suggestion to use a test: if(isset($_GET['q'])) is the way to avoid this error. If you want to test testwopart1.php, you can go directly to the page and add "?q=something" into the address bar (change the something to what you think should be sent) and see what the output is. If the output looks good, then I would put a line at the top of testwopart1.php: echo "some random words"; die(); and then alert the xmlhttp.responseText to the screen on return to the ajax function. From these two steps you can get a better idea of where the problem lies.
I find this type of problem standard issue whenever I have used Ajax. Good luck :)

adam.adamski.96155 43 Junior Poster

I don't see how the hidden input can possibly be populated with the intended value because it is PHP that echoes the value and PHP won't do anything once the page is loaded. $_POST['brand'] needs to exist when the page is loaded for PHP to echo the value onto the page. Pritaeas idea to make your own submit function and use Javascript to populate the hidden element and then submit the form is what I would do. If I have misunderstood your intentions, please excuse me :)

adam.adamski.96155 43 Junior Poster

Ok, understood.
Presumably you want the input validated before the form is submitted and only alllowed to continue if the input passes the validation test.
You need to capture the submission of the form and take control which you almost do:
<form onsubmit='checkform();'>
This may not be the correct way, but I have always added return false; at this point to stop the form submitting, it has always worked as intended for me:
<form id="myform" onsubmit='checkform(); return false;'>
Now the function has control of the form input and can decide if the submission is to be refused and a reason given to the user, or allow the form to continue.

If it is decided that the form is okay and can procede the following command will acheive it:
document.getElementById('myForm').submit();

for reference:

<SCRIPT type "text/JavaScript">
function checkform(){
    var user_value = document.getElementById('user').value;
    var error_div = document.getElementById('error_div');
    if (user_value.length < 5){
        error_div.innerHTML = "Please enter a valid Username (5chars+)";
    } else {
        document.getElementById('myForm').submit();
    }
}
</SCRIPT>

and the html:

<form id="myForm" onsubmit='checkform(); return false;'>
<input type="text" id="user" />
<input type="submit" value="submit"/>
<div id="error_div">initial data</div></form>
adam.adamski.96155 43 Junior Poster

You say the code is dead.
What does that mean?
What do you think the code should do?

adam.adamski.96155 43 Junior Poster

if (user.lenght<5) <-- typo of the word length. There may be other things, but your code is so messy I need to format your nested loops to make any sense of them.
There is a great article here regarding the format of your code and loops:
http://phpmaster.com/practical-refactoring-1/

adam.adamski.96155 43 Junior Poster

Hey that's great :)
Can you mark this thread as solved?
Thanks!

adam.adamski.96155 43 Junior Poster

Both of your functions have the same name, so presumably the second version is overwriting the first one, meaning that really there is only one function - the second one. Did you try to name the two functions differently and add both functions to the onclick event of the button?

function OnButtonA(){
//send form to location one.
}
function OnButtonB(){
//send form to location two.
}
onclick="OnButtonA(); OnButtonB();"

If this doesn't work, I would try to use Ajax to achevieve the desired result.

adam.adamski.96155 43 Junior Poster

That JS line that produces the radio group has gone horribly wrong :D
The best way forward is to look at the exact syntax of a static radio group:

<input type="radio" name="overall" value="0">0

then escape the double quotes:

<input type=\"radio\" name=\"overall\" value=\"0\">0

then put it inside the document.write function:

document.write("<input type=\"radio\" name=\"overall\" value=\"0\">0");

That would produce the static radio button, but we need to make allowance for the changing values (1-10) -

value=\"" + i + "\">" +i

...and altogether:

document.write("<input type=\"radio\" name=\"overall\" value=\"" + i + "\">"+i);

Wrap the for loop inside a function and call it to the page when needed:

<script type="text/javascript">
function makeRadio(){
    for(i = 1; i < 11; i++) {// produce values 1-10, using '0' can be problematic for validation.
        document.write("<input type=\"radio\" name=\"overall\" value=\"" + i + "\">"+i);
    }
}
</script>

This will produce 10 radio buttons, all of the same name, 'overall'. You want to make a link that will alert the currently selected radio button? You tried to use the getElementsByName() function inside a link, and then echo it out... but there are many elements with that name, how can this work without looping through the radio buttons?

We need another function to loop through relevant elements and discover which one is selected:

<script type="text/javascript">
function getSelectedRadio(){
    var radioArray = document.getElementsByName("overall"); //make an array with all radio buttons of name 'overall'
    var total = radioArray.length; //how many are there? …
adam.adamski.96155 43 Junior Poster

There could be a problem with your UPDATE statement.
I recommend using error checking with all database transactions, for a great guide look here: mysqli with error checking
If your variables are of string type, your update should look like this:
"UPDATE tablename SET column='value' WHERE id='value'"
I know you are inserting integers, and they don't need to be quoted, but it is possible that $visitid is of string type as we can't see the MySQL column type that supplies the value.
You can try quoting your variables to see if it helps as it is a minimal overhead for the database server to convert variable type with such a small and simple query.

adam.adamski.96155 43 Junior Poster

I copied your situation and tested the code on my own wamp server and it worked fine. I moved the include file above the document root and it still worked okay. This wamp server is so sensitive it throws an error if I look at the screen funny.

adam.adamski.96155 43 Junior Poster

@MWEB, you are drowning in confusion, lets go over it step by step.

Make a form, set the action to the page you want to process the details and the method(get).

Collect form variable/s ready for database search:
$res = $_GET['res'];

Make connection using error checking:

if(!$con = mysqli_connect($host, $user, $pass)){
    echo mysqli_error(); die();
    }

Select database using error checking:

if(!mysqli_select_db("db")) {
    echo mysqli_error(); die();
    }

Build database query:
$sql = "SELECT id, price FROM edit WHERE id='$res' ORDER BY id ")

Send query using error checking:

if(!$res = mysqli_query($sql)){ //error, kill script and tell me what is wrong.
    echo mysqli_error(); die();
} else { //no error continue...
    if(mysqli_num_rows($res)){//no error, but are there any matches?
        while($row = mysqli_fetch_assoc($res)){//there are matches, do the thing...  
            $id = $row['id'];//this step not essential, 
            $price = $row['price'];// but keeps code clean and easy to read.
            echo "$id: The price is $price,<br />"// <--see? clean, easy to read :D
        }
    } else {//no matches, say so
        echo "There were no matches to the search.";
    }
}

Pritaeas has written an excellent guide: http://www.daniweb.com/web-development/php/code/434480/using-phpmysqli-with-error-checking
If there are no DB errors and still no results, try running your query in PHPMyAdmin. You can echo your query to the screen:

$sql = "SELECT id, price FROM edit WHERE id='$res' ORDER BY id ");
echo $sql; die();

...and paste it directly into PHPMyAdmin to see if there is any difference.
Good luck! :D

adam.adamski.96155 43 Junior Poster

@Vingklippt, we were all new once, nothing to be ashamed of :D

@urtrivedi - I'm sure you are just trying to be helpful, but will you also change his nappy after you fed him? At the top of the PHP forum there is a post by the world renown Pritaeas "read this before posting" and one of the points made:

"Do not ask for code. We are not a coding service. We will help you fix your code. If anyone posts a complete working solution for you, they are enabling cheaters. If you use that code you are a cheater."

adam.adamski.96155 43 Junior Poster

@Vingklippt - Exactly, the variables are empty and you are trying to insert little packets of nothingness into your database :D

When you specified method="post" in your form declaration, what does that mean?

It means that the variables you are collecting in your form ($titel, $ingrediens and $pris), will be available to your script on update-success.php (the action of your form declaration) in the 'post' array -
$_POST['titel'], $_POST['ingrediens'] etc...

You could have put method="get" into your form, and then the collected data would be available in the $_GET array.

This is the very basics of PHP/Mysql, you need to be able to do this in your sleep :)

adam.adamski.96155 43 Junior Poster

Your update-success.php page has the statement -

$sql="UPDATE pizza_menu SET titel='$titel', ingrediens='$ingrediens', pris='$pris' WHERE id='$id'";

...but what is the value of $titel, $ingrediens and $pris when the page loads?
at the top of your update-success.php page, put this:

echo "titel = $titel, ingrediens = $ingrediens, pris = $pris"; die();

The value of the variables will be shown on your screen, what are the values?

adam.adamski.96155 43 Junior Poster

I am trying to create a form that updates mySQL-database.

Where is the form?

adam.adamski.96155 43 Junior Poster
$query = mysqli_query($con, "SELECT id,price FROM edit WHERE id=$res");

...this was correct, but lacked the 'ORDER BY' clause, so :

$query = mysqli_query($con, "SELECT id, price FROM edit WHERE id=$res ORDER BY id");

...is all that needed changing, but when urtrivedi changed it to:

WHERE id='{$_GET['res]}'

...it went horribly wrong because it should be '{$_GET['res']}' (utrivedi missed a single quote after the s). I prefer to keep the MySQL statement clean and easy to read as Andreret demonstrated.
This is the bread and butter of PHP/MySQL web development, you should read a thousand tutorials until you can do this in your sleep.

AndreRet commented: Thanx +12
adam.adamski.96155 43 Junior Poster

Pritesh, I replicated your pages and your database on my local machine.
form.php is all good.
save.php had a few problems on my machine:

//I wrapped the next part in an isset() to stop the undefined index error.
if(isset($_POST['prenom'])){
    $prenom=$_POST['prenom'];
    $nom=$_POST['nom'];
    $humeur=$_POST['humeur'];
}

As for the date comparison, I had problems with my machine caching the date and giving false information, so I changed the column type to int and stored a timestamp instead of a date.

$now = date("U"); //num seconds since jan1 1970
$one_day = ($now -(60*60*24));//minus 1 day (60secs * 60mins * 24hrs)
$query = "SELECT * FROM `Humeur_log` WHERE `nom`='$nom' AND `prenom`='$prenom' AND (`datelog` > $one_day)";

Now it will return all rows that were posted in the last 24hrs. There is certainly a better way to acheive this, but this is how I worked it out.

//The updated insert statement.
$sql="INSERT INTO `Humeur_log` (`prenom`, `nom`, `datelog`) VALUES ('$prenom','$nom', $now)";

I tested on name AND surname (prenom && nom) as it made more sense to me like that.
Do you not want to store the mood also in the database?

Questions:
Where is it writing twice?
Which column needs dynamically sorting and when?
Which name should be unique?

adam.adamski.96155 43 Junior Poster

Can you post all your latest code, and re-tell what you want to acheive?

adam.adamski.96155 43 Junior Poster

You have two options -
1. Use Javascript to verify that both passwords match (and the rest of the form is completed correctly) before the form is submitted. Your script appears to be configured that way looking at this line:
<form name="registration_form" method="post" action="register.php" onsubmit="return Validate();">
2.Use PHP to check both passwords once the form has been sent and echo a relevant message to the user if there is a problem with the data submitted.

adam.adamski.96155 43 Junior Poster

a tablename that consists only of digits may need to be encapsulated with `backtick`s - look here

adam.adamski.96155 43 Junior Poster
adam.adamski.96155 43 Junior Poster

I see no reference to "%i" in the manual.

adam.adamski.96155 43 Junior Poster

if($_POST['var']){if there is no post[var] defined, I get the undefined index error.
if(isset($_POST['var'])){I get no error.

Also in this case I think the ternary if syntax would be useful:
<?php echo (isset($_POST['email']) && empty($success)) ? $_POST['email'] : "";?>

adam.adamski.96155 43 Junior Poster

Post your code, what do you have so far?

adam.adamski.96155 43 Junior Poster

file_get_contents() to get the whole csv file into a string.
explode() the string on new line character giving many single $line strings.
foreach loop through all $lines:
explode() the $line on ',' into $pieces
foreach loop through $pieces.
if first $piece of line, check value:
if holds value like "Product A", store in $variable.
if holds value like "", change value to $variable.
implode() $pieces to $line using "," as glue.
add "\n" to each $line.
store $line in $newLines array.
foreach loop through $newLines array adding to DB, outputting to excel format...

adam.adamski.96155 43 Junior Poster

@Will Gresham

echo is a language construct, and can take multiple arguments. If you want to get down to micro seconds, it is also slower to use concatenation in an echo instead of comma separated values...

Point noted and thanks for the correction :D

adam.adamski.96155 43 Junior Poster

Line 8: (mysql_fetch_row($result)>0) is this intended? do you mean (mysql_num_rows($result)>0) ?
All your database interactions should be ready for errors:
if (!$var = mysql_query()) die(mysql_error())
Line 16: the string $sql is wrong, look here to see why: http://www.daniweb.com/web-development/databases/mysql/threads/437020/php-mysql-wont-post#post1877407
Lines 24+27: You don't use a comma to concatenate a string.
Line 24: $_POST["prenom "] <- the key has whitespace.

As for the double entry into the database and the text file, is this ALL the code? I can't see where it is happeneing twice, or even how this script is running with the comma's for concatenation.

adam.adamski.96155 43 Junior Poster

Ahhh okay :)
The replacement value would be
""
(empty quoted string).

adam.adamski.96155 43 Junior Poster