PHP - How Can I Check If Associate Array Element Is Empty Or Not?
Code: [Select]
Array ( [Comment] => Array ( [post_id] => 1 [name] => cc [email] => [body] => spam ) ) How can i check if email is empty or not? Is there any php built in function? Should i use foreach? Similar Tutorialsi am trying to check if the array element (which would be a file) is null or not. when i run it, uploading one file, it says "Please select some files to upload first!" X 3. what am i doing wrong? my code: http://pastebin.com/m0k3fEd2 I have the form / script below that works to add multiple rows of data with one query. One thing I did not think about is what if the first set of form fields are filled and the second is not. Currently the script insert an empty row. I'm sure how I would go about checking for an empty row and if there is an empty row ignore it and do not put it in the DB. Can someone point me in the right direction? Code: [Select] <?php // Begin the script for this page if (isset($_POST['submit'])) { //Assign each array to a variable $id = $_POST['id']; $store = $_POST['store']; $item = $_POST['item']; $itemprice = $_POST['itemprice']; $itemnumber = $_POST['itemnumber']; $couponvalue = $_POST['couponvalue']; $couponsused = $_POST['couponsused']; $limit = count($id); $values = array(); // initialize an empty array to hold the values for($i=0;$i<$limit;$i++){ $store[$i] = check_input($store[$i]); $item[$i] = check_input($item[$i]); $itemprice[$i] = check_input($itemprice[$i]); $itemnumber[$i] = check_input($itemnumber[$i]); $couponvalue[$i] = check_input($couponvalue[$i]); $couponsused[$i] = check_input($couponsused[$i]); $values[$i] = "( '{$id[$i]}', '{$store[$i]}', '{$item[$i]}', '{$itemprice[$i]}', '{$itemnumber[$i]}', '{$couponvalue[$i]}', '{$couponsused[$i]}')"; // build the array of values for the query string } $query = "INSERT INTO `item` (user_id, store, item, itemprice, itemnumber, couponvalue, couponsused) VALUES " . implode( ', ', $values ); // Form the query string and add the implod()ed values if (!mysql_query($query,$link)){ die('Error: ' . mysql_error()); } else { $added = "Your items have been added."; } } ?> <div class="pageContent"> <div id="main"> <div class="container"> <?php echo $added; if($_SESSION['id']){ echo '<form action="" method="post">'; echo '<table cellpadding= "4">'; echo '<tr>'; echo '<input type="hidden" name="id[]" id="id[]" value='.$_SESSION['id'].' />'; echo '<td><DIV CLASS="p2"><b>Store</b></div>'; echo '<input type="text" name="store[]" id="store[]" size="15" maxlength="255"/></td>'; echo '<td><DIV CLASS="p2"><b>Item</b></div>'; echo '<input type="text" name="item[]" id="item[]" size="15" maxlength="255"/></td>'; echo '<td><DIV CLASS="p2"><b>Item Price</b></div>'; echo '<input type="text" name="itemprice[]" id="itemprice[]" size="5" maxlength="255"/></td>'; echo '<td><DIV CLASS="p2"><b>Item #</b></div>'; echo '<select name="itemnumber[]" id="itemnumber[]"><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option><option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option><option value="17">17</option><option value="18">18</option><option value="19">19</option><option value="20">20</option></select></td>'; echo '<td><DIV CLASS="p2"><b>Coupon Value</b></div>'; echo '<input type="text" name="couponvalue[]" id="couponvalue[]" size="10" maxlength="255"/></td>'; echo '<td><DIV CLASS="p2"><b># Coupons</b></div>'; echo '<select style="width: 60px;" name="couponsused[]" id="couponsused[]"><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option><option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option><option value="17">17</option><option value="18">18</option><option value="19">19</option><option value="20">20</option></select></td>'; echo '<td><DIV CLASS="p2"><b>Doubled Coupon</b></div>'; echo '<select style="width: 75px;" name="doubledcoupon[]" id="doubledcoupon[]"><option value="1">Yes</option><option value="0">No</option></td>'; echo '</tr>'; echo '<tr>'; echo '<input type="hidden" name="id[]" id="id[]" value="'.$_SESSION['id'].'" />'; echo '<td><input type="text" name="store[]" id="store[]" size="15" maxlength="255"/></td>'; echo '<td><input type="text" name="item[]" id="item[]" size="15" maxlength="255"/></td>'; echo '<td><input type="text" name="itemprice[]" id="itemprice[]" size="5" maxlength="255"/></td>'; echo '<td><select name="itemnumber[]" id="itemnumber[]"><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option><option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option><option value="17">17</option><option value="18">18</option><option value="19">19</option><option value="20">20</option></select></td>'; echo '<td><input type="text" name="couponvalue[]" id="couponvalue[]" size="10" maxlength="255"/></td>'; echo '<td><select style="width: 60px;" name="couponsused[]" id="couponsused[]"><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option><option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option><option value="17">17</option><option value="18">18</option><option value="19">19</option><option value="20">20</option></select></td>'; echo '<td><select style="width: 75px;" name="doubledcoupon[]" id="doubledcoupon[]"><option value="1">Yes</option><option value="0">No</option></td>'; echo'</tr>'; echo'<tr>'; echo '<input type="submit" name="submit" value="Submit Item">'; echo'</tr>'; echo '</table>'; echo'</form>'; } else { echo '<h1>Please, <a href="index.php">login</a> and come back later!</h1>'; } ?> </div> </div> </div> so I have this code: Code: [Select] <input type='checkbox' name='title8' value='$title8' /></td><td><strong>$title8</strong> <br /> $date8 <br />$ $price8<input type='hidden' name='price8' value='$price8'> how do I make is so that the hidden field is only going to submit if the checkbox is checked........ Hi there, Basic question, but I can't seem to find a page in the PHP docs that answers (though I'm sure such a one exists, I just can't seem to think up the right search terms - anyway) My question is: is there a short-hand way to use a value from an associative array as the key in another associative array? So for example, given this array: $the_array = array(0 => array('name': 'the_name', 'value' : 'the_value'), 1 => etc....); then this kind of foreach loop doesn't work Code: [Select] $new_data = array(); foreach($the_array as $element){ $new_data[$element['name']] = $element['value']; } Obviously I can just save out the values, like $name = $element['name'] --- but I was just wondering if there was a more efficient way to do it? Cheers, PS. I tried encapsulating with {} - i.e. $new_data[{$element['name']}] --- but that also fails. I am just trying to use Associate array in another php file through session.
file1.php <?php $age = array(); $_SESSION["age"] = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); foreach($_SESSION["age"] as $x => $x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>\n"; } ?> OUTPUT: Key=Peter, Value=35 Key=Ben, Value=37 Key=Joe, Value=43 file2.php <?php session_start(); foreach( $_SESSION["age"] as $x => $x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>\n"; } ?> OUTPUT: PHP Notice: Undefined index: age in session.php on line 3 PHP Warning: Invalid argument supplied for foreach() in session.php on line 3 Why am I getting this error? Above is just example I tried to demonstrate for asking question for other issue, unfortunately I got new error in this example. But actual issue was, I was trying to plot graph using library which requires only Associate array, where the data is formed in file1.php. But I get only last index value displayed in file2.php even in graph or in echo. I don't understand why other values are not displayed in file2.php Please point me what is going wrong, Thanks. Ok so i have registration page on my webs but i didn't work on empty fields so how could i check all fields? Code: [Select] //if no name if(!$name){ $error = "Username missing."; } //if no pass if($pass == false){ $error = "$error,Password missing"; } //if no pass conf if($pass_conf == false) { $error = "$error,Pass conf missing."; } //if no email if($email == false){ $error = "$error,Email missing."; } //pass conf if($pass != $pass_conf){ $error = "$error,Passwords do not match."; } echo "<script>alert('$error');</script>;"; //header("Location: register.php"); My script gives same results every time (even if i fill any of fields)...also if i un-comment header command it wont show alert..it just reloads the page So can anyone help me with this? Thanks.. Hi, I have a form containg three text inputs and one text area. On the php page that processes the form, I want to check first to make sure the user entered something (input field is not empty) before processing the form. I'll just provide a skeleton of form processing page below. *(I'm save space and time by omitting the form itself but he text inputs fields have the following name attributes "name", "company", "email", and the textarea field's name attribute is "message" ) I'll do my best to explain the code in further detail within the code comments. Code: [Select] <?php //Turn on output buffering. Allows for headers to be called anywhere on script. See pg228 Ulman. ob_start(); if (isset($_POST['submit'])) { // Initialize a session to keep tract of error and success messages: session_start(); //Define a session variable that keeps tract of how many times user accesses page. $_SESSION['views'] = 1; // Connect to the database. require('config/config.php'); //Check for errors. //Check to make sure they entered their name. if (!empty ( $_POST['name'])) { $a = TRUE; } else { $a = FALSE; //This variable will be echoed on the form if field is missing a value $_SESSION['name'] = '*Please enter a valid name.'; } //Check to make sure they entered their company name. if (!empty ( $_POST['company'])) { $b = TRUE; } else { $b = FALSE; //This variable will be echoed on the form if field is missing a value $_SESSION['company'] = '*Please enter the name of an institution you are affiliated with.'; } //Check to make sure email is valid. if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $_POST['email'])) { $c = TRUE; }else { $c = FALSE; //This variable will be echoed on the form if field is missing a value or email format is wrong. $_SESSION['email'] = '*Please enter a valid email address.'; } //Check to make sure they entered their message. if (!empty ( $_POST['message'])) { $d = TRUE; } else { $d = FALSE; //This variable will be echoed on the form if field is missing a value $_SESSION['message'] = '*Please enter your message.'; } //If no errors if (empty($_SESSION['name'] ) && empty($_SESSION['company'] ) && empty($_SESSION['email'] ) && empty($_SESSION['message'] ) ) { //Insert data into database. $query = "INSERT INTO table... ; $result = mysql_query($query) or die("Data could not be inserted into table because: " .mysql_error()); if (mysql_affected_rows() == 1) { // Display success message //This variable will be echoed on the form if everything is filled out correctly. $_SESSION['sent'] = "Your email has been sent. We will get back to you shortly."; // Display contact page (the page containing the form) header("Location: contact_page.php"); exit(); }else{die(mysql_error());} //Display error messages. } else {// if errors array is not empty // Display page (page containing the form) header("Location: contact_page.php"); exit(); }//End of if there are errors. }//End of if submit. ?> So there it is. Everything works fine except that the part which checks if the textarea (named "message") is empty, doesn't work. If I click the submit button without filling out any field, the appropriate error messages are printed for the text input fields but not the text area field. If I fill out all fields correctly and leave the "message" field blank, the form gets processed correctly and values are placed in the database and the success message is printed out. This is also the case when I enter a value for "message" textarea field. Now I tried something. I changed the textarea to a text field and the $_SESSION['message'] variable finally got echoed when I left this field blank. So apparently, the problem arises from the fact that the named attribute from a textarea tag is not being processed correctly?? Who knows what's going wrong here? I have two array, how I can have if else to check if both array1 and array2 are empty? if (empty both arrays) { } else { even if one of them are not empty } i am pulling the login date from the databases and i want it to check if the variable is empty and if it is echo Never Loged In and if it not empty echo the date <?php include'db.php'; $id=$_GET['id']; $sql=mysql_query("SELECT * FROM admin WHERE id='$id'")or die(mysql_error()); while($row=mysql_fetch_array($sql)) { $date=$row['login_date']; if($date > 0) { echo"Never Loged In"; } else { echo"$date"; } } ?> Hi i would like to know what is the best way to check if a textarea or an input box is empty. Is the empty function effective? Been trying to find an answer and keep running around in circles... I have: ( left test echos in there) if ($r['left_house_number'] != '') { /* Now see what they are supposed to get */ $left_customer_query = "SELECT * FROM customer WHERE house_number ='".$r['left_house_number']."' AND street = '".$r['left_house_street']."' AND route_number = '".$_SESSION['route_number']."'"; // echo "SELECT * FROM customer WHERE house_number ='".$r['left_house_number']."' AND street = '".$r['left_house_street']."' AND route_number = '".$_SESSION['route_number']."'"; $left_customer_result = mysql_query($left_customer_query) or die(mysql_error()); $left_customer_result_count = mysql_num_rows($left_customer_result); echo $r['left_house_number'].' =lhn1'; while ($lrow = mysql_fetch_array($left_customer_result)) { echo $r['left_house_number'].' =lhn2'; /* See if there is any customer if not display blank row */ echo $left_customer_result_count.' = count '; if ($left_customer_result_count < 1) { echo $r['left_house_number'].' =lhn3'; echo '<span class="delivery_nothing">'.$r['left_house_number'].' </span> 1<span class="delivery_nothing">'.$r['left_house_street'].' '; } else { /* Have a customer, now check to see if they are supposed to get something */ if ($lrow['status'] != "AC" && $lrow['status'] != "VH") { /* Customer is stopped or on vacation so show house number and street not bolded */ echo '<span class="delivery_nothing">'.$r['left_house_number'].'</span>2<span class="delivery_nothing">'.$r['left_house_street']; echo $r['left_house_number'].' =lhn4'; } else { /* Now check for correct delivery day and return data */ if (Show_Product($lrow['product']) == '1') { echo $r['left_house_number'].' =lhn5'; echo '<span class="delivery_bold">'.$lrow['house_number'].'</span><span class="delivery_bold">'.$lrow['placement'].'</span><span class="delivery_bold">'.$lrow['street'].'</span>'; echo Product_Formater($lrow['product']); } I have tried... if ($left_customer_result_count < 1) { if ($left_customer_result_count == 0) { if ($left_customer_result_count == '') { if ($left_customer_result_count === 0) { And I can't get it to work. the count "test echo" is either blank or 1 If I echo the sql statement with values I know aren't in the db and paste it into phpmyadmin: SELECT * FROM customer WHERE house_number = '3333' AND street = 'Chili Avenue' AND route_number = '68-24-630' I get: "MySQL returned an empty result set" And if I change it to something that is in the db: SELECT * FROM customer WHERE house_number = '3019' AND street = 'Chili Avenue' AND route_number = '68-24-630' I get: "Showing rows 0 - 0 (1 total, Query took 0.0012 sec)" So what do I have to do to get this to work right? What does it actually output when there are no results returned? thanks, Now this one is a bit of a shit head. I am using a really comprehensive class i found on on the web for upload / re-size / crop but i want to be able to override it's error handling and i am not good enough to start modifying the code in the class with out fucking it up. Firstly i will show you how i have invoked the class. Code: [Select] if( isset($_FILES['image'] ) ) { //Class includes include("../scrips/php/cms/database.insert.class.php"); include ("../scrips/php/cms/img.upload.resize.crop.class.php.php"); //----------|Start: upload, resize & save $your_image = new _image; //----------| Upload orginal image $your_image->uploadTo = 'uploads/'; $upload = $your_image->upload($_FILES['image']); //----------| Resize and upload small thumbnail $your_image->newPath = 'thums/'; $your_image->newWidth = 50; $your_image->newHeight = 50; $resized = $your_image->resize(); //----------| Resize and upload medium thumbnail $your_image->newPath = 'thums2/'; $your_image->newWidth = 100; $your_image->newHeight = 100; $resized = $your_image->resize(); //----------| Getting the image name to insert into the database futher on in the code $name = $resized; $img_str = explode("/",$name); $final_img_name = $img_str['1']; echo "Article has been added!"; //----------------|end //----------------| Start database insert (class manipulation) $table = "blog_posts"; $title = "'".$_POST['ArticleTitle']."',"; $img = "'".$final_img_name."',"; $post = "'".$_POST['ArticleBody']."',"; $aurthor_id = "'1',"; $category_id = "'".$_POST['Category']."',"; $date_posted = "NOW()"; $values = array("$title","$img","$post","$aurthor_id","$category_id","$date_posted"); $fields = array('title,','img,','post,','aurthor_id,','category_id,','date_posted'); $obj= new DatabaseInsert; $obj->DatabaseConnectionRequire(); $obj->ArticleInsert($values,$fields,$table); //----------------|end } As you can see it's fairly basic. What i want to do is before it runs this script and starts including/invoking the class etc, i want to be able to check to see if there is a value been posted from a FILE FORM OBJECT and if there is to proceed with this script, alternatively i want it to execute another code which will handle it in regards to the concept of my page. A simple javascript alert with be ok providing it reloaded the page to it's default state. If any one can help me here i would appreciate it a lot. Thanks Hey guys, Really dumb question, but I want to check if a bunch of variables are all not empty. Then, if they aren't, I want to execute a mySQL query. Right now I have this which I know is wrong because it doesn't work the right way: Code: [Select] if($album != null || $artist != null || $year != null || $genre != null) { // stuff here... } Obviously I want all of those variables to be checked if they are empty or not. I did a quick Google and found that checking if the variables are null wouldn't be the correct way of solving this situation because an "empty string" is still not null? Anyway, any help would be appreciated. I'm pretty sure it's really simple :p. I am using a script to take postcodes and give distances between them and list all postcodes within a radius. Where it should list all the postcodes in the radius it provides and empty array - any clues?? the table is 'geodb' relevant fields are postcode place latitude longitude and the code is Code: [Select] if(isset($_GET['Search'])) { $postcode = strtoupper($_GET['postcode']); $radius = $_GET['radius']; echo $postcode . '<br>'; echo $radius . '<br>'; $conn = mysql_connect(/*credentials removed*/) or die('db connect error: ' . mysql_error()); mysql_select_db('db379121', $conn) or die('could not select database'); $sqlstring = "SELECT * FROM geodb WHERE postcode = '".$postcode."'"; $result = mysql_query($sqlstring); $row = mysql_fetch_assoc($result); ++++++++++++++++++++++++++++++++++++++++++ var_dump($row); // seeing whqat is in the array - returns one result (array(9) { ["id"]=> string(1) "1" ["countrycode"]=> string(2) "GB" ["postcode"]=> string(4) "AB10" ["place"]=> string(8) "Aberdeen" ["postaltown"]=> string(8) "Aberdeen" ["region1"]=> string(8) "Scotland" ["region2"]=> string(13) "Aberdeen City" ["latitude"]=> string(12) "57.135813090" ["longitude"]=> string(12) "-2.121224030" })// ++++++++++++++++++++++++++++++++++++++++++ $lng = $row["longitude"] / 180 * M_PI; $lat = $row["latitude"] / 180 * M_PI; echo $lat . '<br>'; echo $lng . '<br>'; ++++++++++++++++++++++++++++++++++++++++++ echo to check that there is a value here - i get lat 0.99720805922458 lng -0.037022343495923 ++++++++++++++++++++++++++++++++++++++++++ mysql_free_result($result);} $sqlstring2 = "SELECT DISTINCT geodb.postcode,geodb.place,(6367.41*SQRT(2*(1-cos(RADIANS(geodb.latitude))*cos(".$lat.")*(sin(RADIANS(geodb.longitude))*sin(".$lng.")+cos(RADIANS(geodb.longitude))*cos(".$lng."))-sin(RADIANS(geodb.latitude))* sin(".$lat.")))) AS Distance FROM geodb AS geodb WHERE (6367.41*SQRT(2*(1-cos(RADIANS(geodb.latitude))*cos(".$lat.")*(sin(RADIANS(geodb.longitude))*sin(".$lng.")+cos(RADIANS(geodb.longitude))*cos(".$lng."))-sin(RADIANS(geodb.latitude))*sin(".$lat."))) <= '".$distance."') ORDER BY Distance"; $result = mysql_query($sqlstring2) or die('query failed: ' . mysql_error()); $str = "<table width=\"300\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">"; $str .= "<tr>"; $str .= "<th>postcode</th>"; $str .= "<th>city</th>"; $str .= "<th>distance</th>"; $str .= "</tr>"; while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $str .= "<tr><td>".$row["postcode"]."</td><td>".$row["place"]."</td><td>".round($row['Distance'])."km</td></tr>"; } $str .= "</table>"; ++++++++++++++++++++++++++++++++++++++++++ var_dump($row["place"]); // this produces null ++++++++++++++++++++++++++++++++++++++++++ mysql_free_result($result); mysql_close($conn); echo $str; Is there a built in function to remove empty array values for example: change Array ( [0] => Bob [1] => [2] => Ryan [3] => Jane ) to Array ( [0] => Bob [1] => Ryan [2] => Jane ) Thanks I want to merge some arrays as Code: [Select] $mixing = array_merge($mixedresult1, $mixedresult2, $mixedresult3);but the arrays can be empty sometimes. In this case, I will get an error for the empty array as Code: [Select] PHP Warning: array_merge() [<a href='function.array-merge'>function.array-merge</a>]: Argument #1 is not an arrayHow I can avoid this error by omitting empty arrays? Hey guys i am currently building a very complex form for one of my clients. The for has ALOT of imputs and can also generate new one automaticly using javascript. My problem is that come of them returns empty arrays while other works. Is there a maximum or some kind that a form can submit at the time? i made a print_r on the $_POST var and this is what i got (I tooke out all the other arrays but theres a lot more then what i am posting) [...] print ('<tr> <td> <input type="text" size="9" name="styleenc[]" value=""> </td> <td> <input type="text" size="9" name="couleurenc[]" value=""> </td> <td> <input type="text" size="2" name="c_y[]" value=""> </td> <td> <input type="text" size="2" name="c_a_s[]" value=""> </td> <td> <input type="text" size="2" name="c_a_l[]" value=""> </td> <td> <input type="text" size="2" name="c_a_o_s[]" value=""> </td> <td> <input type="text" size="9" name="descenc[]" value=""> <input type="hidden" size="9" name="invisible3[]" value="3"> </td> </tr>'); [...] Code: [Select] Array ( [styleenc] => Array ( [0] => [1] => [2] => [3] => [4] => ) [couleurenc] => Array ( [0] => [1] => [2] => [3] => [4] => ) [c_y] => Array ( [0] => [1] => [2] => [3] => [4] => ) [c_a_s] => Array ( [0] => [1] => [2] => [3] => [4] => ) [c_a_l] => Array ( [0] => [1] => [2] => [3] => [4] => ) [c_a_o_s] => Array ( [0] => [1] => [2] => [3] => [4] => ) [descenc] => Array ( [0] => [1] => [2] => [3] => [4] => ) [invisible3] => Array ( [0] => 3 [1] => 3 [2] => 3 [3] => 3 [4] => 3 ) [emplacement] => sdcwedf ) They should all have values i don't get it ... the only one that has values is invisible3 that has been manualy specified with value="3" I'm creating a quick survey app for my son's cub scout pack's end-of-year surveys. There are two sets of questions: those where they want the responses to be completely anonymous and those questions where we need to know who filled out the response (people volunteering for positions, etc) I'm storing the responses in the db as two separate arrays, $anon and $nonAnon $anon[0] will be an array containing all the questions: $anon[0][0] = Survey question # 1 $anon[0][1] = Survey question #2, etc. The responses will be stored as arrays and placed in $anon as the 2nd element: $anon[1][0][0] = first response, answer to the first question $anon[1][0][1] = first resopnse, answer to the 2nd question $anon[1][1][0] = 2nd response, answer to the 1st question Etc. The pack leadership is concerned that no one would be able to reconstruct which anon response belonged to whom by matching up the order of the anon answers with the non-anon answers. Therefore I'd like to shuffle at least the anon responses. The long answer would be to build a temp array using the elements in $anon[1] and then shuffle that array and then reassign it to $anon[1]. Is there a way to use shuffle directly on $anon[1] without having to build a temporary array, shuffling it, then replacing the elements of $anon[1]? What I am trying to do is to submit as POST values to database_write.php, from within the while statement. What is happening is I am getting the second row of data every time I change the primary button.
Currently database_write.php is just doing print_r($_POST), And my array is always the same, no matter which select box I choose from. How can I get the values to be associated with the row I am currently changing? Any help would be great, thanks.
What I have so far:
<table class="table table-bordered table-hover"> <thead> <th>Room Number</th> <th>Primary Caregiver</th> <th>Seconday Caregiver</th> </thead> <tbody class="list"> <?php $sql = 'SELECT alarm_device_id, alarm_description, alarm_device_type, notes FROM alarm_device where notes in (\'MSU\') ORDER BY alarm_description'; $retval = mysql_query( $sql, $con ); if(! $retval ) { die('Could not get data: ' . mysql_error()); } $x=0; while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) { $id = $row['alarm_device_id']; $alarm_description = $row['alarm_description']; echo '<form id="msu_form">'; echo "<tr><td>{$row['alarm_description']}</td>"; echo "<td>"; $query2 = "SELECT alert_device_id,alert_description FROM alert_device WHERE notes = 'MSU'"; $result2 = mysql_query($query2) or die("Error in alarm_device select:" . mysql_error()); $count2 = mysql_num_rows($result2); if($count2 > 0) { //echo '<select name='.$x.'>'; echo '<select id="Primary" name="primary" onchange="doAjaxPost(this)">'; while($row2 = mysql_fetch_array($result2)) { echo "<option value=".$row2['alert_device_id'].">".$row2['alert_description']."</option>"; } echo "</select>"; }else { echo "Please update alert device to this area"; } echo "</td>"; echo "<td>"; $query3 = "SELECT alert_device_id,alert_description FROM alert_device WHERE notes = 'MSU2'"; $result3 = mysql_query($query3) or die("Error in alarm_device select:" . mysql_error()); $count3 = mysql_num_rows($result3); if($count3 > 0) { echo '<select id="Secondary" name="secondary">'; while($row3 = mysql_fetch_array($result3)) { echo "<option value=".$row3['alert_device_id'].">".$row3['alert_description']."</option>"; } echo "</select>"; }else { echo "Please update alert device to this area"; } echo "</td>"; $aid = $id + $x; //echo $aid; //$ad = $alarm_description + $x; echo '<input type="hidden" id="ID" name="ID" value="'.$id.'"/>'; //echo '<input type="hidden" id="desc" name="desc" value="'.$ad.'"/>'; //echo '<td>'."<input type='submit' name='btnupdate' value='UPDATE' /></td>"; //echo '<td><input type="button" value="Ajax Request" onClick="doAjaxPost()"></td>'; echo '</form>'; $x = $x+1; } ?> <script> function doAjaxPost() { // get the form values var primary = $('#Primary').val(); var secondary = $('#Secondary').val(); var hidden = $('#ID').val(); //var desc = $(sel).parent().nextAll('#desc').val(); $.ajax({ type: "POST", url: "functions/database_write.php", data: $('#msu_form').serialize(), //data: "Primary="+primary+"&Hidden="+hidden+"&Secondary="+secondary, success: function(resp){ //we have the response alert("'" + resp + "'"); }, error: function(e){ alert('Error: ' + e); } }); } </script> </tr> </tbody> </table> |