PHP - Creating Array From Sql Query Data
Hi,
I want to develop array like following Code: [Select] $BCD=array('type' =>'TYPE1', array( 0=>array('column1'=>'value1','column2'=>'value1','column3'=>'value1','column4'=>'value1','column5'=>'value1','column6'=>'value1','column7'=>0), 1=>array('column1'=>'value1','column2'=>'value1','column3'=>'value1','column4'=>'value1','column5'=>'value1','column6'=>'value1','column7'=>0), 2=>array('column1'=>'value1','column2'=>'value1','column3'=>'value1','column4'=>'value1','column5'=>'value1','column6'=>'value1','column7'=>0), 3=>array('column1'=>'value1','column2'=>'value1','column3'=>'value1','column4'=>'value1','column5'=>'value1','column6'=>'value1','column7'=>0), ) )); I have written following code to achieve the same but not getting result. Code: [Select] $sql = "select * from tablename "; $result = mysql_query($sql); $k=0; while ($row = $db->mysql_fetch_array($result)) { // array_push($BCD['type'],$row['type']); $BCD1=array('type' =>$row['type'], array( $k=>array('column1'=>$row['column1'],'column2'=>$row['column2'],'column3'=>$row['column3'],'column4'=>$row['column4'], 'column5'=>$row['column5'],'column6'=>$row['column6'],'column7'=>$row['column7']) )); $k++; } Similar TutorialsHi and thanks for taking the time to read this and to help if you can I have a flex app that is sending data to a php script that will then perform tasks based on the data found inthe array, my problem is that there are over 270 items in the array and I need to alter many of them BEFORE the script performs its task, what I need is a way to alter the data in the array without having to do it one at a time which I will have to do, below is some exxamples of what I am looking to do for example the array will have data on aprox 35 colors and I need to check and these values and change them if needed, my current system is as follows $color1 = $skin['color1']; if (preg_match("/0x/i", $color1)) { $color1 = str_replace("0x", "", $color1); } else { $color1 = str_pad(dechex($color1), 6, '0', STR_PAD_LEFT); } if($color1=="" || $color1=="000000"){$color1="100000";} now currently I would have to do this individualy for $skin['color1'], $skin['color2'], $skin['color3'] etc etc so is there a way I can do it without such bloated code, for example a while or a foreach statement etc? im not great at php so I am not sure how I would go about this if its possible another thing is that the rest of the values in the array are for image values and I need to fillter through them to find out which are the default images and which are not (no tasks are performed on default images) the following are example values from the array for the arrar item $clockface = $skin['clockface'] /home/thesite/public_html/flex_app/assets/default/clockface.png /home/thesite/public_html/flex_app/gallery/clock/clockface_3.png /home/thesite/public_html/flex_app/uploads/uploaded_file.jpg now depending on the value of the array I would wat the following for the 3 values above $clockface = ""; // if its the first value $clockface = "/home/thesite/public_html/flex_app/gallery/clock/pack3/clockface.svg" // if its the second value $clockface = "/home/thesite/public_html/flex_app/uploads/uploaded_file.jpg" // if its the third value now the above is easy to do on an individual basis but I want to streamline my code and not have an if statement with str_replace etc for each and every value which means I would have to do the code over 200 times for the images now as you can see from the first set of values there are certain things that give clues as to what and where the image is ("assests/default", "gallery/clock/clockface_3.png" and "uploads/uploaded_file.jpg") and I would use these to produce the final values above but again I would have to do it on an individual basis for each array value so is there any way I can streamline the process with again a while or a foreach statement or another way of doing this? your help is very much appriciated regards wayne I have these two tables...
schedule (gameid, homeid, awayid, weekno, seasonno)
teams (teamid, location, nickname)
This mysql query below gets me schedule info for ALL 32 teams in an array...
$sql = "SELECT h.nickname AS home, a.nickname AS away, h.teamid AS homeid, a.teamid AS awayid, s.weekno FROM schedule s INNER JOIN teams h ON s.homeid = h.teamid LEFT JOIN teams a ON s.awayid = a.teamid WHERE s.seasonno =2014"; $schedule= mysqli_query($connection, $sql); if (!$schedule) { die("Database query failed: " . mysqli_error($connection)); } else { // Placeholder for data $data = array(); while($row = mysqli_fetch_assoc($schedule)) { if ($row['away'] == "") {$row['away']="BYE";} $data[$row['homeid']][$row['weekno']] = $row['away']; $data[$row['awayid']][$row['weekno']] = '@ '.$row['home']; } }However, I only want to get info for one specific team, which is stored in the $teamid variable. This should be very easy, right? I have tried multiple things, including this one below (where I added an AND statement of "AND (h.teamid=$teamid OR a.teamid=$teamid)"), but this one still outputs too much... $sql = "SELECT h.nickname AS home, a.nickname AS away, h.teamid AS homeid, a.teamid AS awayid, s.weekno FROM schedule s INNER JOIN teams h ON s.homeid = h.teamid LEFT JOIN teams a ON s.awayid = a.teamid WHERE s.seasonno =2014 AND (h.teamid=$teamid OR a.teamid=$teamid)"; $schedule= mysqli_query($connection, $sql); if (!$schedule) { die("Database query failed: " . mysqli_error($connection)); } else { // Placeholder for data $data = array(); while($row = mysqli_fetch_assoc($schedule)) { if ($row['away'] == "") {$row['away']="BYE";} $data[$row['homeid']][$row['weekno']] = $row['away']; $data[$row['awayid']][$row['weekno']] = '@ '.$row['home']; } }Below is the array that the above outputs. In a nutshell, all I want is that 1st array ([1]) which has, in this example, the Eagles full schedule. It's not giving me too much else and I guess I could live with it and just ignore the other stuff, but I'd rather be as efficient as possible and only get what I need... Array ( [1] => Array ( [1] => Jaguars [2] => @ Colts [3] => Redskins [4] => @ 49ers [5] => Rams [6] => Giants [7] => BYE [8] => @ Cardinals [9] => @ Texans [10] => Panthers [11] => @ Packers [12] => Titans [13] => @ Cowboys [14] => Seahawks [15] => Cowboys [16] => @ Redskins [17] => @ Giants ) [27] => Array ( [1] => @ Eagles ) [28] => Array ( [2] => Eagles ) [4] => Array ( [3] => @ Eagles [16] => Eagles ) [14] => Array ( [4] => Eagles ) [15] => Array ( [5] => @ Eagles ) [3] => Array ( [6] => @ Eagles [17] => Eagles ) [] => Array ( [7] => @ Eagles ) [16] => Array ( [8] => Eagles ) [25] => Array ( [9] => Eagles ) [11] => Array ( [10] => @ Eagles ) [7] => Array ( [11] => Eagles ) [26] => Array ( [12] => @ Eagles ) [2] => Array ( [13] => Eagles [15] => @ Eagles ) [13] => Array ( [14] => @ Eagles ) ) I was just wondering if it's possible to run a query on data that has been returned from a previous query? For example, if I do Code: [Select] $sql = 'My query'; $rs = mysql_query($sql, $mysql_conn); Is it then possible to run a second query on this data such as Code: [Select] $sql = 'My query'; $secondrs = mysql_query($sql, $rs, $mysql_conn); Thanks for any help Hi, I want to pull data from db, where sometimes all rows and sometimes rows matching given "username". Here is my code:
//Grab Username of who's Browsing History needs to be searched. if (isset($_GET['followee_username']) && !empty($_GET['followee_username'])) { $followee_username = $_GET['followee_username']; if($followee_username != "followee_all" OR "Followee_All") { $query = "SELECT * FROM browsing_histories WHERE username = \"$followee_username\""; $query_type = "followee_username"; $followed_word = "$followee_username"; $follower_username = "$user"; echo "$followee_username"; } else { $query = "SELECT * FROM browsing_histories"; $query_type = "followee_all"; $followed_word = "followee_all"; $follower_username = "$user"; echo "all"; } }
When I specify a "username" in the query via the url: browsing_histories_v1.php?followee_username=requinix&page_number=1 I see result as I should. So far so good.
Now, when I specify "all" as username then I see no results. Why ? All records from the tbl should be pulled! browsing_histories_v1.php?followee_username=all&page_number=1 This query shouldv'e worked:
$query = "SELECT * FROM browsing_histories";
I'm creating a tool for building project proposals for clients, with pricing. I have a database with two tables: services and clients. The services table looks like this: Code: [Select] | code | name | cost | +-------------+-------------+------+ | logo_design | Logo design | 10 | | web_design | Web design | 20 | The clients table looks like this: Code: [Select] | id | client | logo_design | web_design | +----+---------+-------------+------------+ | 1 | Walrus | yes | yes | | 2 | Narwhal | no | yes | How would I link the results from these two tables so that I only pull out the services each person wants from the database? Here is what I have so far: Code: [Select] <? $sql = "SELECT * FROM services"; $result = mysql_query($sql); while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) { echo $row{'name'} . ': $' . $row{'cost'} . '<br />'; } ?> This, of course, displays all the services, with all the prices, like so: Logo design: $10 Web design: $20 I want to add something here so that based on the selected client, we see only the services/prices they selected (ol' Narwhal's page would not show the "Logo Design" line). I've got the data from "clients" pulled in to this page as well, but don't know how to relate it to "services." Thanks in advance! Let me know if I've left out any info that would help you to point me in the right direction. I am retrieving values in form of array from a database table and out of the I have to build multidimensional array depending upon the parent->child relationship in the same array. The result is as => Array ( => Array ( [label] => Shirt [uri] => # ) [1] => Array ( [label] => Jeans [uri] => # ) [2] => Array ( [label] => Lowers [uri] => # ) [3] => Array ( [label] => T-Shirts [uri] => # ) [4] => Array ( [label] => cotton shirt [uri] => # ) [5] => Array ( [label] => Trousers [uri] => # ) ) each is related to some parent-id. Can any body me any idea. OK, here it is. I have been trying to do this myself, but it has been driving me insane and I turn to professionals here for help.
I am a basic web developer for a company that I work for in other capacities. I have a reasonable understanding of HTML and that is about where my expertise ends. I am not typically a programmer, just a simple (extremely) part time designer that uses Muse and Dreamweaver when necessary.
However, recently my company has asked me to accomplish a task for their website. In plain English, they want a large database that exists currently as a CVS file made into a searchable web page. It is 21 columns by approximately 6,700 rows.
To explain what I need a little more technically, here are my ideas and where I have gotten to so far:
1. The company uses godaddy, into which I *believe* I have successfully imported the spreadsheet. I believe it is successful because through godaddy's SQL Control Panel (phpMyAdmin console), I can do the EXACT searches that the company needs, and it spits out the EXACT results that I need.
2. The end result needs to be a .php that I can upload to the website's root folder that can be then inserted into premade pages using:
<iframe src="SMQ.php" scrolling="yes" width="950" height="800"></iframe>3. On the .php page, I need to have a way to log in to the SQL server and a simple search box built in that will allow the user to input a very simple search string consisting of no more than 4 numbers and 3 letters at a time. No buttons, no check boxes, just a search box. 3. This query then needs to be output as a nice data table, similar to this: This in fact is a screenshot of a search I performed out of my SQL database, in phpMyAdmin using the column "Scott" for the search, and the number 226 as the search term. All column names are visible with the exception of the first column, entitled LINEID, made to be the key, and the output should not include the key but have everything else as above. 4. I can see what the simple line of php is that performed this task: SELECT * FROM `SMQSQL` WHERE `Scott` = '226' ORDER BY `LINEID` ASCbut I can't figure out how the hell to get this incorporated to a .php search. To sum it up, I need a .php page written that can connect to a SQL database, perform a data based search, and spit out a clean table when it is done. I had accomplished this in the past using an import into google docs and using it to perform a search and result display via the following code built into a php called SMQ.php: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Example of Google Spreadsheet Data Visualisation</title> </head> <body> <form id="form1" method="post" action ="<?php echo $_SERVER['PHP_SELF']; ?>"> <label> <input id="search" name="search" type="text" /> </label> <label> <input id="Scott #" name="Scott #" type="submit" value="Scott #" /> </label> <img src="loading.gif" width="16" height="11" /> </form> <p> <?php $search= $_REQUEST['search']; if ($search > ''){ $search = $search;} else { $search = '';} ?> <script type="text/javascript" src="http://www.google.com/jsapi"></script> <script type="text/javascript"> google.load('visualization', '1', {packages: ['table']}); </script> <script type="text/javascript"> var visualization; function drawVisualization() { var query = new google.visualization.Query( 'https://docs.google.com/spreadsheet/ccc?key=0AronCwm9QPefdGpIUllscGgtLUJod2pOazc0bjU0cUE&usp=sharing'); query.setQuery('SELECT A, B, C, D, E, F, G, H, I, J, K, L, M, N, O ,P ,Q ,R ,S ,T WHERE (A) LIKE ("<?php echo $search; ?>") order by A asc label A "Scott #", B "Den", C "Color", D "Cond", E "40", F "60", G "70", H "70J", I "75", J "75J", K "80", L "80J", M "85", N "85J", O "90", P "90J", Q "95", R "95J", S "98", T "98J"'); query.send(handleQueryResponse); } function handleQueryResponse(response) { if (response.isError()) { alert('Error in query: ' + response.getMessage() + '' + response.getDetailedMessage()); return; } var data = response.getDataTable(); visualization = new google.visualization.Table(document.getElementById('table')); visualization.draw(data, { page: 'enable', page: 16, pageSize: 16, legend: 'bottom'}); } google.setOnLoadCallback(drawVisualization); </script> <div id="table"></div> </div> </body> </html>But as you can see, this may not be the most secure thing in the world, plus we want to be able to expand it in the future and not be so simplistic, hence the need to switch to SQL. Please let me know right away by contacting me at disead@gmail.com if this is something YOU might be able to help with. I'm sure for an experienced programmer, once you have the details from me that you need, it would take maybe 10 minutes to write. I don't have much, but I can pay a little bit for this one time job. If it ends up working out, I may be able to pay more down the line for more advanced options such as being able to do drop-down searches based on the column titled "ISSUE", as well as more things down the line as it grows. Thank you so much, I hope to hear from someone soon!!!
My longest post of the year..... (thank you in advance for scrolling 😀) Array ( [newQuantity77777] => 3 [newPrice77777] => 5.00 [usedQuantity77777] => 1 [usedPrice77777] => 3.99 [total77777] => 18.99 [newQuantity88888] => // sometimes empty [newPrice88888] => [usedQuantity88888] => 4 [usedPrice88888] => 12.00 [total88888] => 48.00 [newQuantity44444] => 2 [newPrice44444] => 4.00 [usedQuantity44444] => 0 [usedPrice44444] => 3.99 [total44444] => 8.00 // these values I don't need [date] => July 25 2021 // these values below I don't need [address] => 123 Anystreet Avenue [address2] => [zipcode] => 90210 [city] => Beverly Hills [state] => CA [planet] => Mars ) I've been trying to use that array to create a special "sub-array" for only the SKU numbers and just their new and used quantities and prices. DESIRED RESULT: Array ( [77777] => Array ( [newQuantity] => 3 [newPrice] => 5.00 [usedQuantity] => 1 [usedPrice] => 3.99 ) [88888] => Array ( [newQuantity] => 0 [newPrice] => 0 [usedQuantity] => 4 [usedPrice] => 12.00 ) [44444] => Array ( [newQuantity] => 2 [newPrice] => 4.00 [usedQuantity] => 0 [usedPrice] => 3.99 ) ) Knowing that my SKU numbers are always exactly 5 digits, and no other $_POST keys will ever have 5 digits, I've been able to accomplish this with horribly convoluted and unsatisfactory code like this: $sku = array(); foreach($_POST as $var => $val) { $number = substr($var,-5); if (preg_match("/\d{5}/",$sku)) { $sku[$number] = // the array keys will be the SKU numbers // then I keep looping to look for the string "newQuantity" // capture that value... and create little mini arrays // for my big multidimensional array..... Is there a better way to go about this? Thank you. Hi, after banging my head against the wall for a while thinking this would be a simple task, I'm discovering that this is more complicated than I thought. Basically what I have is a link table linking together source_id and subject_id. For each subject there are multiple sources associated with each. I had created a basic listing of sources by subject... no problem. I now need a way of having a form to create an ordered list in a user-specified way. In other words, I can currently order by id or alphabetically (subject name lives on a different table), but I need the option of choosing the order in which they display. I added another row to this table called order_by. No problem again, and I can manage all of this in the database, however I want to create a basic form where I can view sources by subject and then enter a number that I can use for sorting. I started off looping through each of the entries and the database (with a where), and creating a foreach like so (with the subject_id being grabbed via GET from the URL on a previous script) Code: [Select] while($row = mysqli_fetch_array($rs)) { //update row order if (isset($_POST['submit'])) { //get variables, and assign order $subject_id = $_GET['subject_id']; $order_by = $_POST['order_by']; $source_id = $row['source_id']; //echo 'Order by entered as ' . $order_by . '<br />'; foreach ($_POST['order_by'] as $order_by) { $qorder = "UPDATE source_subject set order_by = '$order_by' WHERE source_id = '$source_id' AND subject_id = '$subject_id'"; mysqli_query($dbc, $qorder) or die ('could not insert order'); // echo $subject_id . ', ' . $order_by . ', ' . $source_id; // echo '<br />'; } } else { $subject_id = $_GET['subject_id']; $order_by = $row['order_by']; $source_id = $row['source_id']; } And have the line in the form like so: Code: [Select] echo '<input type="text" id="order_by" name="order_by[]" size="1" value="'. $order_by .'"/> (yes I know I didn't escape the input field... it's all stored in an htaccess protected directory; I will clean it up later once I get it to work) This, of course, results in every source_id getting the same "order_by" no matter what I put into each field. I'm thinking that I need to do some sort of foreach where I go through foreach source_id and have it update the "order_by" field for each one, but I must admit I'm not sure how to go about this (the flaws of being self-taught I suppose; I don't have anyone to go to on this). I'm hoping someone here can help? Thanks a ton in advance So I'm querying my database to add the results (mapID's) into a PHP array. The MySQL query I used in the below code would usually return 10 values (only 10 mapID's in the database) Code: [Select] while($data = mysql_fetch_array(mysql_query("SELECT mapID FROM maps"))){ $sqlsearchdata[] = $data['mapID']; } Instead the page takes ages to load then gives this error: Quote Fatal error: Allowed memory size of 8388608 bytes exhausted (tried to allocate 16 bytes) It says the error begins on the first line of the above code. I'm assuming this is not the right way to add the value from the MySQL array into a normal PHP array. Can anyone help me? hi i am trying to make a payroll calculator script that takes employee info, calculates pay, displays submitted info in a table, stores info in an array, and updates the array when new info is submitted. i have most of these accomplished, i am having trouble with the "store into an array, and update the array when new info is submitted" parts of the project. i am still not very fluent in php so there may be easier ways to achieve what i have so far. any pointers would be a great help, this part has got me stumped. I have a multi-step form that offers different options of membership to users with the e-mail domain 'vip.co.uk' I finally have it working but have hit a wall with pulling the variables together to form an URL that can be submitted to the payment gateway in the final step.
The variables I need to pass are username, password, email, subscription id (a value attached to a radio button in step 2 - not yet built it).
I have a JS fiddle at http://jsfiddle.net/zsasvoo4/15/.
The final form will be in PHP and I'd prefer to use that language.
Hey Guys. I am trying to create a strict data type within a function. (Boolean only) However when I pass a string it doesn't display any errors. Below is the fucntion I am using. Any help would be really appreciated
function outputAddress($resolve){ if(!is_bool($resolve)) { die("outputAddress() requires a boolean argument"); } outputAddress("true"); // Doesn't display any error messages?? Hello, forgive me if I didn't title this properly. I will try to make this short and sweet and explain it the best I can. I have a script I wrote that uses SimpleXML to parse data and that part works fine. Only problem is the data is kind of construed from the XML feed and I need to convert it to a more real world calculation. The script parses XML for lake level data. The problem is it returns conservation pool levels. The problem with that is lakes are not 400+ feet deep. As it is set up now the XML contains full pool and the current level. From that I display the full pool and the current levels. It then takes the full pool minus the current level to create two new variables, departure I.E. how low or high it is over full pool, then also create % full. The calculations are fine but, since it is basing it off conservation pool I need to translate this to display it in a more known way. What I am wanting to do is hard set the variable for full pool for the actual lake depth. I still need to use the full pool variable to calculate the rest even though I won't be showing that data. So full pool - minus current level to create the departure as it does. Then take the departure variable that was created and subtract/add it from the hard set lake depth to give me the actual new depth of the lake.
I.E.
$a +/- $b = $c
then
$c +/- $d = $e
I hope this makes sense. What I am trying to do is really simple. I am just not good at really explaining things and trying to comprehend how this needs to be laid out and the logic for it. If you need more info or the code I am working with please let me know. So how could I go about doing this?
-Thanks
Edited by Texan78, 28 November 2014 - 12:02 AM. Using curl_multi, I have loaded up 3 url's and then printed the array. 1) How can I also set a timestamp on output to let me know when each url was run? 2) How can I explode the array to only display the data and timestamp, excluding the text "Array ( =>", "[1] =>", "[2] =>" and " )"? Code <?php function multiRequest($data, $options = array()) { // array of curl handles $curly = array(); // data to be returned $result = array(); // multi handle $mh = curl_multi_init(); // loop through $data and create curl handles // then add them to the multi-handle foreach ($data as $id => $d) { $curly[$id] = curl_init(); $url = (is_array($d) && !empty($d['url'])) ? $d['url'] : $d; curl_setopt($curly[$id], CURLOPT_URL, $url); curl_setopt($curly[$id], CURLOPT_HEADER, 0); curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, 1); // post? if (is_array($d)) { if (!empty($d['post'])) { curl_setopt($curly[$id], CURLOPT_POST, 1); curl_setopt($curly[$id], CURLOPT_POSTFIELDS, $d['post']); } } // extra options? if (!empty($options)) { curl_setopt_array($curly[$id], $options); } curl_multi_add_handle($mh, $curly[$id]); } // execute the handles $running = null; do { curl_multi_exec($mh, $running); } while($running > 0); // get content and remove handles foreach($curly as $id => $c) { $result[$id] = curl_multi_getcontent($c); curl_multi_remove_handle($mh, $c); } // all done curl_multi_close($mh); return $result; } $data = array(array(),array()); $data[0]['url'] = 'http://search.yahooapis.com/VideoSearchService/V1/videoSearch?appid=YahooDemo&query=Pearl+Jam&output=json'; $data[1]['url'] = 'http://search.yahooapis.com/VideoSearchService/V1/videoSearch?appid=YahooDemo&query=Black+Eyed+Peas&output=json'; $data[2]['url'] = 'http://search.yahooapis.com/VideoSearchService/V1/videoSearch?appid=YahooDemo&query=Nirvana&output=json'; $r = multiRequest($data); print_r($r); ?> Output Array ( => Pearl Jam [1] => Black Eyed Peas [2] => Nirvana ) Preferred Output 01:00:01 Pearl Jam 01:00:02 Black Eyed Peas 01:00:03 Nirvana This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=344772.0 i've to populate google charts with dynamic data. the data looks llike. +----+-------+---------+-------+-----------+---------+------+ | id | name | physics | maths | chemistry | biology | sst | +----+-------+---------+-------+-----------+---------+------+ | 1 | Name1 | 10 | 25 | 35 | 42 | 62 | | 2 | Name2 | 80 | 45 | 45 | 45 | 25 | | 3 | Name3 | 63 | 25 | 63 | 36 | 36 | | 4 | Name4 | 82 | 36 | 75 | 48 | 42 | | 5 | Name5 | 45 | 45 | 78 | 25 | 24 | | 6 | Name6 | 36 | 36 | 15 | 75 | 36 | | 7 | Name7 | 99 | 45 | 24 | 24 | 45 | | 8 | Name8 | 45 | 85 | 85 | 85 | 96 | +----+-------+---------+-------+-----------+---------+------+ i have to create google charts based on this such that # namewise - such that when i select a name it displays all subject marks of that particular name in a column chart #markswise - when i select a subject, it displays all the names with marks in that particular subject. conisdiering that data may be added and i've to accumulate that also, for namewise i did // chart.php <?php include("connection.php"); $query = "SELECT name FROM csv GROUP BY name DESC"; $statement = $connect->prepare($query); $statement->execute(); $result = $statement->fetchAll(); ?> <!DOCTYPE html> <html> <head> <title>Google charts</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> </head> <body> <br /><br /> <div class="container"> <div class="panel panel-default"> <div class="panel-heading"> <div class="row"> <div class="col-md-9"> <h3 class="panel-title">Student Wise Marks Data</h3> </div> <div class="col-md-3"> <select name="name" class="form-control" id="name"> <option value="">Select Student</option> <?php foreach($result as $row) { echo '<option value="'.$row["name"].'">'.$row["name"].'</option>'; } ?> </select> </div> </div> </div> <div class="panel-body"> <div id="chart_area" style="width: 1000px; height: 620px;"></div> </div> </div> </div> </body> </html> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {packages: ['corechart', 'bar']}); google.charts.setOnLoadCallback(); function load_student_data(name, title) { var temp_title = title + ' '+name+''; $.ajax({ url:"fetch.php", method:"POST", data:{name:name}, dataType:"JSON", success:function(data) { drawStudentwiseChart(data, temp_title); } }); } function drawStudentwiseChart(chart_data, chart_main_title) { var jsonData = chart_data; var data = new google.visualization.DataTable(); data.addColumn('number', 'Physics'); data.addColumn('number', 'Maths'); data.addColumn('number', 'Chemistry'); data.addColumn('number', 'Biology'); data.addColumn('number', 'SST'); $.each(jsonData, function(i, jsonData){ var Physics = jsonData.Physics; var Maths = jsonData.Maths; var Chemistry = jsonData.Chemistry; var Biology = jsonData.Biology; var SST = jsonData.SST; data.addRows([[Physics,Maths,Chemistry,Biology,SST]]); }); var options = { title:chart_main_title, hAxis: { title: "Subjects" }, vAxis: { title: 'Percentage' } }; var chart = new google.visualization.ColumnChart(document.getElementById('chart_area')); chart.draw(data, options); } </script> <script> $(document).ready(function(){ $('#name').change(function(){ var name = $(this).val(); if(name != '') { load_student_data(name, 'Student wise marks data'); } }); }); </script> and in order to fetch data // fetch.php <?php //fetch.php include('connection.php'); if(isset($_POST["name"])) { $query = " SELECT * FROM csv WHERE name = '".$_POST["name"]."' ORDER BY id ASC "; $statement = $connect->prepare($query); $statement->execute(); $result = $statement->fetchAll(); foreach($result as $row) { $output[] = array( 'Physics' => $row["Physics"], 'Maths' => $row["Maths"], 'Chemistry' => $row["Chemistry"], 'Biology' => $row["Biology"], 'SST' => $row["SST"], ); } echo json_encode($output); } ?> it diplays a blank page. however when i play with singular values i.e one subject at a time it displays fine Edited March 19, 2019 by zetastreakI have a array for example: Code: [Select] $item = array( "Great <em>Bittern</em>"=>"Botaurus stellaris", "Little <em>Grebe</em>"=>"Tachybaptus ruficollis", "Black-necked Grebe"=>"Podiceps nigricollis"); which will output Code: [Select] Array ( [Great Bittern] => Botaurus stellaris [Little Grebe] => Tachybaptus ruficollis [Black-necked Grebe] => Podiceps nigricollis ) how can I input data from a database so it comes out as the array assuming I have $row[3] and $row[0] as the data? for example Code: [Select] while($row=mysql_fetch_array($result)){ //$item.=array($row[3],$row[0]); //array_push($item,array($row[3]=>$row[0])); //$item.=array($row[3]=>$row[0]); $item.="[".$row[3]."]=>".$row[0]; } which of course doesnt work?? All I am not the best at PHP and have been trying to work out how to make a treeview from an array. I managed to get as afar as populating my array as i would like and I can get those values back but now im really stuck What id love to be able to do is use my area field as the parent and my title field as the child and have a counter on the parent with no of child nodes. If someone can help me out with that bit id be really greatful, as I ve already sorted my javascript etc this is my last problem and its driving me nuts Many Thanks for looking and i really do appreciate any help Gibbo <?php $row = 0; $myarray = array(); foreach ($view->result as $result) { $arg = $view->render_field('field_decision_type_value', $row); $arg2 = $view->render_field('title', $row); $myarray[$row]["area"]=$arg; $myarray[$row]["title"]=$arg2; $row++; } asort($myarray); $last = count($myarray) - 1; $rowcount=0; while ($rowcount <= $last) { print $myarray[$rowcount]["area"]; print $myarray[$rowcount]["title"].'|<br />'; $rowcount++; } ?> Alright, this has been puzzling me for a while now and I think it's time I seek help before my brain turns to mush. I've been modifying a PHP text based game called Legend of the Green Dragon to add more functionality, etc. One of the things I want to add is the ability to add levels higher then 15. The original array looks like this: $exparray = array(1=>100,2=>400,3=>1002,4=>1912,5=>3140,6=>4707, 7=>6641,8=>8985, 9=>11795,10=>15143,11=>19121,12=>23840, 13=>29437,14=>36071,15=>43930, ); Now, I could just hardcode each level, but noo, I want to be able to do it from a module type thing from the admin panel (which I've already gotten that working gratefully) so I've tried writing a few different scripts to take the information from the MySQL database and turn it into an array like above but I've gotten completely lost. This is what I currently have: $expsql = "SELECT * FROM " . db_prefix("myolevels"); $numrows = mysql_num_rows($expsql); for ($i = 1; $i <= $numrows; $i++) { $expresult = mysql_query($expsql); while ($rows = mysql_fetch_assoc($expresult)) { $exparray = array($i=>$rows['myoexpreq']); } } Although when I call the array, it always returns null for the myoexpreq causing your master to look for you all the time (forcing level up when it shouldn't be). Is there any way to create an array like the first with SQL? Thought this might help as well: PHP Warning: "Variable passed to each() is not an array or object" in /home/ileetcom/public_html/logd/lib/experience.php at 35. Call Stack: 2: each(NULL) called from /home/ileetcom/public_html/logd/lib/experience.php on line 35 3: exp_for_next_level(16, "0") called from /home/ileetcom/public_html/logd/village.php on line 131 |