I'm a newbie so be kind :) In Javascript, how do I add to a variable the current entry from an array? See my code below.
<?php
$array = mysql_query(SELECT column1 FROM table1 WHERE column2='$entry');
//this returns several entries
<script>
var array=<?=json_encode($array)?>; // the
var data={mouse:mickey, rabbit:roger};
$.each(array, function(){
$.post('dostuff.php',data+','+{array[this]}); // <-- not sure
});
</script>
?>
My question is about the data sent in the "post" jquery command. how do I add the current database entry and send it as part of the data sent in the ajax request. I wrote it roughly, but I'm confident it isn't right the way I wrote it here.
Thanks!
mysql_query returns a handle to be used to actually fetch the result (kind of like a file handle when reading files).
You should use mysql_fetch_array which will give you a row from the result set, or false when you have reached the end.
Remember that the returned array from mysql_fetch_array will contain values with a number as key, as well as the field name as a key, you are probably only interested in the latter; then you should use mysql_fetch_assoc:
// please remember to sanitize $entry before using it in a SQL query.
$result = mysql_query ("SELECT column1 FROM table1 WHERE column2='$entry'");
$query_data = array ();
while (($row = mysql_fetch_assoc ($result)) !== false) {
$query_data[] = $row;
}
...
<script>
var array = <?=json_encode ($query_data);?>;
...
I read your post again, if you are only interested in the value of a single row and a single column then you should use mysql_fetch_field (pass it your $result from mysql_query).
That function will return the value in the first column (in your case field1).
Wrap this value in an array and use json_encode before giving it to your javascript.
Documentation
The callback sent to jQuery.each can optionally take two parameters.
With this knowledge you could write your function as:
$.each(array, function(idx, value){
$.post('dostuff.php',[data, value]);
});
// or.. (depending on what you wanna do)
var post_data = $.extend ({}, data, {array_data: array});
$.post ('dostuff.php', post_data);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With