Been hammering away at this for weeks. I think it's actually simple...but I just can't get it.
I want to pull info from the database and use it in divs later on in my html. I've been successful in other cases looping through and displaying the full results of a query in the past. In this case I just want to echo a specific team name or team ID in my html. All the data gets used...so I'd like to just have one query, but the data gets used in different divs in different places...so being able to echo specific parts of the query is important.
The query I have returns 10 rows and 4 columns.
<?php
$playoffs = mysqli_query($con, "SELECT playoffseed, ttName, teamID, ttsUID
FROM standings
WHERE ttsUID = $season_view
AND playoffseed > 0
ORDER BY playoffseed
LIMIT 10");
?>
Now, I think I've learned that this query returns a result set and not an array. It needs to be processed using some php to turn it into an array. Correct? And given the fact it's got multiple columns and rows once it is processed it would be a multidimensionsal array. Ok I've scoured this site and google...tried many ideas using mysqli_fetch_array, mysqlifetch_assoc, and any other mysqli_fetch that I'd come across.
In my mind anyway, after processing the query with some php I'm thinking the array would look like this...
playoffseed ttName teamID ttsUID
1 Buffalo 13 1993
2 Miami 19 1993
3 Detroit 8 1993
4 Denver 3 1993
5 Chicago 26 1993
...and so on. 10 rows total
After that I'd like to be able to call on (echo) various items from the above in my html. Let's say in one div I'd like to be able to echo the ttName "Detroit" and then to call and image associated with the teamID I'd like to be able to call that too (it'd be something like this in my html...
IMG SRC="../images/<?php echo "teamID" ?>.jpeg
...where in this case Detroits image is "8.jpg").
How can that be done? How do I correctly fetch the array and then echo a specific item of data from it?
I'm thinking if the above is an associated array I'd be able to echo something like this to return "Detroit"...
echo $playoffs[3]['ttName'];
[3] = 3rd row and ['ttName'] = column. no? I realize that [3] would actually refer to the 4th row if it's actually pointing to rows that start with zero and not one, but I'd like to be able to call on the item by using the "playoffseed" identifier, but I'm just too confused at this point.
I already feel I've made this question too confusing in itself. Thanks a ton for your help.
kevinabelita:
this could shed some light to you us2.php.net//manual/en/mysqli-result.fetch-assoc.php
OP:
been there a 100 times. i'm just not getting something. long story short in case the above is too much....take query and process it with php to create an array...then echo....say..."detroit" from that array
And still didn't notice this simple way?
while ($row = mysqli_fetch_assoc($playoffs)) {
$values[]=$row;
echo $row["ttName"];
//print_r($row); // if you want to see all the data this row contains
}
mysqli_free_result($result);
}
Now you can use $values with an index like you wish. i.e.
echo $values[0]["ttName"];
Edit
I mistakenly was trying to execute the query again. Fixed in the code above. Now for a little explanation of what you are confused with. Here's how the flow goes roughly
Connect to the database
Prepare/Run a query (mysqli_query in this case)
Store the result resource In a variable ($playoffs in this case)
Either fetch all rows from that result all together or fetch one by one. In this case mysqli_fetch_assoc in a loop is fetching the rows one by one till all of the result set has been fetched.
Provide that fetched row as an array for you to use, in that case its stored in $row variable.
Related
I have 18 rows in one of my tables with several columns. I would like to extract the data from several different non-sequential rows and echo them individually on different parts of my page.
For example, let's say I wanted to pick records 5, 9 and 13 from column_1 and echo them to the page in different places. How would I accomplish this? Would I need to perform one query each to retrieve these unique fields? Here is my code so far:
// $database connect code, blah blah...
$sql = "SELECT page_id FROM pages WHERE (not sure if something should go here)";
$query = mysqli_query($connect, $query);
while ($row = mysqli_fetch_array($query)){
maybe some code here, not sure...
};
Doing so with ALL of the records in a specific column is easy using a while loop, but that's not what I'm after. I thought there may have been a way to cherry pick the specific row with an associative array like $fetchRow['row']['row_number'], but that doesn't appear to work. Performing one query for each unique instance seems awfully inefficient.
I'm familiar with how to retrieve things from the database and display them on the page. I'm intermediate level, but this has gotten me stumped.
Any ideas?
Thanks.
You'll need an IN clause.
$sql = "SELECT page_id FROM pages WHERE column_1 IN (5, 9, 13)";
Or if you'd rather do it with a PHP array, something like this:
$cols = array(5,9,13);
$in_cols = implode(',', $cols);
$sql = "SELECT page_id FROM pages WHERE column_1 IN ({$in_cols}})";
If you're going to use #2, make sure you properly sanitize/prepare the statement before executing it.
I think what you're looking for is data_seek
However, since you only have 18 rows... I would store all the result set in an array and use this array to echo the rows elements I want on the page. That way you do not have the overhead of typing the supplementary code (the best code is no code) and having to retrieve the specific rows you want. Furthermore, would you ever want to retrieve other records, there would be no need to modify your query.
I'm making a car part system, to store all the parts inside mysql and then search for them.
Part adding goes like this:
you select up to 280 parts and add all the car info, then all the parts are serialized and put into mysql along with all the car info in a single row.
(for this example I'll say that my current database has 1000 cars and all of those cars have 280 parts selected)
The problem is that when I have 1000 cars with each of them having 280 parts, php and mysql starts getting slow and takes a lot of time to load the data, because the number of parts is 1000*280=280 000.
I use foreach on all of the cars and then put each part into another array.
The final array has 280 000 items and then I filter it by the selected parts in the search, so out of 28 000 parts it may have only have to print like 12 500 parts (if someone is searching for 50 different parts at the same time and 250 cars have that part).
Example database: http://pastebin.com/aXrpgeBP
$q=mysql_query("SELECT `id`,`brand`,`model`,`specification`,`year`,`fueltype`,`capacity`,`parts`,`parts_num` FROM `warehouse`");
while($r=mysql_fetch_assoc($q)){
$partai=unserialize($r['parts']);
unset($r['parts']); //unsetting unserialized parts so the whole car parts won't be passed into the final parts-only array
foreach($partai as $part){
$r['part']=$parttree[$part]; //$parttree is an array with all the part names and $part is the part id - so this returns the part name by it's id.
$r['part_id']=$part; // saves the part id for later filtering selected by the search
$final[]=$r;
}
}
$selectedparts=explode('|', substr($_GET['selected'], 0,strlen($_GET['selected'])-1)); //exploding selected part ids from data sent by jquery into an array
foreach($final as $f){
if(in_array($f['part_id'], $selectedparts)){
$show[]=$f; //filtering only the parts that need to be shown
}
}
echo json_encode($show);
This is the code I use to all the cars parts into arrays and the send it as json to the browser.
I'm not working on the pagination at the moment, but I'll be adding it later to show only 10 parts.
Could solution be to index all the parts into a different table once 24h(because new parts will be added daily) and then just stressing mysql more than php? Because php is doing all the hard work now.
Or using something like memcached to store the final unfiltered array once 24h and then just filter the parts that need to be shown with php?
These are the options I considered, but I know there must be a better way to solve this.
Yes, you should definitely put more emphasis on MySQL. Don't serialize the parts for each car into a single row of a single column. That's terribly inefficient.
Instead, make yourself a parts table, with columns for the various data items that describe each part.
part_id an autoincrement item.
car_id which car is this a part of
partnumber the part's external part number (barcode number?)
etc
Then, use JOIN operations.
Also, why don't you use a WHERE clause in your SELECT statement, to retrieve just the car you want?
Edit
If you're looking for a part, you definitely want a separate parts table. Then you can do a SQL search something like this.
SELECT w.id, w.model, w.specification, w.year, w.fueltype,
p.partnumber
FROM warehouse w
JOIN parts p ON (w.id = p.car_id)
WHERE p.partnumber = 'whatever-part-number-you-want'
This will take milliseconds, even if you have 100K cars in your system, if you index it right.
Your query should be something like:
<?php
$selectedparts=explode('|', substr($_GET['selected'], 0,strlen($_GET['selected'])-1)); //exploding selected part ids from data sent by jquery into an array
$where = ' id < 0 ';
foreach ($selectedparts AS $a){
$where .= " OR `parts` like '%".$a."%'";
}
$query = "SELECT * FROM `warehouse` WHERE ".$where." ORDER BY `id` ASC";//this is your query
//.... rest of your code
?>
Yes, look into has many relationships a car has many parts.
http://net.tutsplus.com/tutorials/databases/sql-for-beginners-part-3-database-relationships/
Then you can use an inner join to get the specified parts. You can do a where clause to match the specific partIds to filter out unwanted parts or cars.
Ive got a database that Im trying to pull data from (the name of each unique identifier and also how many times it appears in the database) by using this query:
$query = "SELECT Dcol, COUNT(*) FROM dtest GROUP BY Dcol";
and then using this to actually print the data out:
while($result->fetch_row()){
$row = $result->fetch_array(MYSQLI_NUM);
printf("<strong>%s</strong> : <i>%s</i><br />",$row[0],$row[1]);
}
and it works great except for the fact that it only gets 2 of the 4 unique items from the Dcol column. I've tested it by just putting everything that the fetch_row() returns into an array and then using print_r and when I do that it actually shows all 4 with the correct number of times it was used, but when I try to print it using the above statement I get 2 of the 4 (the second and fourth one, if that helps at all)
Can anyone tell me why this would only be giving two of the four unique items?
The 'fetch_row' command is getting the first row - then you ask for the 2nd row with the 'fetch_array' command. So you're only seeing 2 and 4 as a result.
I'm learning currently php/mysql and I'm confused about this bit.
After some heads scratching I have figured out that mysql_fetch_array remembers which row it last accessed and accesses the next one. (I was originally trying to work out how the code was communicating this to it in example code)
so for database:
parent | job
-------+-------------
mom | receptionist
-------+-------------
dad | taxi driver
the code
mysql_fetch_array($result)[job]
returns 'receptionist' the first time and 'taxi driver' the second.
Where/how is it keeping track of this?
What happens if I don't want to access them in order?
thanks
internal implementation in PHP. Don't try to figure it out ;)
if you want a different order, then specify it in your database query.
Where/how is it keeping track of this?
The mySQL server has an internal result pointer. In some databases / wrappers / libraries you can rewind that pointer, but as far as I know, this is not possible in the mysql_* library of functions.
What happens if I don't want to access them in order?
You have to access them in some order. The only alternative to that is to fetch all rows into an array: Then you can access each row randomly.
If you want to change the order of records, do that in the query using the ORDER clause.
Some database wrappers like PDO have a fetchAll() method that does exactly that. For large result sets, this can be memory intensive and break the script's memory limit, which is why it's usually not done this way.
There is another way to attack this question.
If you want to know how YOU TOO can make functions that do what this one does. Here is how:
<?php
function count_off()
{
static $count = 1;
echo $count++;
}
count_off();
count_off();
count_off();
count_off();
count_off();
?>
the above will output 12345
I should mention. You shouldn't do this without a very good reason. It is SUPER hard to trace when debugging.
If you want to access them in a different order, use an ORDER BY clause in your SQL to change the order that the results are retrieved from the database.
The result of mysql_fetch_array is always the next result/row of the query (first the first row off course)
Intern it will keep a pointer how for it has fetched.
If you want to get them in an alternate order, you have to define it in the query.
Like said the result will always be in the order specified by the query (implicit or explicit)
If you wrote typical looking code like this:
$result = mysql_query("SELECT parent, job FROM table");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo $row['parent'] . ' - ' . $row['job'];
}
Each time mysql_fetch_array() is called, if there is another row in the result, it will return the row as an associative array into the $row variable. Otherwise, it will return false, and the execution of the while loop will end.
Also, because you didn't specify an ORDER BY clause, it defaults to returning rows in the order they were inserted into the table.
The mysql_fetch_array() function grabs one row from the database, in the order that MySQL returns it from the query you gave.
To obtain all the rows, you can put the function in a loop.
while($row = mysql_fetch_array($result)) {
echo $row["job"];
}
This will output:
receptionist
taxi driver
You can change the order by using the sql term order by, which can alphabetically or numerically order your results by a certain column
select * from parent order by job
The above query will order the results alphabetically by the parent job field (results closer to A will come first in the mysql_fetch_*
I got some help with gettin the number of rows returned from mysql, and it works fine...
BUT, how do I get the number of rows with a certain field value?
Do I have to make a new Mysql search query?
Here is the code where I query mysql and display in a table using fetch_array... Also, Im using mysql_num_rows to get number of rows.
So how do I get number of rows with certain field value also?
$qry_result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_num_rows($qry_result);
while($row = mysql_fetch_array($qry_result))
Thanks for all help
OBSERVE: Im trying to avoid using another SELECT WHERE clause...
Is there a way to do what I want withouth another search?
In your query, you can use the where clause. (select * from table where column1 = 'value')
Another option would be to have a counter variable that you increment in your while loop:
$counter = 0;
while($row = mysql_fetch_array($qry_result))
{
if($row[0] == "value")
$counter++;
}
After you have this counter, reset the result set using mysql_data_seek($qry_result, 0); and then continue with your original while loop.
There are several ways to reach this, either run additional queries against MySQL or use programm logic to calculate what you need while iterating over the array.
Fetching the number of rows from MySQL is a task that has several solutions as well. You could blindly call SELECT count(*) FROM table WHERE foo = bar, or use the more advanced SQL_CALC_FOUND_ROWS variable of the database.
If you could explain yourself better, I would be glad to provide a good solution!
OBSERVE: Im trying to avoid using another SELECT WHERE clause... Is there a way to do what I want withouth another search?
I'm curious why you don't want to use another SELECT WHERE clause?
From what I interpret of your question, you are asking to have the number of rows of a given query AND, a count of unique variables?
ex:
NAME AGE
Joe 15
Simon 13
Simon 16
Joe 21
Mary 15
Joe 28
Your row count would be 6 and your count (that you are requesting) would be:
Joe x 3
Simon x 2
Mary x 1
If that is what you are asking, why not use 2 queries, 1 for your set of data, and another query where you GROUP BY 'name' and return only UNIQUE 'name' results? That would get you a count of your "certain fields".
Then again correct me if I miunderstood your question.