Jump to content

Search the Community

Showing results for tags 'while'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. Hi, Freaks, I hope all are well. I'm trying to make a while loop and there's a common manner used that I've seen in many, many example of code -> <?php while($row = mysqli_fetch_array($data_query)) { ... } and this manner of doing it auto-stops when it's to the end of the mysqli array. Using this exact way is not compatible with the syntax that I can use as I use a database wrapper that is highly abstracted. for example, this would be the typical layout of a DB query for a user post -> <?php $table = "un_posts"; $field = "deleted"; $value = "no"; $rule = "ORDER BY id DESC"; $query = $this->_db->get($table, array($field, "=", $value), $rule); $this->_data = $query->all(); // $this->_data is an array of objects and this would be my typical way of assigning the data -> <?php foreach ($this->data() as $obj) { $post_data = array( "id" => $obj->id, "content" => $obj->content, "added_by" => $obj->add_by, "date_added" => date("F d, Y H:i:s", strtotime($obj->date_added)), "user_to" => $obj->user_to, ); for project specific reasons I'd like to change this from a foreach loop to a while loop. What I found out is that the auto-stop of the while loop using the $row = mysqli..... does not work if I do something like this -> <?php while($obj = $this->data()) { $post_data = array( "id" => $obj->id, "content" => $obj->content, "added_by" => $obj->add_by, "date_added" => date("F d, 20y H:i:s", strtotime($obj->date_added)), "user_to" => $obj->user_to, ); and it creates an infinite loop. Keeping in mind that $this->data() (I have a class method data() that returns $this->_data if anyone noticed the difference) is an array of objects why am I not getting the same result as <?php while($row = mysqli_fetch_array($data_query)) { ... } I don't understand. They're both arrays being looped through. What's the difference where mine isn't breaking the loop at the end but the mysqli array breaks the loop at the end of it?
  2. <?php function factorial($number) { if ($number < 2) { return 1; } else { return ($number * factorial($number-1)); } } function poisson($occurrence,$chance) { $e = exp(1); $a = pow($e, (-1 * $chance)); $b = pow($chance,$occurrence); $c = factorial($occurrence); return $a * $b / $c; } $x = 2.5; $y = 1.5; $calAll = array(); for($z = 0 ; $z <= 9 ; $z++) { array_push($calAll, (poisson($z,$x) * poisson(0,$y))*100, (poisson($z,$x) * poisson(1,$y))*100, (poisson($z,$x) * poisson(2,$y))*100 ); } $value = max($calAll); $key = array_search($value, $calAll); print_r($calAll) . "\n"; echo "max =",$value , " key =",$key . "\n";; ?> it is possible to find $z and the number 0,1 or 2 from the max of the returned array ? I used excel to perform this action and i found that for max=8.5854557290941 the $z is 2 and number 1 how to achieve this in php ?
  3. <?php function getFullMonthName($num) { if ($num < 1 || $num > 12) { return "Unknown"; } return ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][$num - 1]; } $ids = mysqli_real_escape_string($db, $id); $sql = "SELECT * FROM multimedia, keertan WHERE multimedia.id LIKE '$ids' AND keertan.multimediaid LIKE '$ids' ORDER BY k_order ASC"; $result = mysqli_query($db, $sql); $title_list = "xyz"; $done = "xyz"; while ($myrow = mysqli_fetch_array($result)) { $location = $myrow["location"]; $program = $myrow["program"]; $year = sprintf("%04s", $myrow["year"]); $month = sprintf("%02s", $myrow["month"]); $monthName = getFullMonthName($month); $isnew = $myrow["isnew"]; if ($done != "true") { echo "<h3><b>$location $program $monthName $year</b></h3>"; } $done = "true"; while ($title_list != $myrow["title"]) { $title_list = $myrow["title"]; $sublist = $myrow["sub_title"]; echo "<div class=\"panel panel-primary\"><div class=\"panel-heading clickable\"><h3 class=\"panel-title\"><b>$title_list</b></h3>"; echo "<small>$sublist</small><span class=\"pull-right\"><i class=\"fa fa-minus\"></i></span></div><div class=\"panel-sarabveer-table\"><table class=\"table\"><thead><tr><th>Time</th><th>Kirtani</th><th>MP3</th><th>Video</th></thead>"; } if (strtotime($myrow["created"]) > strtotime("3 weeks ago")) { $newed = "NEW"; } elseif (strtotime($myrow["modified"]) > strtotime("3 weeks ago")) { $newed = "UPDATED"; } else { $newed = ""; } printf("<tr><td>%s</td><td>%s <small>%s</small></td>", $myrow["length"], $myrow["keertaneeya"], $newed); $mp3f = urlencode($myrow['mp3_link']); if ($myrow["mp3_link"] != "") { printf("<td><a target=\"_blank\" href=\"http://www.akji.org.uk/multimedia/%s/%s/%s\"><img src=\"images/play.png\" border=\"0\" width=\"25\" height=\"25\"></a></td>", $myrow["location"], $year, $mp3f); } else { echo "<td></td>"; } if ($myrow["rv1_link"] != "") { printf("<td><a target=\"_blank\" href=\"%s\"><img src=\"images/vplay.png\" border=\"0\" width=\"25\" height=\"25\"></a></td></tr>", $myrow["rv1_link"]); } else { echo "<td></td></tr>"; } echo "</table></div></div>"; } ?> So Basically I have this code that displays this page: https://akjmobile.org/keertannew.php?id=532 The problem is that the echo on line 97 runs to early and cuts of rest of the table information, making the other table information be spit out outside of the Bootstrap Panel. How would I fix this?
  4. Hello so I have a simple code here that will check if a random number already exists in the database and will generate a new one: $rand = mt_rand(100000, 999999); $sid = array( ":sponsorID" => $rand ); $accounts = $db->select("accounts", "sponsorID = :sponsorID", $sid) while(count($accounts) > 0) { $newNum = mt_rand(100000, 999999); } What I wanted to do is to echo out $newNum. When I echo it out I get undefined index of that variable. How can I solve this?
  5. Hi everyone, I am still learning PHP, I am getting better a little, but i am still struggle with while and foreach loop to create few columns. I create one column with while or foreach, but I couldn't figure to create few columns intsead of one long column. Can you help me or make any suggest? Thank you so much
  6. Hi everyone, I am still learning to do PHP, please be patient with me. Thank you so much! I am trying to understand how "while loop" work in PHP, or do you recommend me use foreach, for, or do for array list from MySQL database? my Code in PHP: <!doctype html> <html> <head> <title>Test foreach columns</title> <link href="default.css" rel="stylesheet" type="text/css"> </head> <body> <?php $Garydb = mysqli_connect("XXXXXX","XXXXXX","XXXXXX") or die("Could not connect MySQL Database"); mysqli_select_db($Garydb, "XXXXXX") or die("Could not find Database"); $sql = "SELECT * FROM XXXXXX"; $display = mysqli_query($Garydb, $sql); while($key = mysqli_fetch_array($display)) { echo "<table><tr><td>".$key."</td><td>".$key."</td></tr></table>"; } ?> </body> </html> seem display on website showing "Array Array" 12 row and 2 columns, what I did do wrong?
  7. Hi, I have a json data, below which contains an item with tax: "date": "2015-05-05 12:41", "shop": "Toto", "products": [ { "price": "2.00", "quantity": "1", "description": "chocolat", "tax": [ { "price": "1.00", "quantity": "1", "description": "tax1" }, { "price": "2.00", "quantity": "1", "description": "tax2" } ] } ] } I am able to calculate the price ($amountAll) with the following code: $datajs = "myJsonSimple2.json"; $datajs = file_get_contents($datajs); $decodageDatajs = json_decode($datajs); $dateBiling = $decodageDatajs->date; $shopName = $decodageDatajs->shop; foreach ($decodageDatajs->products as $obj) { $ItemPrice = $obj->price; $ItemQuantity = $obj->quantity; $ItemDescription = $obj->description; $taxes = (array)$obj->tax; $taxesPrice1 = !empty($taxes[0]) ? $taxes[0]->price : 0.00; $taxesPrice2 = !empty($taxes[1]) ? $taxes[1]->price : 0.00; $taxesQuantity1 = !empty($taxes[0]) ? $taxes[0]->quantity : 0; $taxesQuantity2 = !empty($taxes[1]) ? $taxes[1]->quantity : 0; $taxesDescription1 = !empty($taxes[0]) ? $taxes[0]->description : '1er tax null'; $taxesDescription2 = !empty($taxes[1]) ? $taxes[1]->description : '2e tax null'; $amountAll = $ItemPrice * $ItemQuantity + $taxesPrice1 + $taxesPrice2; } But how I calculate if there are several items (2 or 3 or 5...) { "date": "2015-05-05 12:41", "shop": "Toto", "products": [ { "price": "2.00", "quantity": "1", "description": "chocolat", "tax": [ { "price": "1.00", "quantity": "1", "description": "tax1" }, { "price": "2.00", "quantity": "1", "description": "tax2" } ] }, { "price": "3.00", "quantity": "1", "description": "bonbon", "tax": [ { "price": "2.00", "quantity": "1", "description": "tax1" }, { "price": "3.00", "quantity": "1", "description": "tax2" } ] }, { "price": "2.00", "quantity": "1", "description": "gateaux", "tax": [ { "price": "1.00", "quantity": "1", "description": "tax1" }, { "price": "2.00", "quantity": "1", "description": "tax2" } ] } ] } I need like as : $amountAll = $ItemPrice1 * $ItemQuantity1 + $ItemPrice2 * $ItemQuantity2 + $ItemPrice3 * $ItemQuantity3 + $taxesPrice1a + $taxesPrice2a + $taxesPrice1b + $taxesPrice2b + $taxesPrice1c + $taxesPrice2c; but this is wrong : I must counter and use while statement but I don,t know how I can write ? $calculeItems = count($decodageDatajs->products); $i = 0; while ($i < $calculeItems) { foreach ($decodageDatajs->products as $obj) { $ItemPrice = $obj->price; $ItemQuantity = $obj->quantity; $ItemDescription = $obj->description; $taxes = (array)$obj->tax; $taxesPrice1 = !empty($taxes[0]) ? $taxes[0]->price : 0.00; $taxesPrice2 = !empty($taxes[1]) ? $taxes[1]->price : 0.00; $taxesQuantity1 = !empty($taxes[0]) ? $taxes[0]->quantity : 0; $taxesQuantity2 = !empty($taxes[1]) ? $taxes[1]->quantity : 0; $taxesDescription1 = !empty($taxes[0]) ? $taxes[0]->description : '1er tax null'; $taxesDescription2 = !empty($taxes[1]) ? $taxes[1]->description : '2e tax null'; $amountAll = $ItemPrice * $ItemQuantity + $taxesPrice1 + $taxesPrice2; /* this si wrong !!!!! $amountAll = $ItemPrice1 * $ItemQuantity1 + $ItemPrice2 * $ItemQuantity2 + $ItemPrice3 * $ItemQuantity3 + $taxesPrice1a + $taxesPrice2a + $taxesPrice1b + $taxesPrice2b + $taxesPrice1c + $taxesPrice2c; */ } $i++; } can you help me please Thanks
  8. Hi everyone, I'm having troubles with query from database. I want to select all from one table and select sum from second table in the same time. Is this possible? Here is my script: $conn = mysqli_connect('localhost', 'root', '', 'test'); if (!mysqli_set_charset($conn, "utf8")) { printf("Error loading character set utf8: %s\n", mysqli_error($conn)); } $sql = "SELECT first_id, first_name FROM first"; $sql = "SELECT sum(total) as SumTotal FROM second"; $result = mysqli_query($conn, $sql); while ($data = mysqli_fetch_array($result)) { echo '<tr>'; echo '<th>'.$data['first_id'].'</th>'; echo '<th>'.$data['first_name'].'</th>'; echo '<th>'.$data['SumTotal'].'</th>'; echo '</tr>'; } mysqli_close($conn); Thanks!
  9. I'm not sure I know how to explain what I want to allow you to understand. I'm working on a ventilation app that has different fan sizes. In the input php file I have a dropdown list that's populated by what's in the database. I'd like a results page that lists the fan size and number of each size and the cfm's each fan kicks out. the problem is that I don't know how to do anything with it other than hard code it. What I'd like, is for it to also pull all of the fan sizes and list them, that way the database can be fluid. This is the code I'd like to replace with some sort of loop. //9" fan $results = mysql_query("SELECT * FROM fan WHERE size=9", $link); while ($row = mysql_fetch_array($results)) { $capacity9 = $row['capacity']; }; //--------------------------------------------------------- //10" fan $results = mysql_query("SELECT * FROM fan WHERE size=10", $link); while ($row = mysql_fetch_array($results)) { $capacity10 = $row['capacity']; }; //--------------------------------------------------------- //14" fan $results = mysql_query("SELECT * FROM fan WHERE size=14", $link); while ($row = mysql_fetch_array($results)) { $capacity14 = $row['capacity']; }; //--------------------------------------------------------- //16" fan $results = mysql_query("SELECT * FROM fan WHERE size=16", $link); while ($row = mysql_fetch_array($results)) { $capacity16 = $row['capacity']; }; //--------------------------------------------------------- //18" fan $results = mysql_query("SELECT * FROM fan WHERE size=18", $link); while ($row = mysql_fetch_array($results)) { $capacity18 = $row['capacity']; } //--------------------------------------------------------- //20" fan $results = mysql_query("SELECT * FROM fan WHERE size=20", $link); while ($row = mysql_fetch_array($results)) { $capacity20 = $row['capacity']; }; //--------------------------------------------------------- //24" fan $results = mysql_query("SELECT * FROM fan WHERE size=24", $link); while ($row = mysql_fetch_array($results)) { $capacity24 = $row['capacity']; }; //--------------------------------------------------------- //36" fan $results = mysql_query("SELECT * FROM fan WHERE size=36", $link); while ($row = mysql_fetch_array($results)) { $capacity36 = $row['capacity']; };
  10. Hi all, I have a looping error in my PHP. I am trying to add use a while statement to gather the users first and last name in to a string, add them to an array called $friendname, then check that the $friendname[] is only output/echoed once. At the moment the code looks good to me but with multiple rows with the same name associated, the name is echoed the same amount of times as rows, instead of once as it is supposed to be. Any ideas anyone? while($row2 = mysqli_fetch_assoc($result2)) { $friendcode = $row2['Code']; $names = "SELECT FirstName, LastName from users WHERE Code = '$friendcode' AND Code != '$crewcode'"; $resultnames = mysqli_query($cxn,$names) or die ("Can't get friends names."); while($rownames = mysqli_fetch_assoc($resultnames)) { $friendname = array(); $newfriendname = ($rownames['FirstName'].' '.$rownames['LastName']); if (!in_array($newfriendname, $friendname)) { array_push($friendname, "$newfriendname"); echo $newfriendname; } } }
  11. I have the following code which prints results from a sqlsrv_fetch_array() using a while loop. For one segment, however, I only need the first $value of the $key=>$value pair, and obviously with the code written this way it returns all rows. I have an idea of an approach, and I'm wondering if I'm headed in the right direction or if anyone has experience with this that they can share. So, during the while loop, I am pushing the elements of the sqlsrv_fetch_array() into a separate array. So I see two potential options: 1. Print from the $actcontacts[] array rather than from the sqlsrv fetch array. 2. During the while loop, rather than pushing anything into a new array, build a conditional that says to only print the record if $row['ENDTIME'] is in position $row[0]. I'm leaning toward #2, but I'm not quite sure how to get there...and if there is a better way under door #3, I would like to try that. while ($row = sqlsrv_fetch_array( $stmt_act, SQLSRV_FETCH_ASSOC) ) { $actcontacts[] = "N/A" . "," . $row['COMPANYNAME'] . "," . $row['CITY'] . "," . $row['STATE'] . "," . $row['CUST_Salesman_124705300'] . "," . $row['ENDTIME'] . "," . "ACT"; // I have done a print_r() on $actcontacts and the data is correct. $endtime[] = $row['ENDTIME']; echo "<tr>"; echo "<td>" . "<i>N/A</i>" . "</td>"; echo "<td>" . $row['COMPANYNAME'] . "</td>"; echo "<td>" . $row['CITY'] . "</td>"; echo "<td>" . $row['STATE'] . "</td>"; echo "<td>" . $row['CUST_Salesman_124705300'] . "</td>"; echo "<td>" . $row['ENDTIME'] . "</td>"; // This is the bugger that is printing eleventy records. It may be one customer, but there are always multiple contact/history entries. echo "<td>" . "ACT" . "</td>"; echo "</tr>"; }
  12. Hi guys, I am trying to create a while condition that would display an output such as: "Duty: 1234, = Dep: 01:00, End: 03:35 code1, code4, code5" The problem I am having is instead of echoing the first line once, with my while statements the first line will echo as many times are there are codes associated with it that I am trying to output from another mysql table. Have a look below and you will see what I mean! My output at the moment looks like: "Duty: 1234, = Dep: 01:00, End: 03:35 code1 Duty: 1234, = Dep: 01:00, End: 03:35 code4 Duty: 1234, = Dep: 01:00, End: 03:35 code5" $sql = "SELECT * FROM calendar WHERE Duty = '$duty' AND BeginTime = '$begintime' AND EndTime = '$endtime'"; $result = mysqli_query($cxn,$sql) or die ("Can't execute query."); while($row=mysqli_fetch_assoc($result)) { echo 'Duty: '.$row['Duty'].' = Dep:'.$row['BeginTime']. ', Land:'.$row['EndTime'].'<br />'; $sql1 = "SELECT * FROM users WHERE Code = '{$row['Code']}'"; $result1 = mysqli_query($cxn,$sql1) or die ("Can't execute query1."); while($row1 = mysqli_fetch_assoc($result1)) { echo $row1['Rank'].': '.$row['Code'].'</br>'; } } Thanks!
  13. Greetings all, I have been developing a comment box for my site and I ran into an issue I can't seem to figure out. In my comment box when I am logged in as an admin I want to be able to delete comments by simply clicking a button. The comments are printed out from a database using a while loop: <?php echo '<div id="commentMainTitle"><h3>Video Comments</h3></div>'; while($row = mysqli_fetch_array($results, MYSQLI_ASSOC)){ echo '<div id="commentUniqueWrap"> <div id="commentUniqueTitleMessageWrap"> <div id="commentUniqueTitle"> <h4>'. stripslashes($row['name']) .'</h4>';?> <?php if (isset($_SESSION['admin'])){?> <!--If admin add form for delete comment.--> <form enctype="multipart/form-data" action="includes/function/deletecomment.php" method="post"> <input type="hidden" name="cursect" value="<?php echo $sect1;?>" /> <input type="hidden" name="curvideored" value="<?php echo $_GET['curvideo'];?>" /> <input type="hidden" name="postID" value="<?php echo $row['id'];?>" /> <input type="submit" name="submit" value="Delete" /> <?php echo $row['id']; } echo '</div> <div id="commentUniqueMess"> <p>' . stripslashes($row['comment']). '</p> <p class="datealign">' . $row['date'] . '</p> </div> </div> </div>'; } ?> When the comments are listed out a Delete button is listed next to the commentors name. A comment is deleted however it is not the comment that is selected for deletion. Instead the last comment that was echo'd out from the while loop is deleted. Here is the script that deletes the comment: <?php if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['postID'])){ //Requires the database connection script. require $_SERVER['DOCUMENT_ROOT'] . '/mywebsite/masters/connect.php'; $qdelete = "DELETE FROM comment WHERE id ='".$_POST['postID']."' LIMIT 1"; if (!mysqli_query($connect,$qdelete)){ die('Error: ' . mysqli_error($connect)); } // Close database connection. mysqli_close($connect); // Set path for redirect. $redirect = 'http://www.mywebsite.com/myvideos.php?sect=' . $_POST['cursect'] . '&curvideo=' . $_POST['curvideored']; // Redirect to previous page. echo '<script type="text/javascript"> setTimeout(redirect, 0000); function redirect() { location.href="'.$redirect.'" } </script>'; } ?> I'm not sure what the issue is or how to go about solving it. I feel like the answer is staring me in the face but I've been looking at the code for too long and it has me at a loss. Any help would be greatly appreciated. Thank you for your time. Best Regards, Nightasy
  14. Ok, so I created a test database on my server, created 1 table with 1 row in it and the row is populated with values. I can connect to the database without error, but when I try to put in a while loop to print the results I get nothing but a blank screen. I tried placing some debug code in the while loop to see where its getting hung up but the while loop doesn't want to run at all. I placed an echo directly outside of the loop and the debug text is displayed fine but anything I put in the loop doesn't work. Can anyone help me out? Here is my code: <!doctype html> <html> <head> <meta charset="utf-8"> <title>Untitled Document</title> </head> <body> <?php $dbuser = "webestat_testdb"; $dbpass = "password"; $dbname = "webestat_testdb"; $server = "localhost"; $conn = mysql_connect($server, $dbuser, $dbpass); if (!$conn) { echo "Failed to connect to db" . mysql_error(); } $selectdb = mysql_select_db('webestat_testdb', $conn); $sql = "SELECT * FROM 4000Series"; $results = mysql_query($conn, $sql); while($row = mysql_fetch_assoc($results)) { echo "test"; echo $row['gpu']. " " .$row['khs']. " " .$row['usd']; echo "<br>"; } mysql_close($conn); ?> </body> </html>
  15. I read data from binary file which contains names of domains separated by semicolon. I have saved one word "localhost;" into the position. I tried more versions, the main difference is with the use of last condition of the while loop: $word=$byte=""; fseek( $fh , $n );echo "n is $n;"; while ( $byte=fread($fh,1) && bindec($byte)!=59) // semicolon is ord 59 ... && ord($byte)!=0 { echo "<b>".$byte."</b>"; $word.=$byte; } echo ":$word==".$_SERVER["HTTP_HOST"]."<br>".ord($byte); if ( $word==$_SERVER["HTTP_HOST"] ) return false; // this domain is blocked First of all I tried this: while ( $byte=fread($fh,1) && $byte!=";") none works: while ( $byte=fread($fh,1) && chr($byte)!=";") also no success: while ( $byte=fread($fh,1) && ord($byte)!=";") It should print localhost==localhost ... however I am getting number one instead (repeated ). If I will skip the last condition, the localhost is printed commonly with the rest of the file (but I need to break it). Any idea what I do wrong?
  16. Ugh - title should say sort, not sport, sorry. This should be easy, but for the life of me, I cannot get this to work. I've been staring at it for so long, I'm going nuts. Ultimately, what I'm trying to do is combine the unique results of a query (of 3 columns of a table) to populate a drop-down menu. I have a function in place, however, that function only grabs data from one of the 3 fields I designate, not all 3. So I'm trying to create a new query to search all 3 fields, remove duplicates, sort alphabetically, and then display them in the drop-down list. Here's the function I originally had, but I don't know how to alter this (if possible) to include combining 3 fields instead of having to list 1: function filldropdown($sql, $sfieldname) { $result=mysql_query($sql); while($row=mysql_fetch_assoc($result)){ echo "<option value='" . $row[$sfieldname] . "'>" . $row[$sfieldname] . "</option>"; } mysql_free_result($result); return; } And then this is the code that adds the list to the page, except you'll notice at the end of the query, I have to list only 1 field to pull from (TW), instead of it listing TW1, 2 and 3. <? filldropdown("SELECT distinct TW, TW2, TW3 from TABLE", "TW"); ?> So instead, I'm trying to do this (I've simplified this to hopefully make it easier to understand my thought process of what I'm trying to do). What am I doing wrong? $TW1 = mysql_query("SELECT distinct TW from TABLE"); $TW2 = mysql_query("SELECT distinct TW2 from TABLE"); $TW3 = mysql_query("SELECT distinct TW3 from TABLE"); // combine and sort results of TW, TW2, TW3 fields into a single list $TW1result = mysql_fetch_array($TW1); $TW2result = mysql_fetch_array($TW2); $TW3result = mysql_fetch_array($TW3); $CombinedTW = array_merge($TW1result, $TW2result, $TW3result); $UniqueTW = array_unique($CombinedTW); $ALLTW = asort($UniqueTW); while($ALLTW) { echo "<option value='" . $ALLTW . "'>" . $ALLTW . "</option>"; }
  17. I have the following php code that produces some multiple choice questions with each answer per question giving different points. <?php $done = $_POST['done']; if ($done < '1' ) { ?> <form action="quiz.php" method="post" /> How many domains do you own? </BR> <input type="radio" name="op1" value="0"> I don't <BR/><input type="radio" name="op1" value="5"> 1 <BR/><input type="radio" name="op1" value="10"> 2 <BR/><input type="radio" name="op1" value="15"> 3 <BR/><input type="radio" name="op1" value="20"> 4 <BR/><input type="radio" name="op1" value="30"> 5 or more <BR><BR> Do you use skype? </BR> <input type="radio" name="op2" value="1"> Yes <BR/><input type="radio" name="op2" value="0"> No </BR></BR> How many people are currently in your Skype contact list? </BR> <input type="radio" name="op3" value="1"> less than 5 <BR/><input type="radio" name="op3" value="2"> 5 to 10 <BR/><input type="radio" name="op3" value="3"> 11 to 15 <BR/><input type="radio" name="op3" value="4"> 15 to 30 <BR/><input type="radio" name="op3" value="5"> more than 30 <BR><BR> <input type="hidden" name="done" value="1"/> <input type="submit" value="Submit...."/> </form> <?php } else { $score1=$_POST['op1']; $score2=$_POST['op2']; $score3=$_POST['op3']; $total = $score1 + $score2+ $score3; print "Your score Is " . $total . "!"; } ?> </div> I am trying to modify the code so i can make it work with a database i have.This is the structure of the table question which also includes the answers and the points of each answer. que_id | test_id | que_desc | ans1 | ans2 | ans3 | ans4 | true_ans | type | points1 | points2 | points3 | points4 | And this is what i have done so far: <?php session_start(); require_once('config.php'); include 'dbconnect.php'; include 'functions.php'; extract($_POST); extract($_GET); extract($_SESSION); if(isset($subid) && isset($testid)) { $_SESSION[sid]=$subid; $_SESSION[tid]=$testid; header("location:$self_page?page=kinder.php"); } ?> <?php $rs=mysql_query("select * from question where test_id=20",$conn) or die(mysql_error()); $i=0; while($row = mysql_fetch_array($rs)) { $i++; $id = $row["id"]; $question = $row["que_desc"]; $opt1 = $row["ans1"]; $opt2 = $row["ans2"]; $opt3 = $row["ans3"]; $opt4 = $row["ans4"]; $score1= $row['points1']; $score2= $row['points2']; $score3= $row['points3']; $score4= $row['points4']; $answer = $row["true_ans"]; echo "$question<br>"; echo "<input type='radio' id='radio1' name='$i' value='$opt1'/><label for='radio1'>$opt1</label><br>"; echo "<input type='radio' id='radio1' name='$i' value='$opt2'/><label for='radio1'>$opt2</label><br>"; echo "<input type='radio' id='radio1' name='$i' value='$opt3'/><label for='radio1'>$opt3</label><br>"; echo "<input type='radio' id='radio1' name='$i' value='$opt4'/><label for='radio1'>$opt4</label><br>"; echo "<br>"; } ?> <center> <input type="hidden" name="done" value="1"/> <input type="submit" value="Submit...."/> </center> </form> <?php } else { $total = ........... } ?> </div> </body> My question is how to pass each answer points using the While loop i have above and how to calculate the total score.
  18. Hey, so to display an image from a database I was using $id = addslashes($_REQUEST['id']); $image = mysql_query("SELECT * FROM store_image WHERE id=$id"); $image = mysql_fetch_assoc($image); $image = $image['image']; header("Content-type: image/jpeg"); echo $image; That worked fine to return an image via matching the id. But I want to get ALL images from the table.. I tried this: $image = mysql_query("SELECT * FROM store_image"); while($image = mysql_fetch_array($image)){ $image = $image['image']; header("Content-type: image/jpeg"); echo $image; } But did not work.. what am I doing wrong?
  19. hey, this should echo all of the results from the query, right? in the database there is more than 1 fields to echo, but it only echos 1, whats wrong with it? $getid = mysql_query("SELECT * FROM $tbl_name WHERE userid='$id'", $connect); $idresults= mysql_fetch_array($getid); while($idresults= mysql_fetch_array($getid)){ echo $idresults['frienduserid']; }
  20. There are a lot of solutions out there as to how to save the position of draggable DIVs but I haven't found any that will help with using a While loop in php. I have a database of "needs" and I want to display all the "needs" that match the persons username and status=inprogress. This could be 1 need or 1,000,000 needs depending on if the criteria is met. I want to save the position of the need (DIV) automatically when it's moved. Is this possible? Here the code I currently have that displays the "needs" (divs) <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" /> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script> <link rel="stylesheet" href="/resources/demos/style.css" /> <style> #set div { width: 90px; height: 90px; padding: 0.5em; float: left; margin: 0 10px 10px 0; } #set { clear:both; float:left; width: 368px; height: 120px; } p { clear:both; margin:0; padding:1em 0; } </style> <script> $(function() { $( "#set div" ).draggable({ stack: "#set div" }); }); </script>
  21. I'm wondering if it's possible in an easy way that when I use while function to call out a bunch of data and put them into table but I want to use css to make it one row with regular background and one row with light background. hopefully what I sad make sense.... this is what I have echo "<style type='text/css'>"; echo "th {background: #CEED5E;}"; echo "</style>"; echo "<table border=1>"; echo "<tr><th>Product ID</th><th>Title</th><th>Author</th><th>Description</th></tr>"; while ($row = mysqli_fetch_assoc($result)) { echo "<tr><td>" . $row["id"] . "</td><td>" . $row["title"] . "</td><td>" . ucwords(strtolower($row["authorFirstName"] . " " . $row["authorLastName"])) . "</td><td>" . $row["description"] . "</td></tr>"; } echo "</table>";
  22. I have created a user defined function to return a string value function getModel($part) { $root = substr($part,0,4); $query = "SELECT Root, Model FROM tbl_Root WHERE Root = '$root'"; $result = mysql_query($query) or die ("Query Root failed: " . mysql_error()); while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) { if (in_array($root, $rec)): $Model = $rec['Model']; else: $Model = 'UNKNOWN'; endif; } return $Model; } When trying to find the attributes of several hundred part numbers, I pass them to a MySQL temp table that would then select the distinct part numbers and loop them through my functions. $query = "SELECT DISTINCT A FROM TempAttributes"; $result = mysql_query($query) or die ("Query failed: " . mysql_error()); while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) { $part = mysql_escape_string($rec['A']); $Model = getModel($part); $query = "REPLACE INTO tbl_Attributes (Part, Model) VALUES ('$part', '$Model')"; $endresult = mysql_query($query) or die ("Query Load failed: " . mysql_error()); } The line of code that stops the execution of my loop is $Model = getModel($part); I executed the loop with this line of code in and it stops after the first part number. When I comment this line of code out, my loop processes all of my part numbers, but of course not with the return values I am looking for. Why does my user defined function not process through the while loop to assign the $Model variable the return value of the getModel function? Please help!
  23. Hey there, so I have a custom Wordpress loop that is working just fine. Inside that loop I have a second loop using Salesforce API. What is happening is that the main loop is looping but the secondary Salesforce loop is showing the same record for each and not looping. There is a unique ID for each so that isn't the problem. while ($wp_query->have_posts()) : $wp_query->the_post(); $sid = get_the_ID(); $SalesForceId = get_post_meta($sid, 'SalesForceId', true); $query = "SELECT Name, Phone, BillingCity, BillingState from Account WHERE Id = '" . $SalesForceId . "'"; $response = $mySforceConnection->query(($query)); foreach ($response->records as $record) { $Name = $record->{Name}; $Phone = $record->{Phone}; $BillingCity = $record->{BillingCity}; $BillingState = $record->{BillingState}; } echo $Name; echo $BillingCity; echo $BillingState; endwhile; ?>
  24. Hi; i want learning PHP coding. i read books and watching tutorials. and i've problem about pointers. i wrote this code by myself and this code not working. <?php $num= Array(0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20); while ($a = current($num)) { echo $a . ","; next($num); } ?> why this is not working ? please help me.
  25. Im having a bit of trouble with my script. I wrote the script originaly to run from one variable which i changed manualy, but now im trying to put the whole script inside a loop. The script is now running all the way through fine on the first loop, starting starting the second but getting stuck at the part with my implode. This is my script that is around the implode area. Bear in mind that this code snippet is from a very large script. $t=1; while ($t <= $bm) { $mn=${'m'.$t}; $mn2[$t]="$mn"; $t++; } // The is where the script runs to, and the error comes from the next few lines and the script stops running $implode=implode(',', $mn2); print $implode; $query2="SELECT * FROM artists WHERE id IN(".implode(',', $mn2).")"; $result2=mysql_query($query2) or die(mysql_error()); $i=0; $bm2=$bm-1; while ($i <= $bm2) { $id3=mysql_result($result2,$i,"id"); ${"id3$i"} = $id3; $s1=mysql_result($result2,$i,"s1"); ${"s1$i"} = $s1; $s2=mysql_result($result2,$i,"s2"); ${"s2$i"} = $s2; $sl1=mysql_result($result2,$i,"sl1"); ${"sl1$i"} = $sl1; $sl2=mysql_result($result2,$i,"sl2"); ${"sl2$i"} = $sl2; $i++; } And this is the error that im getting ,,,You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ',,)' at line 1 Any help or point in the right direction would be amazing right no. Thanks Eric
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.