PHP - Trying To Limit Data That Comes Back From Mysql Query Into Array
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 ) ) Similar TutorialsHi. I'm trying to make a sort of a forum, and this is the part of the code that needs to be changed, only I don't know how. Code: [Select] mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $sql="SELECT * FROM $tbl_name ORDER BY id DESC"; // OREDER BY id DESC is order result by descending $result=mysql_query($sql); ?> <table width='50%' border="0" align="center" cellpadding="3" cellspacing="1"> <?php $limit=10; $page=0; $numrows = mysql_num_rows($result); $pages = intval($numrows/$limit); if ($numrows % $limit) { $pages++;} $current = ($page/$limit) + 1; if (($pages < 1) || ($pages == 0)) { $total = 1;} else { $total = $pages;} $result = mysql_query("SELECT * FROM $tbl_name ORDER BY id DESC LIMIT $page,$limit"); while($rows=mysql_fetch_array($result)){?> <tr><td><font size="+2"><a href="view_topic.php?id=<? echo $rows['id']; ?>"><? echo $rows['topic']; ?></a><BR></font></td> <td width='0*'><? echo $rows['datetime']; ?></td></tr> <tr><td><? echo substr($rows['detail'], 0, 250)."..."; ?> <a href="view_topic.php?id=<? echo $rows['id']; ?>"><? echo "Citeste mai mult";} ?></a> </td></tr> <tr><tr><td> <? if ($page != 0) { // Don't show back link if current page is first page. $back_page = $page - $limit; echo("<a href=\"$PHP_SELF?query=$query&page=$back_page&limit=$limit\">back</a> \n");} for ($i=1; $i <= $pages; $i++) // loop through each page and give link to it. { $ppage = $limit*($i - 1); if ($ppage == $page){ echo("<b>$i</b>\n");} // If current page don't give link, just text. else{ echo("<a href=\"$PHP_SELF?query=$query&page=$ppage&limit=$limit\">$i</a> \n");} } if (!((($page+$limit) / $limit) >= $pages) && $pages != 1) { // If last page don't give next link. $next_page = $page + $limit; echo(" <a href=\"$PHP_SELF?query=$query&page=$next_page&limit=$limit\">next</a>");} ?> </td></tr></tr><?php mysql_close(); ?> </table> I made a database with 4 fields and 11 entries. The script shows the last 10 entries just as it should, but when I click on the 'next' button, nothing happens (it should show the first entry, but it just refreshes the page, and still the last 10 entries/1st page are shown). I think it has something to do with the link, but I can't figure out what exactly. Can someone help, or at least give me a hint? Thanks in advance. Bye. Lets start out by saying I'm a nube to sql/php things so I am learning as I go. I try to read all that I can before I post, and only post when I cant figure it out on my own. That being said. What I want to do in simplest terms is be able to assign a variable to each item in an sql table. So say I have an mysql table that has ID, username, fontcolor. I want to be able to pull those out so say.... while($row = mysql_fetch_array($users)) { $username[$i] = $row[username]; $fontcolor[$i] = $row[fontcolor]; } Then on the page I can just call to $username[1] type thing. I have tried mixing this several different ways with for and while and I keep getting errors on the page. I realize the code isn't showing everything but its just there to show you the idea of what I'm trying to do. I just want it to generate a list(array) that will make it easier for me to call back just the items I need on parts of the page with out having to have extra coding everywhere. Thanks in advance. Jim 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 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++; } Hi 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 This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=322237.0 Hello guys, Got a question here.. If I have a database table called features with the following columns with example f_id | f_name | f_status 1 | deck | 1 2 | Fireplace | 1 3 | Alarm | 1 I have another table another table called ads that has a column called features and it has the following 1,2,3 (for example) I want to be able to query the db and display all the f_name. Here is what I have so far but it's not working and need some help Code: [Select] // Query the ads table $result3 = mysql_query("SELECT * FROM ads WHERE ad_id='$id2'") or die(mysql_error()); $row3 = mysql_fetch_array( $result3 ); $features = $row3['features']; echo'This is the features ' . $features .''; $feature2 = explode(",", $features); print_r($feature2); echo "test" . $feature2[0]; // piece1 echo $feature2[1]; // piece2 $result = mysql_query("SELECT * FROM features WHERE f_id=$feature2[1]") or die("Sql error : " . mysql_error()); while($row = mysql_fetch_assoc ($result)){ $f_name=$row["f_name"]; echo $f_name; } Hey guys, New to the forum and a newer user of PHP / MySQL. I am having trouble with some code I've written up. I don't seem to get any errors when running it, but it's not updating my database the way that it should. hopefully a simple fix. I am thinking that it must be on the MySQL side of things. Couple of things to start. My html form is comprised completely of drop down list inputs. I'm the only user so I thought this would be the easiest approach. Because of that I've made my PHP as follows: Code: [Select] <?php $season = $_POST['season']; $month = $_POST['month']; $day = $_POST['day']; $year = $_POST['year']; $time = $_POST['time']; $event = $_POST['event']; $game = $_POST['game']; $buyin = $_POST['buyin']; $connect = mysql_connect('localhost','root','') or die('can not connect'); if ($connect) { echo "connected to database"; } $db = mysql_select_db('dpl') or die('can not find database'); if ($db) { echo "DPL Selected"; } $query = sprintf("INSERT INTO events (season , month , day , year , time , event , game , buyin) VALUES ('%s' , '%s' , '%s' , '%s' , '%s' , '%s' , '%s' , '%s')", $season , $month , $day , $year , $time , $event , $game , $buyin ); if ($query) { echo "Your event has been added"; } ?> My connection is working, my database is selected and I'm even now getting confirmation that my query is working, but when i go to check my database there are no entries in it? any thoughts? I've tried the drop down variables as both VARCHAR and TEXT inputs in MySQL, but I can't seem to get it to work. Any help is greatly appreciated. Hello Guys, I have a question I have the following query $result3 = mysql_query("SELECT * FROM table1 WHERE ad_id='$id2'") or die(mysql_error()); $row3 = mysql_fetch_array( $result3 ); // Grab all the var $features = $row3['features']; I am turning it into an array (comma separated) $feature2 = explode(",", $features); print_r($feature2); ) The result is like so Array ( [0] => 5 [1] => 9 [2] => 13 I want to query the features for just the ids (F_name) are for the features . This query will show all.. I would like to just display the f_name values from the array query. // build and execute the query $sql = "SELECT * FROM features"; $result = mysql_query($sql); // iterate through the results while ($row = mysql_fetch_array($result)) { echo $row['f_name']; echo "<br />"; } Please Advise.. Thanks, Dan I have tried many ways of storing an array of data that comes from a multiple selection form into a mysql table, including serialization. I am currently trying to do it by forming a string, and using the string in the insert query, but keep getting errors, or just nothing happening. I am not sure what I am doing wrong. Code: [Select] $categoryString = array(); if ($categoryArray){ foreach ($categoryArray as $category){ $categoryString[] = $category.'<br />';} } $categoryquery= "INSERT INTO categoryname VALUES('$categoryString')"; mysql_query($categoryquery); Thank you for your time as always. when i run the below code i get an error...
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in...
but when i take out the h>0 then there is no errors in the code. in table users, i need all columns in the array. How to get h>0 working?
$query = "SELECT * FROM users WHERE h>0 ORDER BY id"; $result = mysqli_query($link, $query); $data = array(); while($row1 = mysqli_fetch_array($result)) { $data[] = $row1; } print_r($data); Edited by kalster, 27 October 2014 - 07:38 PM. Hi all, I have the following code that queries a MySQL database and outputs results on-screen. Code: [Select] $result= mysql_query (" SELECT email,firstname,lastname FROM tablename WHERE ID IN('".$IDs."') "); if (!$result) {die('Error: Could not search database. ' );} while($row = mysql_fetch_assoc($result)) { echo $row['firstname']," ",$row['lastname'],"<br />"; $emails[]=$row['email']; } var_dump($emails); var_dump($IDs); However, the two var_dump's output the following (in the case of 2 results for the query): array(6) { => string(14) "email1@email.com" [1]=> string(23) "email2@email.com" [2]=> string(14) "email1@email.com" [3]=> string(23) "email2@email.com" [4]=> string(14) "email1@email.com" [5]=> string(23) "email2@email.com" } string(67) "9543219aa68ffa1d434dc8530f23fe48','d4384b2b493867706b0bcedda012ed48" ($IDs is an imploded array) Even though the MySQL table only contains one email per ID, both emails are listed 3 times in $emails, instead of just once. Can anyone see why this is? I'm stuck. Thanks! I have a MySQL table with a list of albums and there is a field called "views" with the number of views each album has received. I'm looking to generate an array of all the albums in the table and sort the array by the number of views (descending). I have a list of functions defined in a ContentController.php file. I created a new function called build_albumlist, which I've pasted below. The function "get_ip_log" already exists and works, and I used it as a template to create the "build_albumlist" function: public function build_albumlist(){ return $this->select_raw("SELECT * FROM albums WHERE deleted = '0' ORDER BY views DESC",array(),'all'); } public function get_ip_log(){ return $this->select_raw("SELECT * FROM sessions ORDER BY ID DESC",array(),'all'); } When I use the function, I get this warning: Warning: mysql_real_escape_string() expects parameter 1 to be string, array given inC:\xampp\htdocs\Controllers\DBController.php on line 10 [font=cabin, 'trebuchet ms', helvetica, arial, sans-serif]The "select_raw" function that I used in "build_albumlist" is defined in the DBController.php file, and is defined as below:[/font] private function clean_array($params){ $final=array(); foreach($params as $param){ $final[]=mysql_real_escape_string($param); } return $final; } public function select_raw($query,$params,$type=''){ $query=str_replace("?","'%s'",$query); $final_query= call_user_func_array('sprintf', array_merge((array)$query, $this->clean_array($params))); if($type==''){ $result=mysql_query($final_query) or die(mysql_error()); return mysql_fetch_assoc($result); } elseif($type=='all'){ $result=mysql_query($final_query) or die(mysql_error()); $final=array(); while($row=mysql_fetch_assoc($result)){ $final[]=$row; } return $final; } Does anyone know why the "build_albumlist" function is generating this warning, while the "get_ip_log" is not? Any help would be great, as I am obviously pretty new to this. I am in the process of writing code for a dynamic form. I have the part of the form written for information to be entered. I am now trying to write code for the modification of the information in the table. I know that I want to get the table data my doing a MySql Select and putting that information into an array. I am not very familiar with arrays and have spent some time looking for a solution online with no solution. When I print_r the results I get what I want but when I do anything else I get Array. What I am actually looking to do is make it so that the table data is in another variable this is the section of code that I am working with. Code: [Select] $mod_form = "<form name='insert_table' id='insert_table' action='ad_add.php' method='post' enctype='multipart/form-data'> <fieldset> <legend>table information</legend> <input name='table' TYPE='hidden' VALUE='" . $table . "' />"; $mod_sql = "SELECT * FROM $table WHERE id = '$id'"; $mod_sql_result = mysql_query($mod_sql); $allowed_ext = array('jpg', 'jpeg', 'png', 'gif'); $input_array = array(); while ($row = mysql_fetch_array($mod_sql_result, MYSQL_NUM)) { $input_array[] = $row; } foreach ($input_array as $input => $data) { print_r($data); } while ($i < mysql_num_fields($mod_sql_result)) { $header = str_replace("_", " ", (mysql_field_name($mod_sql_result, $i))); $name = mysql_field_name($mod_sql_result, $i); (mysql_field_name($mod_sql_result, $i) == 'image' ? $mod_form .= "<p>" . $header . ": <input name='" . $name . "' id='" . $name . "' type='file' /></p>" : $mod_form .= "<p>" . $header . ": <input name='" . $name . "' id='" . $name . "' type='text' value='" . $input . "'/></p>"); $i++; } $mod_form .= " <p> <input type='submit' name='submit_mod' id='submit_mod' /> </p> </fieldset> </form> "; echo $mod_form; Hi All, First time posting here. I've googled the problem, but can't seem to find a response that's the same. All I want to do is have a list of id numbers and for each id number in the array, submit a MySQL query to retrieve information relating to the id number. When I execute the code below however, I end up with only the last item in the array being printed in the echo statement. Any clues? Thanks, Code: [Select] // get array of ids $ids = getIDs($ids); // loop through input list foreach ($ids as &$id) { getVarDetails($id); } function getVarDetails($local) { $con = mysql_connect('localhost:3306', 'root', '********'); if (!$con) { die('Could not connect: ' . mysql_error()); } // set database as Ensembl mysql_select_db("Ensembl", $con); $result = mysql_query("SELECT * FROM variations WHERE name = '$local' LIMIT 1"); $row = mysql_fetch_array($result) while($row = mysql_fetch_array($result)) { echo $row['name'] . " " . $row['id']; echo "<br />"; } // close connection mysql_close($con); } Hi all, I have the following MySQL insert query: Code: [Select] $insert= mysql_query ("INSERT INTO tablename (column1,`".$EXPfields."`) VALUES ('$something','".$EXPvalues."')"); where $EXPfields is an array of table-field-names and $EXPvalues is an array of table-field-values. Now I want to write an equivalent query, but using UPDATE instead of INSERT INTO, but I don't want to write out all the field names/values separately, but again want to use $EXPfields and $EXPvalues. So something like this: Code: [Select] $update = mysql_query ("UPDATE tablename SET (column1,`".$EXPfields."`) = ('$something','".$EXPvalues."') WHERE .... "); Is this possible? If so, what is the proper syntax? Thanks! I'm working on a store locator style program. I first get and sort all zip codes based on a their distance to an original location. I then use that zip code array to find all stores in the mysql database, but when I get the results, they're no longer arranged by distance from the original location.. and I can't just sort them ascending or descending based on their zip codes because that doesn't sort them correctly either. So I need to sort the data I get from the mysql database based on their "zip_code" column and in order from the $zip array.. Here's an example of what $zip looks like.. the zip code is the key and the distance from the original zip is the value [meaning the first key is the $originalZip]: Array ( [70601] => 0 [70616] => 1.12 [70629] => 1.2 [70612] => 1.24 [70602] => 1.31 [70615] => 1.88 [70609] => 3.41 [70605] => 4.4 [70669] => 4.62 [70606] => 4.9 [70611] => 7.23 [70607] => 9.68 [70663] => 9.74 ) and then I create the $WHERE variable by each key supplied: $WHERE = "WHERE zip_code='$originalZip'"; foreach ($zip as $key => $value) { if ($key == $originalZip) {} else { $WHERE .= " OR zip_code='$key'"; } } } Then I do the query [with a paginator]: $query = query("SELECT * FROM " . $db['prefix'] . "stores $WHERE LIMIT $from, $maxResults"); but when I print the data, it doesn't keep the correct sorting format.. if (mysql_num_rows($query) > 0) { for ($i = 0; $i<mysql_num_rows($query); $i++) { $storeData = mysql_fetch_array($query, MYSQL_ASSOC); // print store information here such as $storeData['name'] $storeData['address'] $storeData['zip_code'] } } Is there an easy way to sort the mysql results based on the $zip array? Im wondering if someone can shed some light on possibly the best way to do this. I currently have a website which recieves 26000-37000 visits a month. The host got on my case about to many MySql connections and with help from someone here decided a cache system was best. the cache system is now in place and only updates if the cached file is older than 5 days. I am still recieving high connections to my database and wonder if it is spam as i have a search box. the search box once filled in redirects to a page which queries the database for the keyword and displays results and because it was just selecting and not inserting into database i didnt go for the captcha. this is why i suspect spam, I have thought about limiting the amount of search queries per time limit by ip but I am unsure of how to tackle this and if it will help against spam bots? a google search has only found an answer which stores every visitors ip in a database and keeps count there which I cant see the benefit as it is creating more work for the DB. I have thought maybe creating a session variable that increments with every search and when searching checks this value but I am not to sure if this would help as it would be down to cookie settings. can anyone shed some light on a possible solution to this. I am not expecting you to write this for me but for now just to help with the best way to tackle the problem. Thank you for your time. Hi there I have a MySQL database table that has multiple records which look like (1, Which of these are your favorite color(s)?, Red||Blue||Orange||Green, question-type1 ) I have written some PHP code in extracting that data into a HTML form. (The above data looks like a question with multiple options (radio buttons/checkboxes) below it). Below is what I'm trying to achieve: When the action is Submit: store the question number, user responses of the options , time stamp and user name into a new database table. I came to know that passing arrays will do the job, but I got stuck in the middle. Please see the attached documents that has the code. TIA [attachment deleted by admin] |