PHP - Retrieving Javascript Array In Php
As part of a form submission, I have several textboxes The textboxes have an array name such as text[]. I'm sending the textbox values via http request. Sending an element value via http request is usually be done using document.getElementById, assigning the elements ID to a var and posting the var name . Then accessing the value using $_POST. However I'm sending an array of string values. How do I access the array using $_POST? Any help appreciated.
Similar TutorialsHello all, I'm currently working on a project and it is the first time I have had to store/retrieve an array with PHP and MySQL. Basically its a website that has a list of discounts/coupons on it. People can register and submit their discounts and such. I am storing an array for who is eligible for the discount, as well as which categories the discount falls under. I did some googling and there seems to be tons of thoughts on the best way to do this. Some say to use implode/explode, some say to serialize/unserialize, I was just wondering if there is a common, concrete way to do this? I will need to be able to search the array for its contents. So if children are eligible for the discount, I need to be able to store that in a database, retrieve it later, and search it for only "Children" so I can display the discounts available only to children. If someone could please advise the best way to do this and post some examples, it would be greatly appreciated. I learn best with examples that are explained properly. I use Popshops Datafeed API and cant figure out an issue im having with an array. I'm trying to retrieve a category name from an array for the current page. Here is the array code which is in the index.php file. $categories = array(); $categories[] = array( 'name' => 'page name', 'search_options' => array( 'keywords' => 'page keyword' ) ); $categories[] = array( 'name' => 'page name', 'search_options' => array( 'keywords' => 'page keyword' ) ); $categories[] = array( 'name' => 'page name', 'search_options' => array( 'keywords' => 'page keyword' ) ); This is how the script calls the current page keyword. <?php echo ucwords($_REQUEST[$popshops->nameSpace.'keywords']) ?> The code above works fine, so I thought all I had to do was change the 'keywords' to 'name' to get what I was looking for. But that does not seem to work? <?php echo ucwords($_REQUEST[$popshops->nameSpace.'name']) ?> I've tried as much as my limited php knowledge can take me, so now I need some advice. Here is the function in the popshops.php file they use to pull the page name out for the links in the navigation, but I just want to know how to retrieve just the category name for the current page, nothing else. function customCategoryLink($category) { $url = $this->baseURL($this->params); if (isset($category['search_options']) && sizeOf($category['search_options']) > 0) { foreach($category['search_options'] as $key => $value) { $url = $this->addParameter($url,$key,$value); } } else { $url = $this->addParameter($url,'keywords',$category['name']); } $url = str_replace('?&','?',$url); return '<a href="'.$url.'">'.$category['name'].'</a>'; } Thanks in advanced! Hi All, small question here. I was just playing around with a small script I made to obtain an ip-address, remove the dots and than glue the parts together. Not for any use but for practice. But I am having difficulties to accessing the array values. But maybe that because its the first time i am using explode() and print_r. If someone has a spare minute I would be pleased to be enlightened. <?php $ip=$_SERVER['REMOTE_ADDR']; echo $ip.'<br />'; $cleaned_ip = substr($ip,0,6); echo $cleaned_ip.'<br />'; $cleaned_ip2 = print_r(explode('.', $ip, 6)).'<br />'; // this is the point where I dont know how to get the array values. // echo $cleaned_ip2[0].[1].[2]; that doesnt work. ;( ?> Code: [Select] $a = $landSellCheck[0]; echo("<p>a: $a"); $a = $landSellCheck[1]; echo("<p>a: $a"); $a = $landSellCheck[2]; echo("<p>a: $a"); $i = 0; $landSellCheck = $landSellCheck[$i]; echo("<p>b: (0): $landSellCheck"); $i = 1; $landSellCheck = $landSellCheck[$i]; echo("<p>b: (1): $landSellCheck"); $i = 2; $landSellCheck = $landSellCheck[$i]; echo("<p>b: (2): $landSellCheck"); As can be seen from the output below when I echo my array by manually inserting the index number, it works fine as it should. If I set the index number as a variable and echo it, it works for index value 0, for index value 1 is gives 'a' somehow (no idea where that comes from) and for index value 2 it is empty. What am I doing wrong? Output is: a: landSellConfirm7 a: landSellConfirm6 a: landSellConfirm1 b: (0): landSellConfirm7 b: (1): a b: (2): Hi, just a very simple question: I have an array as follows: $langList = array('English', 'French', 'German', 'Dutch'); What's the easiest way to store this array in an external file, so that multiple php scripts can access its contents? And what is then the php line I need to retrieve the array from the external file? Thanks! PLEASE HELP! I need help I am a new php user, and am trying to understand how to read a .txt file into an array then to retrieve the index of the array at will. Code: [Select] <?php //echo $myfile = fopen("ArrayTestFile.txt", "r") . "File exists: " or die("File does not exist or you lack permission to open it! "); //echo "The contents of the file is " . file_get_contents("ArrayTestFile.txt") . "<br />"; $fh = fopen("ArrayTestFile.txt", 'r+') or die("Failure"); $array = array(); //creation of array $num = fgets($fh);// recursive call variable $num fgets(.txt line) for ($i = 0; $i <= 5; $i++) //for loop loads first 5 of .txt { $array["i"] = $num; //loads each line of .txt into the array at the loops index. echo "Line " . $i . " of the array is " . $array["i"]; // displays the contents of the array in a print message } ?> Thank you. MOD EDIT: code tags added. Hi, I'm having problems retrieving the values from a form posting without getting a warning My form records playername, hours played and minutes played Code: [Select] <li id="input1" style="margin-bottom:4px;" class="clonedInput"> Name: <select name="player[1][userid]" id="player[1][userid]" class="playerInput" style="width: 7em;" > <option value=""></option> <?php while($row = mysql_fetch_array($sql)) { echo '<option value="'.stripslashes($row['userid']).'">'.stripslashes($row['name']).'</option>'; } mysql_data_seek($sql,0); ?> </select> <select name="player[1][hours]" id="player[1][hours]"> <option value="">Hours</option> <option value=""></option> <?php for($x = 0; $x <= 23; $x++ ) { echo '<option value="'.$x.'">'.$x.'</option>'; } ?> </select> <select name="player[1][minutes]" id="player[1][minutes]"> <option value="">Minutes</option> <option value=""></option> <?php for($y = 15; $y <= 59; $y+=15) { echo '<option value="'.$y.'">'.$y.'</option>'; } ?> </select> </li> I use some javascript to create new players as necessary so every player has a userid, hours, minutes played... After posting the query string looks like this /cLeagueHandler.php?player[1][userid]=1&player[1][hours]=3&player[1][minutes]=15&player[2][userid]=3&player[2][hours]=6&player[2][minutes]=45&submit=Save+Points player1 userid = 1 hours = 3 minutes = 15 player2....... The code i'm using to access the values is Code: [Select] print_r ($_GET); // test display form values foreach ($_GET as $key => $value) { echo '<br/>'.$key.'<br/> '; foreach ($value as $iKey => $iValue) { // Line 72 foreach ($iValue as $xKey => $xValue) { echo " The $xKey for Player $iValue is $xValue <br/>"; } } } The above code displays Array ( [player] => Array ( [1] => Array ( [userid] => 1 [hours] => 3 [minutes] => 15 ) [2] => Array ( [userid] => 3 [hours] => 6 [minutes] => 45 ) ) [submit] => Save Points ) player The userid for Player Array is 1 The hours for Player Array is 3 The minutes for Player Array is 15 The userid for Player Array is 3 The hours for Player Array is 6 The minutes for Player Array is 45 submit Warning: Invalid argument supplied for foreach() in .................cLeagueHandler.php on line 72 Line 72 is foreach ($value as $iKey => $iValue) { If anyone could help me with this it would be great appreciated.......I want to be able to build and sql string to Insert a players id, hours, minutes into a database......(obviously not incl the submit value!) Maybe this is not even the best way of approaching this.....I'm quiet new to PHP so apologies if this is long winded...I'm trying to give as much info as possible.... thanks in advance tmfl I need a help in the following : I have an admin page from where the admin attaches an gif image.This attached image should be shown to the user as a scrolling image. The code for the scrolling image is done through javascript. So my actual problem is getting the name of the attached gif image to the javascript array which is used for scrolling horizontally. $qID = ''; $question = 'Question not set'; $answerA = 'unchecked'; $answerB = 'unchecked'; $answerC = 'unchecked'; $answerD = 'unchecked'; $answerE = 'unchecked'; ?> <html> <head> <script type="text/javascript"> function show_alert() { alert("Please Click OK to proceed!"); } </script> </head> <form action="Process1.php" method="POST"> <table> <tr> <td> <?php $SQL = "SELECT stu_satisfaction_tblquestions.question_id, stu_satisfaction_tblquestions.question, answer_type.answer1, answer_type.answer2, answer_type.answer3, answer_type.answer4, answer_type.answer5 FROM stu_satisfaction_tblquestions INNER JOIN answer_type ON stu_satisfaction_tblquestions.answers_id=answer_type.answers_id "; $result = mysql_query($SQL); while($db_field = mysql_fetch_assoc($result)){ $qID = $db_field['question_id']; $question = $db_field['question']; $A = $db_field['answer1']; $B = $db_field['answer2']; $C = $db_field['answer3']; $D = $db_field['answer4']; $E = $db_field['answer5']; print $question; ?> </td> </tr> <tr> <td> <INPUT TYPE = 'Radio' Name ='q' value= 'A' <?PHP echo $answerA; ?>><?PHP echo $A; ?> <INPUT TYPE = "Hidden" Name = "h" VALUE = <?PHP print $qID; ?>> <?php echo $qID;?> </td> </tr> <tr> <td> <INPUT TYPE = 'Radio' Name ='q' value= 'B' <?PHP echo $answerB; ?>><?PHP echo $B; ?> <?php echo $qID;?> </tr> </td> <tr> <td> <INPUT TYPE = 'Radio' Name ='q' value= 'C' <?PHP echo $answerC; ?>><?PHP echo $C; ?> </tr> </td> <tr> <td> <INPUT TYPE = 'Radio' Name ='q' value= 'D' <?PHP echo $answerD; ?>><?PHP echo $D; ?> </tr> </td> <tr> <td> <INPUT TYPE = 'Radio' Name ='q' value= 'E' <?PHP echo $answerE; ?>><?PHP echo $E; ?> <br> <?php } mysql_close(); ?> </tr> </td> <tr> <td> Please add any comments you may have:</br> <textarea rows="3" cols="60" name="comments" id="comments"> </textarea> </td> </tr> </table> <input type="submit" onclick="show_alert()" value="Submit" /> </form> </html> I ran to some problems here. After filling every question up with the answers. When i process the form, i only managed to get QID of 20 and the answer of 1st question as my database have only 20questions. How do i go about in solving, so that i'm able to retrieve all result and update my database correctly $selected_radio = $_POST['q']; $qID = $_POST['h']; echo $selected_radio; echo $qID; $SQL = "UPDATE answers SET $selected_radio = $selected_radio + 1 WHERE question_id='$qID'"; $result = mysql_query($SQL); mysql_close(); print "Thanks for voting!"; ?> THis is my process page, and i echo out the answer to be B and qid as 20. In my script, users login with their Username & Password. However, I'd like to be able to echo the email address used on their account.
I've tried adding the email to the session I'm not having much luck... Here's a piece of the login code(untouched); $username = $_POST['name']; $passwd = $_POST['passwd']; $query = "SELECT name,passwd FROM users WHERE CONCAT('0x', hex(passwd)) = '{$salt}'"; $result = mysql_query($query); $login_ok = false; if(mysql_num_rows($result) > 0) { $login_ok = true; } if($login_ok) { $row = mysql_fetch_array($result, MYSQL_NUM); $_SESSION['user'] = $row;I've also tried messing around with this piece below in a few different ways but still nothing. <?php echo htmlentities($_SESSION['user']['email'], ENT_QUOTES, 'UTF-8'); ?>Any help is greatly appreciated.. Hi, so i have a problem. I'm using a script to enable and disable checkboxes, and i'm id-ing them fetching values from a database: while($data = mysqli_fetch_array($sql)) { if ($count % 5 == 0) { echo '</tr><tr>'; $count = 0; } echo '<td><input name="subject_level[]" class="subject_a" disabled="disabled" type="checkbox" id="subject_level_'.$data['subject_level_id'].'" value="'.$data['subject_level_id'].'"/>'; echo '<label for="subject_level_'.$data['subject_level_id'].'" class="subject_1">'.$data['subject_name'].'</label></td>'; $count++; //Increment the count } The names of the checkboxes come out fine, just that, is there any way to retrieve the values of the checkboxes into an array of some sort so that i could build a search query later? if($_POST(subject_level)) or if($_POST(subject_level[])) doesn't return true. does it make sense? im new to php so please forgive my ignorance. Help appreciated. Thanks! Hi, I need to get data from an XML file, like the format below: Code: [Select] <ISBNdb server_time="2011-05-31T19:19:42Z"> <BookList total_results="1" page_size="10" page_number="1" shown_results="1"> <BookData book_id="build_your_own_database_driven_web_site_using_php_mysql_4th_" isbn="0980576814" isbn13="9780980576818"> <Title> Build Your Own Database Driven Web Site Using PHP & MySQL, 4th Edition </Title> <TitleLong/> <AuthorsText>Kevin Yank, </AuthorsText> <PublisherText publisher_id="sitepoint">SitePoint</PublisherText> <Details change_time="2009-04-02T00:30:10Z" price_time="2011-05-31T17:46:10Z" edition_info="Paperback; 2009-06-15" language="" physical_description_text="360 pages" lcc_number="" dewey_decimal_normalized="5" dewey_decimal="005"/> </BookData> </BookList> </ISBNdb> I need to know how you get the details from <title>,<AuthorsText><PublisherText> and Bookdata. Tried using the example on W3C, using simplexml_load_file but it only returns: Code: [Select] ISBNdb BookList: Code I'm currently using is: Code: [Select] $xml = simplexml_load_file("http://isbndb.com/api/books.xml?access_key=----&results=details&index1=isbn&value1=".$isbn); echo $xml->getName() . "<br />"; foreach($xml->children() as $child) { echo $child->getName() . ": " . $child . "<br />"; } ok im back quicker than i thought.... i got my drop box sorted and i got it reloading the page. so it all works correctly. but how do i get the page to display information regarding the film i have selected in the drop box.? i have no code for this at the mo. also i would like the drop box to display the selected item at top of box when it refreshes code for drop box: Code: [Select] <FORM> <?php $result = mysql_query( "SELECT * FROM movie_info ORDER BY title ASC ") ; echo "<select name= Film onChange='submit()' >film name</option>"; while ($nt=mysql_fetch_array($result)){ ?> <?php echo "<option value='$nt[id]'>$nt[title] </option>"; } ?> </select> </FORM> any help would be great There's many options available for downloading a URL - but I'm stuck. I've looked through all the ones I know, but none seem to pay attention to partial content. I'm trying to retrieve a URL that gives the following header: HTTP/1.1 206 Partial Content Content-Range: bytes 0-100000/631723 As you can see it dishes out the file in 100,000 byte chunks. Trouble is, when I use any method in PHP, ie file_get_contents, fopen, or even cURL, none of these continue on after retrieving the 100,000 bytes. End result, I have a 100,000 byte file. What I need is to get the PHP script to grab all the data, in the example above, all 631,723 bytes. How can I do this? i have this script called view.php Code: [Select] <?php include 'db.inc'; $file = clean($file, 4); if (empty($file)) exit; if (!($connection = @ mysql_pconnect($hostName, $username, $password))) showerror(); if (!mysql_select_db("Php_test", $connection)) showerror(); $query = "SELECT mime, data FROM file WHERE id = $file"; if (!($result = @ mysql_query ($query,$connection))) showerror(); $data = @ mysql_fetch_array($result); if (!empty($data["data"])) { // Output the MIME header header("Content-Type: {$data["mime"]}"); // Output the image echo $data["data"]; } ?>after i have db.inc Code: [Select] <?php // These are the DBMS credentials $hostName = "localhost"; $username = "root"; $password = "oxioxi"; // Show an error and stop the script function showerror() { if (mysql_error()) die("Error " . mysql_errno() . " : " . mysql_error()); else die("Could not connect to the DBMS"); } // Secure the user data by escaping characters // and shortening the input string function clean($input, $maxlength) { $input = substr($input, 0, $maxlength); $input = EscapeShellCmd($input); return ($input); } ?>and i have my page witch part of it is this Code: [Select] <?php include 'db.inc'; $query = "SELECT id, name, mime FROM file"; if (!($connection = @ mysql_pconnect($hostName, $username, $password))) showerror(); if (!mysql_select_db("php_test", $connection)) showerror(); if (!($result = @ mysql_query ($query, $connection))) showerror(); ?> <h1>Image database</h1> <?php if ($row = @ mysql_fetch_array($result)) { ?> <table> <col span="1" align="right"> <tr> <th>Short description</th> <th>File type</th> <th>Image</th> </tr> <?php do { ?> <tr> <td><?php echo "{$row["name"]}";?></td> <td><?php echo "{$row["mime"]}";?></td> <td><?php echo "<img src=\"view.php?file={$row["id"]}\">";?></td> </tr> <?php } while ($row = @ mysql_fetch_array($result)); ?> </table> <?php } // if mysql_fetch_array() else echo "<h3>There are no images to display</h3>\n"; ?>i have do it right but for some reason it doesnt displays the pictures the type and the name are displayed normally but not the picture!! instead of them there are small icons of not existing pictures.. please i want help i really need to do it i have had a difficult time trying to work this out.I need to do some pattern matching for certain urls and retrieve information from it. For example, $url=http://www.test.com/showpic.php?do=showpic&u=89165&a=34933 if $url contains the value showpic.php,then i need to retrieve the following { $u=value of u(i.e. 89165 in this case) $a=value of a(i.e. 34933 in this case) } else do nothin.. the format of the url will always be the same as above if it contains showpic.php I'm making a game I have finished but have spent days and still can't figure out this part or how it should be done: Gamer will type in keyword on the form box on my page then click submit the page will connect to yahoo search then save/put the address bar URL search result of the keywords into a variable onto my page but the gamer will never have his page directed to yahoo but continue staying on my page while this all happens. Any Help in the right direction or some code would be appreciated? I have a basic table where I am trying to retrieve records that are filtered by a form request. Here is the code I have... $ps = $pdo->prepare("SELECT * FROM `Products` Where `Vendor` LIKE concat('%',?,'%'); $ps->execute(array($_POST['Vendor']));; echo "post=" . $_POST['vendor']; ////Displays correct data from form request $count = $ps->rowCount(); echo "Count=" . $count; ////Count = 0 although I know for a fact that there is 1 record that should be in there ////Used for display of records foreach ($ps as $row){ echo $row, PHP_EOL . "xxx<br>"; } Where is the incorrect code? I am new to php and pdo. Thank you in advance K Hi there I am trying to use cURL to retrieve XML from a gateway. The code I am using works (ie. returns the HTTP response) for any URL that I use except the one that I need! The URL is below, and when using that I get a blank response every time. I've tested and can telnet to that IP address on that port from my server. I'm not sure if it is because of the format/structure of the URL? Could it have something to do with the port of the gateway? Any assistance would be much appreciated. http://196.11.120.190:8080/mtnusa/client.jsp?command=<usareq NODE="tHTTP" USERNAME="HTTP" PASSWORD="1234" TRANSFORM="SMPP"><command><submit_sm><a_number>278200703520709</a_number><b_number>27824411926</b_number><service_type/><message>Test</message><registered_delivery/></submit_sm></command></usareq> The function I am using (from http://davidwalsh.name) is: /* gets the data from a URL */ function get_data($url) { $ch = curl_init(); $timeout = 5; curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout); $data = curl_exec($ch); curl_close($ch); return $data; } $returned_content = get_data('http://196.11.120.190:8080/mtnusa/client.jsp?command=<usareq NODE="HTTP" USERNAME="HTTP" PASSWORD="1234" TRANSFORM="SMPP"><command><submit_sm><a_number>278200703520709</a_number><b_number>27824411926</b_number><service_type/><message>Test</message><registered_delivery/></submit_sm></command></usareq>'); i am trying to retrieve messages with some code. It seems to be a bit more complicated that i thought it would be. so here it goes: Code: [Select] $query = "SELECT * FROM memberMail WHERE userIDFrom='92' AND unread='1'"; $result = mysql_query($query) or die(mysql_error()); if (mysql_num_rows($result) > 0) { $row = mysql_fetch_array($result) or die(mysql_error()); $num_rows = mysql_num_rows($result); echo "You have (" . $num_rows . ") unread message(s)."; $i = 0; for($i; $i<$num_rows; ++$i) { if($row[$i[unread]] == "1") { echo $row[$i[message]] . "<p>"; } } } what i am trying to do, is print out the messages from the records that are unread, and are from a certain user. i don't think this for statement will pick up the record numbers that got matches though. and i am not entirely sure about the $row statements in the for statement either. |