PHP - Array_filter And Count Not Acting As Expected
I have a form on a page that has checkboxes for a number of entities, including one that is new. I want to determine how many checkboxes were checked for the new entity. The html is:
<div id="new" style="display:block;">Which method(s) of valuation would you like to use for this report?<br /> <input type="checkbox" name="method_code['new'][]" value="EE">Excess Earnings<br /> <input type="checkbox" name="method_code['new'][]" value="DCF">Discounted Cash Flow</div> <div id="75" style="display:none;">Which method(s) of valuation would you like to use for this report?<br /><input type="checkbox" name="method_code['75'][]" value="EE" checked="checked" >Excess Earnings<br /> <input type="checkbox" name="method_code['75'][]" value="DCF" checked="checked" >Discounted Cash Flow</div><div id="79" style="display:none;">Which method(s) of valuation would you like to use for this report?<br /> <input type="checkbox" name="method_code['79'][]" value="EE">Excess Earnings<br /><input type="checkbox" name="method_code['79'][]" value="DCF">Discounted Cash Flow</div> <div id="77" style="display:none;">Which method(s) of valuation would you like to use for this report?<br /> <input type="checkbox" name="method_code['77'][]" value="EE">Excess Earnings<br /> <input type="checkbox" name="method_code['77'][]" value="DCF">Discounted Cash Flow</div>I looked for a method of counting the nuber of checked boxes for a given entity and found So, to count only non-empty: count(array_filter($array));here and here So I implemented that in my code and it doesn't work. I put in the following to debug: echo '<pre>'; print_r($_POST['method_code']); echo '</pre>'; echo "arraycount ".count(array_filter($_POST['method_code']['new']));die();and I get the following output: Array ( ['new'] => Array ( [0] => EE ) ['75'] => Array ( [0] => EE [1] => DCF ) ['78'] => Array ( [0] => EE ) ) arraycount 0Why is the count 0? I expect that count(array_filter($_POST['method_code']['new'])) would be one since there is one element in that array. Similar TutorialsHi - I have looked at a dozen examples and I think my syntax is correct, yet for some reason, I must be doing it wrong as it won't work. My filter_array() produces the exact same output as a print_r() which makes me think that there is something is wrong with the function, but I can't see what it could be. I'm using PHP 5.3.8 Many Many Thanks for your help ! The Array Contents from a print_r() Code: [Select] Array ( [0] => Array ( [pickupid] => 5 [pickuplocation] => Banff [date1] => 1329980400 [date2] => 1333260000 [date3] => 1334469600 [date4] => 1335852000 ) ) The Array_Filter() Code: [Select] function greaterThanNow ($i){ $now = time(); if ($i > $now) { return true; } } $filtereddates = (array_filter( $deliverydates,"greaterThanNow")); print_r($filtereddates); Hi guys, I need your help. I am trying to insert the rows in the mysql database as I input the values in the url bar which it would be like this: Code: [Select] www.mysite.com/testupdate.php?user=tester&pass=test&user1=tester&email=me@shitmail.com&ip=myisp However i have got a error which i don't know how to fix it. Error: Column count doesn't match value count at row 1 <?php session_start(); define('DB_HOST', 'localhost'); define('DB_USER', 'mydbusername'); define('DB_PASSWORD', 'mydbpassword'); define('DB_DATABASE', 'mydbname'); $errmsg_arr = array(); $errflag = false; $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } $db = mysql_select_db(DB_DATABASE); if(!$db) { die("Unable to select database"); } function clean($var){ return mysql_real_escape_string(strip_tags($var)); } $username = clean($_GET['user']); $password = clean($_GET['pass']); $adduser = clean($_GET['user1']); $email = clean($_GET['email']); $IP = clean($_GET['ip']); if($username == '') { $errmsg_arr[] = 'username is missing'; $errflag = true; } if($password == '') { $errmsg_arr[] = 'PASSWORD is missing'; $errflag = true; } if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; echo implode('<br />',$errmsg_arr); } else { $sql = "INSERT INTO `members` (`username`,`email`,`IP`) VALUES ('$adduser','$email','$IP')"; if (!mysql_query($sql,$link)) { die('Error: ' . mysql_error()); } echo "The information have been updated."; } ?> Here's the name of the columns i have got in my database: Code: [Select] username IP I have input the correct columns names, so I can't correct the problem I am getting. Please can you help? This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=331562.0 Why am I getting this error when there are 3 Fields with 3 values? Column count doesn't match value count at row 1 Code: [Select] $sql5="INSERT INTO participants (participant_name, team_no, sport) VALUES ('".implode("','$_POST[team]'),('",$_POST['participant_name'])."','$_POST[team]','$sport')"; Anyone can help me? <?php $tbl_name="menu"; $kategorije = mysql_query("SELECT * FROM $tbl_name WHERE Left(menu_name, 1) BETWEEN 'A' AND 'M' ORDER BY menu_name ASC"); if (!$kategorije) { die("Database query failed: " . mysql_error()); } while ($row=mysql_fetch_array( $kategorije )) { echo "<div id=lista-header><h4>{$row["menu_name"]}</h4></div>"; $id_sub=$row['id_menu']; $podkategorije = mysql_query("SELECT * FROM submenu WHERE id_menu=$id_sub ORDER BY sub_name ASC", $connection); if (!$podkategorije) { die("Database query failed: " . mysql_error()); } echo "<ul class=\"pod\">"; while ($pod=mysql_fetch_array( $podkategorije )) { echo "<li><a href=index.php?=podkate?".$pod["id_sub"]." class=black>{$pod["sub_name"]}</a><hr size=1 align=left width=100px color=#cccccc></li>"; } echo "</ul>"; } ?> In this way, I get list with categories and hes subcategories. How to count how many subcategories have each categories, and count how many articles have each categories? Example (I wanna get this kind of look): Categories name (3) subcategoriesname (2) subcategoriesname (4) subcategoriesname (7) Categories name (5) subcategoriesname (1) subcategoriesname (14) subcategoriesname (9) subcategoriesname (2) subcategoriesname ( Categories name (2) subcategoriesname (28) subcategoriesname (17) Where the numbers represent how many categories and sub-items have articles Here is the code in question: <form method="post" action="../php/sendmail.php"> <?php function RandomLine() { $textfile = "../messages/compliments.txt"; if(file_exists($textfile)) { $compliments = file($textfile); $string = $compliments[array_rand($compliments)]; } else { $string = "Error"; } return $string; } $line = RandomLine(); echo "<p style='color: red;'>"."$line"."</p>"; ?> <br> <input type="hidden" name="email" value="email@email.com"> <input type="hidden" name="subject" value="random compliment generator"> <input type="hidden" name="message" value="$line"> <input type="hidden" name="to" value="5555555555@mms.uscc.net"> <input type="submit" name="sendtext" value="Send to phone!"> </form> And here is the php from sendmail.php: <?php $email = $_REQUEST['email']; $subject = $_REQUEST['subject']; $message = $_REQUEST['message']; $to = $_REQUEST['to']; $sent=mail($to, $subject, $message, "From: $email"); if($sent)echo "<br><p>The message was sent!</p>"; else echo "<br><p>There was an error while sending the message.</p>"; ?> When the form from the first bit of code is opened in an iframe, the echo displays the correct code but if the button is sent, the sms/email received simply says "$line". Any ideas? Everytime I make an announcement/post with a link like so: "This is an announcement with the following link: <a href="http://www.blah.asp">link</a>" It never goes to the actual webpage. It always goes to a "not found" page on my website like so: http://mywebsite.com/"http://www.blah.asp/" This error is very bizarre since I can't seem to debug it. When I require my header, it is included. When I require my footer, it is not. I am 100% the paths are correct, and I tried another file to make sure it wasn't the footer causing the error. Here's the code for the header, footer, and index. If you need to see anything else just tell me. header Code: [Select] <?php ob_start(); ?> <?php ini_set('session.cookie_domain', '.domain'); ?> <?php ini_set('display_errors','On'); ?> <?php session_start(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <head> <link rel='stylesheet' href='includes/css/reset.css' type="textcss"/> <link rel="stylesheet" href="includes/css/style.css" type="text/css"/> <title>Domain</title> </head> <?php require('classes/common.inc.php'); $common = new common(); if($common->_truesession()) { $hsuser = $_SESSION['username']; } $common->_cookiecheck(); $db = $common->_db(); echo "<ul>"; echo "<li><a href=domain.com>Domain</a><ul>"; $query = $db->_query("select * from links where id > 1"); while($row = $db->_assoc($query)) { $name = $row['name']; $link = $row['url']; echo "<li><a href=".$db->_out($link).">".$db->_out($name)."</a></li>"; } echo "</ul></li></ul>"; ?> index Code: [Select] <?php require('includes/header.php'); ?> <?php ?> <?php require('includes/footer.php'); ?> footer Code: [Select] <?php echo "<ul>"; echo "<li><a href=about.php>About</a></li>"; if(!$common->_truesession()) { echo "<li><a href=register.php>Register</a></li>"; } echo "</ul>"; $year = date('Y'); echo "© $year <a href='http://domain.com'>Domain</a>"; ob_end_flush(); ?> I have a table called "newsletters": Quote +----------------+------+--------+ | email | mens | womens | +----------------+------+--------+ | test1@test.com | 0 | 1 | | test2@test.com | 1 | 1 | +----------------+------+--------+ What I want to do is make it so after PHP unregisters a user, it checks the database to see if they are signed up to any other newsletters, and if they arn't, then to delete the key (email) from the table: Unregistering an e-mail address from the mens newsletter would go something along the lines of this: Code: [Select] $query = "INSERT INTO newsletters(email, mens) VALUES('$email', 0) ON DUPLICATE KEY UPDATE mens = 0"; if (MySQL table newsletters(email == $email + womens == 0) { $query = "delete from testdb.newsletters where email='$email'"; } This is the line where I need PHP to check, the rest of the code is fine. This line is made up - to give an idea of what I'm trying to do. Code: [Select] if (MySQL table newsletters(email == $email + womens == 0) { I run PHP5 on a Linux (Ubuntu) box. The setup has been working for years without a problem, sending E-mails to my local address via web pages and PHP. Today, I'm trying to write a simply page to send me an E-mail. No E-mail, no error, no nothing. However, it WILL send the E-mail if the text is something else. After HUNDREDS of E-mails to myself to test this, I have come up with the following: This works: Code: [Select] <?php $mailtext = "e'a'to"; mail('myaddress@mydomain.com',' My subject', $mailtext); ?> BUT....If I take out any character from $mailtext, or substitute any other letter, the mail will not be sent. Just to be silly, I tested this, and it works: Code: [Select] <?php $mailtext = "This is a sample E-mail"; mail('myaddress@mydomain.com', 'My Subject', $mailtext); But this doesn't work: Code: [Select] <?php $mailtext = "This is a sample Email"; mail('myaddress@mydomain.com', 'My Subject', $mailtext); ?> Very weird combinations of characters in $mailtext will get sent just fine, but change it at all, and the mail won't get sent. Any ideas? Hello everyone, I'm working on an account update page where users can update their email address, password, or security question/answer as desired. The way I currently have it set up is so that only the information that the user enters will be updated in the database. So if they only enter a new email address, the email field in the database is updated and all other fields are left as is. I'm also trying to set a javascript even handler (onUnload) depending on whether or not anything was updated. When their info is successfully updated, I want to alert the user accordingly, as well as when no information was updated. To do this, I have a variable "$updated" that is set at "false" by default and is supposed to be set to "true" when something is updated and "none" when nothing is updated. The form and mysql commands are working and the correct fields are being updated as expected. The problem that I'm having is the $updated variable is not being set correctly and is ALWAYS being set to "true", even when it is expect to be set to "none." Here's the code that I have: Code: [Select] <?php function safe($value){ return mysql_real_escape_string($value); } $updated = "false"; if (isset($_POST['submit'])) { // If the form has been submitted. $newemail = $_POST['newemail']; $pword1 = $_POST['pword']; $question = safe($_POST['question']); $answer = safe($_POST['answer']); $updated = $_POST['updated']; $pword = md5($pword1); $q = mysql_query("SELECT * FROM `signin` WHERE email = '$newemail'") or die (mysql_error()); $r = mysql_num_rows($q); // Checks to see if anything is in the db. if ($r == 1 && $email == $newemail) { $noemail = "true"; } elseif ($r == 0) { $noemail = "true"; } else { $noemail = "false"; } if ($newemail != "" && $pword1 == "" && $question == "0") { if ($noemail == "true") { mysql_query("UPDATE `signin` SET `email` = '$newemail' WHERE email = '$email'") or die (mysql_error()); $_SESSION['email'] = $newemail; $updated = "true"; } } elseif ($newemail == "" && $pword1 != "" && $question == "0") { mysql_query("UPDATE `signin` SET `pword` = '$pword' WHERE email = '$email'") or die (mysql_error()); $updated = "true"; } elseif ($newemail == "" && $pword1 == "" && $question != "0") { mysql_query("UPDATE `signin` SET `question` = '$question',`answer` = '$answer' WHERE email = '$email'") or die (mysql_error()); $updated = "true"; } elseif ($newemail != "" && $pword1 != "" && $question == "0") { if ($noemail == "true") { mysql_query("UPDATE `signin` SET `email` = '$newemail',`pword` = '$pword' WHERE email = '$email'") or die (mysql_error()); $_SESSION['email'] = $newemail; $updated = "true"; } } elseif ($newemail != "" && $pword1 == "" && $question != "0") { if ($noemail == "true") { mysql_query("UPDATE `signin` SET `email` = '$newemail',`question` = '$question',`answer` = '$answer' WHERE email = '$email'") or die (mysql_error()); $_SESSION['email'] = $newemail; $updated = "true"; } } elseif ($newemail == "" && $pword1 != "" && $question != "0") { mysql_query("UPDATE `signin` SET `pword` = '$pword',`question` = '$question',`answer` = '$answer' WHERE email = '$email'") or die (mysql_error()); $updated = "true"; } elseif ($newemail != "" && $pword1 != "" && $question != "0") { if ($noemail == "true") { mysql_query("UPDATE `signin` SET `email` = '$newemail',`pword` = '$pword',`question` = '$question',`answer` = '$answer' WHERE email = '$email'") or die (mysql_error()); $_SESSION['email'] = $newemail; $updated = "true"; } } else { $updated == "none"; } } ?> //This is where the event handler (onUnload) is set according to what has occurred in the code above <?php if (isset($_POST['submit']) && $updated = "true") { echo "<body onUnload=\"alert('Your information has been successfully updated.')\">"; } elseif (isset($_POST['submit']) && $updated = "false") { echo "<body onUnload=\"alert('There have been no updates made to your account information.')\">"; } else { echo "<body>"; } ?> Can anyone see a problem with this and why the $updated variable is not being set as expected. Any ideas on a better way to accomplish what I want to do? Thanks in advance for anyone's help! Hello I want to check that a variable the user enters is not empty and that it is a string (no numbers). Here is what i have written: Code: [Select] <?php include('css/layout.css.php'); include('css/menu.css'); if (isset($_POST['submit'])) { include('includes/dbconn.php'); if (is_string($_POST['name']) && strlen($_POST['name']) > 0) { $name = mysql_real_escape_string($_POST['name']); } else { echo "Category name must be a word!<br />"; } if (isset($name)) { echo $name; } else { echo "something"; } } ?> and this is the form i'm getting the data from: Code: [Select] <form action="category_add.php" method="post"> <table class="table-view"> <tr> <td><label for="name">Category Name</label></td> <td><input type="text" name="name" id="name"></td> </tr> <tr> <td><input type="submit" value="Save changes" name="submit" id="submit"></td> </tr> </table> </form> If i enter nothing it works fine, if i enter a string it also works fine, the problem is when i enter 123 in the textbox, i dont get the "Category name must be a word!" as i expected i would. Could someone help me with this one please? Thanks in advance. I wish to find a way to test if multiple sites are up or not. I have been using get_headers but it seems that this does not do what I thought I would. I wish to know if the sites are down or not. Is there another function that can test what state the site is in. i.e. server not found, server issues prevented the page from showing... Using get_headers will still show the site is live even if the server is not found, due to server problems, if any. I'm using PHP 5.2.14 under Windows XP. I'm trying to use ini_set to turn on the 'track_error' configuration option, and it's not working. I make this call, $xxx = ini_set('track_error',"1"); and it returns false. According to the documentation, track_error can be set from any source (including ini_set). What could prevent that from happening? Going back one step, I want to set track_errors so that I can fetch and process the error which occurs when mysql_connect fails. Since it fails, it returns no link, making it impossible to call mysql_errors. Whether ini_set can be made to work or not, is there another, perhaps better way to accomplish this? I am trying to load all rows from a table in a database into a table on a webpage. I cannot understand why the following code does not work: Code: [Select] <?php ... echo "You are currently in a fleet. The details of the fleet are below.<br>"; $fleetName = $_SESSION['charFleetName']; $sqlFleetDetails = "SELECT * FROM `$fleetName`"; $queryFleetDetails = mysql_query($sqlFleetDetails); echo "<table>"; echo "<tr>"; echo "<th>Pilot</th>"; echo "<th>Ship</th>"; echo "<th>Type</th>"; echo "</tr>"; while($rowFleetDetails = mysql_fetch_array($queryFleetDetails)) { $charId = $rowFleetDetails['charId']; $charName = $rowFleetDetails['charName']; $shipHull = $rowFleetDetails['shipHull']; $shipType = $rowFleetDetails['shipType']; echo "<tr>"; echo "<td><a href=\"#\" onClick=\"CCPEVE.showInfo{1377, " . $charId . "}>" . $charName . "</a></td>"; echo "<td>" . $shipHull . "</td>"; if($shipType == 1) echo "<td>Logistics</td>"; if($shipType == 2) echo "<td>DPS Boat</td>"; if($shipType == 3) echo "<td>Sniper 120Km+</td>"; if($shipType == 4) echo "<td>Off-grid Booster</td>"; echo "</tr>"; } echo "</table><br>"; I originally had the $rowFleetDetails['charId'] and others in the echo instead of loading them into variables then echoing the variables but changed it to see if that was working, neither is. If I add an extra line outside of the while loop to echo the output of the array then the information is displayed fine, so I know that the information is being transferred from the table into the array correctly, but why is it not outputting properly in the While loop? Hello.
I'm having some issues with a select statement containing ABS().
Here's the select query:
"SELECT gadenavn, husnr, ABS(husnr - $husnr) AS husnr_range, postnr,db, shaping, dsl_node, ctr_node, db_ctr_luftlinje, bynavn FROM `TABLE 1`, Post_numre WHERE `postnr`=`postnummer` AND `gadenavn`=`$vejnavn` AND `postnr`=`$postnr` AND `husnr`>0 ORDER BY husnr_range ASC LIMIT 5"Now lets asume my variable "$husnr" is a value of 15. In my table I have the values for coulmn "husnr": 13,12,11,10,9 What really bugs me is the outcome doing af simple "while loop" is returning the values 12,11,10,9. What happened to 13?! printing the "husnr_range" values shows "3,4,5,6". What puzzles is the row missing, as I only get 4 results, with a "LIMIT 5". Can anyone explain why the last resulst isn't included? I have an avatar upload script. The uploading and moving of the image file to the correct directory works fine, but the displaying of the image causes problems. This is the code that is supposed to display the avatar. // _DISPLAY_ avatar - START $query2 = "SELECT * FROM user WHERE user_id = '$dbuser_id'"; $row2 = mysqli_query ($dbc, $query2) or die (mysqli_error($dbc)); $assoc2 = mysqli_fetch_assoc ($row2); $target = AVATAR_UPLOADPATH; $avatar_name = $target . $assoc2['avatar']; if (is_file($assoc2['avatar'])) { echo "<img src='$avatar_name' alt='Avatar' /><br /><br />"; } else { echo "is not a regular file"; } // END The avatar column in the MySQL database says: image.jpg So there's a regular file. What I want to accomplish: I want the script to check if there's an avatar in the database, if NOT, then it should say: "no avatar uploaded yet." But as it is now it's telling me that there's no regular file even if there is, as I said the avatar column has an entry saying: image.jpg. Should I use if !empty instead? The strange thing is it used to work, now for some reason it suddenly doesn't. EDIT: With !empty it works, am I using the is_file function incorrectly? I have only one result being displayed in a select query result whereas I'm expecting 4 results in an array. This is my code below. $sq2="SELECT course FROM course_reg WHERE userid=?"; $stm =$conn->prepare($sq2); $stm->bind_param("s",$logged); $stm->execute (); $return2= $stm->get_result(); $r2 = $return2->fetch_all(); //print_r($r2); foreach($r2 as $course){ foreach($course as $courses){ echo $courses; } }
If I do print_r($r2); it comes out with array containing all the possible results. When i loop through the array to get individual result, it only comes out with a single result. I.e CME211 I would be glad if you can help me figure where the issue is. Thanks!!!
Hello, this is my first post in this forum, in fact my first post about php. I am developing a crud application, but when i am trying to list a set of results it gives me more that the expected Let me explain. if i print_r my array (which i get it from a sql result) it gives me this Array ( => SHR1 [codprod] => SHR1 [1] => REGULAR SERVICE HOUR [proddescription] => REGULAR SERVICE HOUR [2] => 3.00 [qty] => 3.00 [3] => HR Code: [Select] => HR [4] => 45.0000 [price] => 45.0000 [5] => 0.00 [discount] => 0.00 [6] => 135.00 [amount] => 135.00 ) [/li][/list] if I foreach($detailrow as $value){ echo $detailrow['codprod'] . ", " . $detailrow['proddescription'] . ", " . $detailrow['qty'] . ", " . $detailrow['code'] . ", " . $detailrow['price'] . ", " . $detailrow['discount'] . ", " . $detailrow['amount'] . "<br/>"; } It gives me 14 rows with the same info. I run the query in mysql and it gives me only 1 result as expected. I noticed that the 14 rows are the same quantity of items in the array not results but let say columns, i dont know if it has something to do with the results. My questions: Why it is giving me 14 rows instead just one? What is the $value in the foreach function? why can't i just say foreach($myarray)? why the print_r shows me the items array duplicated using the array position and the item name? Thank you for your help!! |