PHP - Array_push Inside While
Hey guys I have the following script that correctly retrieves 2 values from mysql: security_code and selected_address:
The problem I have, is how can I add the retrieved values (more than 1 row) inside an array called $data $data = array(); $result = mysql_query("SELECT security_code, selected_address FROM purchase WHERE purchase_id = '412012' AND selected_address = 'General Roca 900' ORDER BY `offers_bought`.`security_code` ASC"); $cant = 0; while($row=mysql_fetch_array($result)) { array_push($data[$row['selected_address']], $row['security_code']); $cant++; } The array_push function gives me the following error: Warning: array_push() [function.array-push]: First argument should be an array in C:\wamp\www\Test\test\excelTest.php on line 24 In other words this is want I want to achieve: $data = array(array("selected_address" => $row['security_code'])); Only that this example adds only 1 retrieved row Any ideas? Thanks in advance! Cheers, Similar TutorialsHello all. I'm pretty new to this, but I'm trying to build a script that will write random questions for a quiz app that I'm working on. The data is contained in two different tables. I'm trying to randomize the question order that is spit out, as well as randomize the answer order that is displayed. The output has to be in the specific JSON string that is denoted in the code. There are no errors when I go the url that I load the script, however, the string is not populated with any of the data from my tables (it is just an empty set of strings in the JSON format that the program requires. Could someone please take a look at this and tell me where I'm going wrong. I've checked that the query is pulling from the correct databases so I know that's not the problem. Thank you in advance. Code: [Select] <?php //Connect To Database $hostname=""; $username=""; $password=""; $dbname=""; $question_table="wp_mtouchquiz_question"; $answer_table="wp_mtouchquiz_answer"; $yourfield = "question"; $question = "question"; $answer = "answer"; $connection = mysql_connect($hostname, $username, $password); $lastQuestionID = -1; $str = ""; mysql_select_db($dbname, $connection); # Check If Record Exists $query = "SELECT * FROM $question_table q, $answer_table a WHERE q.ID = a.QUESTION_ID AND q.quiz_id = 1 ORDER BY question_id ASC, correct DESC"; $result = mysql_query($query); $questions = array(); $fields = array(); if($result) { while($row = mysql_fetch_array($result)) { if($lastQuestionID != $row["question_id"]) { $fields = array(); if($lastQuestionID != -1) { array_push($questions, $fields); } $fields = array(); $lastQuestionID = $row["question_id"]; $fields["question_id"] = $row["question_id"]; $fields["question"] = $row["question"]; } // correct if($row["correct"] == 1) { $fields["correct"] = $row["answer"]; } // incorrect if ($row["sort_order"] ==2) { $fields["incorrect0"] = $row["answer"]; } // incorrect if ($row["sort_order"] ==3) { $fields["incorrect1"] = $row["answer"]; } // incorrect if ($row["sort_order"] ==4) { $fields["incorrect2"] = $row["answer"]; } if ($row["sort_order"] ==5) { $fields["incorrect3"] = $row["answer"]; } } $str .= "{\"childItems\":["; $numQuestionsToUse = 172; //Set this larger than returned questions or less than row limit / 5 $randomQuestionKeys = array_rand($questions, $numQuestionsToUse); $numQuestions = count($randomQuestionKeys); for($i = 0; $i < $numQuestions ; $i++){ $pickedField = $questions[$randomQuestionKeys[$i]]; $str .= "{\"itemId\":\"question" . $pickedField["question_id"] . "\","; $str .= "\"itemType\":\"BT_questionItem\","; $str .= "\"questionText\":\"" . $pickedField["question"] . "\","; $str .= "\"correctAnswerText\":\"" . $pickedField["answer"] . "\","; $incorrectAnswers = array(); array_push($incorrectAnswers, $pickedField["incorrect0"]); array_push($incorrectAnswers, $pickedField["incorrect1"]); array_push($incorrectAnswers, $pickedField["incorrect2"]); array_push($incorrectAnswers, $pickedField["incorrect3"]); $incorrectAnsKey = array_rand($incorrectAnswers, 3); $str .= "\"incorrectText1\":\"" . $incorrectAnswers[$incorrectAnsKey[0]] . "\","; $str .= "\"incorrectText2\":\"" . $incorrectAnswers[$incorrectAnsKey[0]] . "\","; $str .= "\"incorrectText3\":\"" . $incorrectAnswers[$incorrectAnsKey[0]] . "\","; $str .= "\"imageURLSmallDevice\":\"http://www.myquizcoach.com/extras/images/clear_header.png\","; $str .= "\"imageURLLargeDevice\":\"http://www.myquizcoach.com/extras/images/clear_header.png\"},"; } // remove last comma $str = substr($str,'',-1); $str .= "] }"; echo $str; } ?> Our disc golf league uses a little PHP script that I developed (stealing lots of code in the process) that sucks in a list of league players from a text file, lets you select the ones that show up on league day, and randomly assigns the selections into foursomes and threesomes (Demo: http://edge.byethost18.com/demo4/foursomes.php)
Here's a modified example using letters of the alphabet:
. . . and the code: The actual version uses the shuffle() function to randomize the assignments and has a refresh button to reshuffle the assignments if a grouping contains bitter enemies. I disabled it in the example in order to show how the "A-B-C"s are assigned to the groups. As you can see, it assigns "A" to the first group, "B" to the second group, "C" to the third group and so on until it reaches the last group and then starts back at group 1 with the next letter. One of the our players wants a modification. He wants to be able to assign players into foursomes/threesomes according to their handicaps (best to worst). In other words, Group 1 would contain A, B, C, D. Group 2 would contain E, F, G, H and so on. Naturally, this would depend on which player checkboxes are selected, but the order is maintained. What I am having trouble with is getting the "A-B-C"s assigned into groups in the order they are listed in the text file. I tried using array_chunk() in the following script: https://neth.roe3.org/mdrone/ABCs/foursomes2.php
. . . and the code: In a nutshell, here's the code that's doing the work . . .
$numgroups = $d; $rows = array_chunk($players,$numgroups);
$x=0; I'm sure there's a simple solution. I'm just not seeing it. I'm really just a hobbyist . . . not a real programmer by any stretch of the imagination. Thanks for any help anyone can send my way. BTW . . . if anyone is interested in the foursomes generator source, I'm happy to share it. It could probably use improvement. I am trying to add new elements to an empty array using a form and submit button and the code is not adding anything from it. Here is the code I use:
<!DOCTYPE html> <html> <head> <title> </title> </head> <body> <div class="site"> <div class="menu"> </div> <div class="head"> </div> <div class="content"> <form> <input type="text" value="" name="add"/><br/> <input type="submit" value="Add" name="submit"/> </form> </div> <div class="footer"> </div> </div> </body> </html> <?php $submit = $_POST["submit"]; $field = $_POST["add"]; $list = array(); if($submit){ $psh = array_push($list,$field); echo $list; } ?>Any idea why is it not working? This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=316454.0 The Script:
$desired_width = 110; if (isset($_POST['submit'])) { $j = 0; //Variable for indexing uploaded image for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array $target_path = $_SERVER['DOCUMENT_ROOT'] . "/gallerysite/multiple_image_upload/uploads/"; //Declaring Path for uploaded images $validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.) $file_extension = end($ext); //store extensions in the variable $new_image_name = md5(uniqid()) . "." . $ext[count($ext) - 1]; $target_path = $target_path . $new_image_name;//set the target path with a new name of image $j = $j + 1;//increment the number of uploaded images according to the files in array if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded. && in_array($file_extension, $validextensions)) { if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>'; $tqs = "INSERT INTO images (`original_image_name`, `image_file`, `date_created`) VALUES ('" . $_FILES['file']['name'][$i] . "', '" . $new_image_name . "', now())"; $tqr = mysqli_query($dbc, $tqs); // Select the ID numbers of the last inserted images and store them inside an array. // Use the implode() function on the array to have a string of the ID numbers separated by commas. // Store the ID numbers in the "image_file_id" column of the "thread" table. $tqs = "SELECT `id` FROM `images` WHERE `image_file` IN ('$new_image_name')"; $tqr = mysqli_query($dbc, $tqs) or die(mysqli_error($dbc)); $fetch_array = array(); $row = mysqli_fetch_array($tqr); $fetch_array[] = $row['id']; /* * This prints e.g.: Array ( [0] => 542 ) Array ( [0] => 543 ) Array ( [0] => 544 ) */ print_r($fetch_array); // Goes over to create the thumbnail images. $src = $target_path; $dest = $_SERVER['DOCUMENT_ROOT'] . "/gallerysite/multiple_image_upload/thumbs/" . $new_image_name; make_thumb($src, $dest, $desired_width); } else {//if file was not moved. echo $j. ').<span id="error">please try again!.</span><br/><br/>'; } } else {//if file size and file type was incorrect. echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>'; } } }Hey, sorry that I am posting this darn image upload script again, I have this almost finished and I am not looking to ask more questions when it comes to this script specifically. With the script above I have that part where the script should store the ID numbers (the auto_increment column of the table) of the image files inside of one array and then the "implode()" function would get used on the array and then the ID numbers would get inserted into the "image_file_id" column of the "thread" table. As you can see at the above part the script prints the following: Array ( [0] => 542 ) Array ( [0] => 543 ) Array ( [0] => 544 )And I am looking to insert into the column of the table the following: 542, 543, 544I thought of re-writing the whole image upload script since this happens inside the for loop, though I thought maybe I could be having this done with the script as it is right now. Any suggestions on how to do this? I'm trying to pull results from a database (using php) to populate a javascript "top news rotation" script I found. The problem is that I'm getting the "java is disabled" message that is in the code...instead of the results I'm expecting. Here's the code: Code: [Select] <!-- create a element in your HTML like the following --> <div id="quotetext" > Text will go here. Be sure to add initial text here for users with JavaScript disabled. </div> <!-- The easiest way is to place the below JavaScript code after the above HTML. The better way would be to add in the <head> section of the document and call the rotatequote() function through the window.onload event. However this can cause problems if you have other scripts that use the window onLoad settings --> <script type="text/javascript" > var myquotes = new Array( <?php $link = mysql_pconnect($host, $username, $password); mysql_select_db('briansch_brn',$link); $sql = "SELECT * FROM story WHERE ORDER BY date DESC LIMIT 4"; $rs = mysql_query($sql,$link); $matches = 0; while ($row = mysql_fetch_assoc($rs)) { $matches++; echo "'<strong>$row[headline]</strong><br />(posted $row[date]) - $row[short_story]<br /><a href='/pages/$row[keyword]'>READ MORE</a>'"; if($matches < 4) { echo ','; } if($matches == 4) { echo ''; } } if (! $matches) { echo (""); } echo ""; ?> ); function rotatequote() { thequote = myquotes.shift(); //Pull the top one myquotes.push(thequote); //And add it back to the end document.getElementById('quotetext').innerHTML = thequote; // This rotates the quote every 10 seconds. // Replace 10000 with (the number of seconds you want) * 1000 t=setTimeout("rotatequote()",10000); } // Start the first rotation. rotatequote(); </script> I know that javascript inside php is hard to make work...and I know that php inside javascript is hard to make work. Any ideas? Thanks! I have a php code... In which there is a link and i want to apply a javascript onclick event onthat link... Code: [Select] echo "<a onclick=vieww_det(". $arr[$i].", ".$arr[$j].")>View Details </a>"; But its not working... Any help will be appreciated - Pranshu Agrawal pranshu.a.11@gmail.com Hello, First of all I am using only divs in my site. I am using js to open links inside my content div and is working fine. Now I have a form that customers need to fill. when they fill wrong things they get error msgs. How do I make the error msg to appear in my page instead of opening a new blank one? Thank you I need to put php inside php. Code: [Select] $insertGoTo = "index.php? "$sbninesven" "; if (isset($_SERVER['QUERY_STRING'])) { $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?"; $insertGoTo .= $_SERVER['QUERY_STRING']; } What do I do to get that inside of $insertGoTo = "index.php? "$sbninesven" "; hello, might be a stupid question but can you put an if and else inside of if brackets like i have done in this script? <?php require("../include/mysqldb.php"); $uinwish = $_GET['uinwish']; $wishrefer = $_SERVER["HTTP_referer"]; $wishdate = mktime(0, 0, 0, date("m"), date("d")+3, date("Y")); $rand_wish_cookie = $_COOKIE["wishtracking"]; $con = mysql_connect("$dbhost","$dbuser","$dbpass"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("$dbame", $con); $sql = "select * from Wish_list_guest where usercookie='$rand_wish_cookie' and uinwish='$uinwish'"; //search db has the profile already been added to favorites $result = mysql_query($sql); $row = mysql_fetch_row($result); if (mysql_num_rows($result)!= 1) { //if 1 of more results found profile already added redirect back! //Re-direct back script!! if (!isset ($wishrefer)){ $host = $_SERVER['HTTP_HOST']; $uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); $extra = 'profile.php?uin='; header("Location: http://$host/$extra$uinwish"); exit; } else { header("Location: $wishrefer"); exit; } //end redirect script else { mysql_query("INSERT INTO Wish_list_guest (usercookie, date_delete, uinwish, referwish) VALUES ('$rand_wish_cookie', '$wishdate', '$uinwish', '$wishrefer')"); mysql_close($con); } if (!isset ($wishrefer)){ $host = $_SERVER['HTTP_HOST']; $uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); $extra = 'profile.php?uin='; header("Location: http://$host/$extra$uinwish"); exit; } else { header('Location: $wishrefer'); exit; } ?> Everything works except for the data needed for "$f_images", which what I am trying to get is the multiple images for each product. Code: [Select] <?php $featured_results = mysql_query("SELECT * FROM products JOIN product_images ON products.product_id=product_images.product_id WHERE products.product_active='1' AND thumb='1' Limit 10"); while($featured_row = mysql_fetch_assoc($featured_results)) { //Thumbnail Query $fthumb_result = mysql_query("SELECT image_name FROM product_images WHERE product_id='".$mfeatured_row['product_id']."' AND thumb='1'"); $fthumb = mysql_fetch_row($fthumb_result); $fimages_result = mysql_query("SELECT image_name FROM product_images WHERE product_id='".$featured_row['product_id']."'"); while($fimages_row = mysql_fetch_assoc($fimages_result)) { $f_images .= "'/includes/getimage.php?img=".$fimages_row[0]."&w=224', "; } $f_vars .= "\nproductId = ".$featured_row['product_id'].";\napp.isotope.vars.homeFeaturedImages[productId] = [".$f_images."];\napp.isotope.vars.homeFeaturedProducts[productId] = {\nname : \"".$featured_row['product_name']."\",\nprice : \"".$featured_row['product_price']."\",\nurl : '/'\n};"; } ?> Hello, I need to add rel="..." in the first part of the script but it is not working, below is the script: Code: [Select] echo " <a href='products/".$image[$abc]."' target='_blank'><img border=0 src='products/thumbs2/".$image[$abc]."' /></a>"; Thank you, I want to use a window.open java script but generate the list of links via phpe <script> function multiWin() { $s=2; while ($s <= 25) { echo '$links[$s]'; $s++; } } </script> I realize the above coding is wrong and it will be inside php so how would I do it correctly? Also I want it to drop a liner after every link. I've played around with this for a few hours now and I am completely lost now. im trying to create a table for a site admin. bsicaly all he has to do is fill out a form and the values of the form are turned into the table name. im using a .sql file as a template but to create the table i need the php genarated table name to be inserted into the .sql file. <?php include("config.php"); $con details $tbl_name = "static_name_for_now"; if (mysql_query("seat_plan.sql")) { echo "success"; } else{ echo "fail"; } ?> sql file snippet INSERT INTO `<?php $tbl_name ?>` VALUES('A', 1, 0, 'Y'); also tried INSERT INTO `<?php echo $tbl_name ?>` VALUES('A', 1, 0, 'Y'); thanks I get this error so I was wondering if it is because I can't put a while inside a foreach? "syntax error, unexpected T_WHILE in home/g/h/t...." while($rows=mysql_fetch_array($rr)){ $pt_id = unserialize($rows['pts']); foreach ($pt_id as $indiv) { $q = "select * from indiv where id_incr = '$indiv'"; echo $q; $result = mysql_query($q) while $ptrow =mysql_fetch_array($result)){ echo $ptrow['v1']; echo "<br>"; } } } As of right now I have values of 0 for the fields in champ_id as well as the con1_id, con2_id, and con3_id which is all fine. The end query returns 0 results which I understand however I'm trying to figure out that if the values in these fields is 0 then have it echo "Vacant" but i'm not sure if you can do a if statement inside a select statement. $query = "SELECT titles.titlename, titles.id, ( SELECT c.charactername FROM characters AS c WHERE c.id = champions.champ_id ) AS champion, ( SELECT c.charactername FROM characters AS c WHERE c.id = champions.con1_id ) AS con1, ( SELECT c.charactername FROM characters AS c WHERE c.id = champions.con2_id ) AS con2, ( SELECT c.charactername FROM characters AS c WHERE c.id = champions.con3_id ) AS con3 FROM champions INNER JOIN titles ON champions.title_id = titles.id"; i have a database which contains a table named girls with three columns ...Serial(int) name(text) hits(int) <?php error_reporting(E_ALL ^ E_NOTICE); $con = mysql_connect("localhost","gaurav",""); mysql_selectdb("website",$con); $index1 = rand(1,$count); $sql = mysql_query("SELECT * FROM girls WHERE Serial=$index1"); $row = mysql_fetch_array($sql); $name1 = $row['name']; $hits1 = $row['hits']; echo <<<ECO <html> <script language="javascript"> increment(){ // some php code to increase the hits in database where name = $name1 } </script> <input type="button" value="increment" onclick="increment();" name="button"> </html> ECO; ?> sorry for the code to be really haphazard..i jst started with php.....now i dont know wat code to put to increment the hits in increment function since it would also use varialble $name1 and $index1..... I'm sure you can do this in PHP, but for some reason when I view news.php - It automatically tells me I liked the post, when I haven't even clicked like yet! while($fetch = mysql_fetch_assoc($query)) { if($_GET['like'] == $fetch['id']) { $like = mysql_real_escape_string($_GET['like']); $has_liked = mysql_query("SELECT * FROM likes WHERE id = '$like' AND username = '". $_SESSION['user'] ."'"); if(mysql_num_rows($has_liked) > 0) { echo " <div id='post-1' class='post'> <h2 class='title'><font color='white'>#". $i." ".$fetch['title'] ."</font> <h3 class='date'>". $fetch['date'] ."</h3> <div class='entry'> <p>". nl2br(stripslashes($fetch['content'])) ."</p> </div> <p class='meta'><b>You've already liked this announcement.</b></p> </div> "; } else { mysql_query("UPDATE news SET likes = likes + 1 WHERE id = '". $_GET['id'] ."'"); echo " <div id='post-1' class='post'> <h2 class='title'><font color='white'>#". $i." ".$fetch['title'] ."</font> <h3 class='date'>". $fetch['date'] ."</h3> <div class='entry'> <p>". nl2br(stripslashes($fetch['content'])) ."</p> </div> <p class='meta'><b>You liked this announcement.</b></p> </div> "; } } else { echo " <div id='post-1' class='post'> <h2 class='title'><font color='white'>#". $i." ".$fetch['title'] ."</font> <h3 class='date'>". $fetch['date'] ."</h3> <div class='entry'> <p>". nl2br(stripslashes($fetch['content'])) ."</p> </div> <p class='meta'><a href='news.php?like=". $fetch['id'] ."'>Like</a></p> </div> "; } } how can i put an if statement inside an echo this is what i want to do Code: [Select] <?php echo "<li> <a class='thumb' href='../images/Sections/pinkpanthers/" . $year . "/" . $sessions . "/" . $day . "/" . $y . ".jpg' title=''> <img src='../images/Sections/pinkpanthers/" . $year . "/" . $sessions . "/" . $day . "/thumbs/" . $y . ".jpg ' /></a><div class='caption'> <div class='download'><a href='../images/Sections/pinkpanthers/" . $year . "/" . $sessions . "/" . $day . "/big/" . $y . ".jpg ' target='_blank' />Download</a> </div><div class='image-desc'>" . if ($count == 1){echo "<a href='tag.php?tag=$name'" . $name . ">" . $name . "</a>";}if ($count > 1){$z = 0;$w = $count - 1;while ($z <= $w){$p = $multi[$z];echo "<a href='tag.php?tag=$p'" . $p . ">" . $p . "</a>";$z++;}} . "</div></div></li>"; ?> all the code works wright up until i added the if statements in the last little bit |