"how many search results from mysql" help - php

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.

Related

Needing only 1 row from PHP MySQL database

I'm sure I've done this in the past, but it's a few years ago and I don't remember how it's done and the online tutorials aren't helping.
I have a MySQL database. It has 1 table in it called 'data'. In the 'data' table, there are about 15,000 rows, and 31 columns. I need to extract the data from only 1 of these rows, based on a lookup referencing the string in column 1. When the mysql query finds the correct row, I need every single item read into variables that I can show on my page.
I believe this line is the problem:
$sql = "SELECT Mark,Manufacturer,Model FROM data";
Could someone please let me know what it needs to be changed to, to get the desired result? TIA! :)
you can set options of select query
$sql = "SELECT Mark,Manufacturer,Model FROM data WHERE Model (or manufacturer,mark) = 'some text'";
As my colleges have Explained "where' is your friend!
So you can always query as follows :
Select * from Data
Where column_1 = 'Your Desired String'
Alternatively you could use
Select Discinct Limit 1 Mark,Manufacturer,Model FROM data
Order By Mark Asc

echo specific item from multidimensional array

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.

MySQL - INSERT into only if it's weekend

I'm trying to populate a table from another one only if the day is a weekend, but when i try to fetch my results into a php array, it says that i'm fetching a non-object, and this error began when i added my where clause that tries to pick only weekend days. If someone could take a look and correct me, my code is:
EDITed
$con->query("INSERT INTO eventos_dias SELECT DATE(inicio_periodo),'1','0','0','0' FROM eleva WHERE HOUR(inicio_periodo) BETWEEN 0 AND 6 AND WEEKDAY('inicio_periodo') BETWEEN 5 AND 6")
$query=$con->query("SELECT Data, Sum(0h_6h) as sum0_6,Sum(6h_12h),Sum(12h_18h),Sum(18h_24h) FROM evnetos_dias
GROUP BY Data
ORDER BY Data ASC")
while($row->$query->fetch(PDO::FETCH_ASSOC)) //this line contains the error
{
$dados0_6_fds[] = $row['sum0_6'];
}
Ideas are welcome too!
You can't have a WHERE in an INSERT query. Do your date filtering at the PHP level and simply don't run the query at all if it's the weekend:
if ($is_not_weekend);
$con->query('INSERT ...');
}
INSERT INTO eventos_dias(put the columns in here)
SELECT DATE(inicio_periodo),'1','0','0','0'
FROM eleva
WHERE HOUR(inicio_periodo) BETWEEN 0 AND 6
AND WEEKDAY('inicio_periodo') BETWEEN 5 AND 6
Always a good idea to develop your queries with a suitable tool until (and possible still after) you get the hang of sql.
are you sure that
while($row->$query->fetch(PDO::FETCH_ASSOC))
is correct? should it not be
while($row = $query->fetch(PDO::FETCH_ASSOC))
and for clarification (as I can't comment on anything but my own posts) that insert statement works fine, as the where clause is for the select.

Can you help me understand this php script

I'm a fairly newbie php coder, got this php code in a tutorial to create a randomly generated quote, but I don't fully understand the code
IN particular, I don't understand
a) line 4 -- where does the "rows" come from. Is that a name made up on the spot. Could it just as easily have been called "ferrari"
b) line 9 -- where does "storedtext" come from? is it just made up on the spot?
c) based on the code, do you have an idea what the database is supposed to look like. Would it just be a database called "text" with a table called "quotables" in it?
<?
//
// count() gets the number of rows from database text--
//it assigns a number to rowcount
1 $rowcount = mysql_query("select count() as rows from text");
// don't understand what exactly is happening here, where did "rows" come from
2 while ($row = mysql_fetch_assoc($rowcount))
3 {
4 $max = $row["rows"];
5 }
// Selects an item's index at random
6 $rand = rand(1,$max)-1;
//there is a database table called "quotables?" taking one random row
7 $result = mysql_query("select from quotables limit $rand, 1");
8 $row = mysql_fetch_array($result);
//where does "storedText" come from?????
9 $randomOutput = $row['storedText'];
10 echo '<p>' . $randomOutput . '</p>';
11 ?>
where does the "rows" come from?
It is a name assigned to a value in the SQL query select count() as rows from text.
where does "storedtext" come from?
It seems to be the name of a field in the quotables table.
based on the code, do you have an idea what the database is supposed to look like. Would it just be a database called "text" with a table called "quotables" in it?
No. We cannot say anything about the database name. But this database contains the tables text and quotables where the latter has at least the field storedText.
a) Yes.
b) It must be a column in the database. In line 7, it's pulling all columns in the database, but isn't specific about it's names
c) No, you could print_r($row) to see the table structure though (will print out the array, showing all columns). You should also have access to the db (to make this work, you'll need the db and tables set up), so however you mysql_connect() and mysql_select_db() will tell you the name of the host/db.
A) rows is the alias given to the count() function in the mysql query in line 1. If you changed rows in line one to ferrari then changed rows in line 4 to ferrari then it would still work.
B) stored text comes from the second mysql query on line 7. This will be the name of a column from within that table.
C) Based on the code you have given I can tell you that you have a database which I do not know the name of and that database has two tables one called text and the other quotables I can tell you that quotables has one column called storedText.
a) rows came from sql query "select count() as rows from text"
b) I think there "*" in line 7 because there is no column specified, so if * is there then its selecting all the columns in that table and "storedText" is one column in it
c) text,quotables both are tables
a) rows comes from the SQL query:
$rowcount = mysql_query("select count() as rows from text");
It is the name given to the count() column.
b) storedText is a column in the quotables table, probably with the quote in it.
What the script does is, get a row count from the text table.
Get a random number in the range of 1 to $max.
Get the corresponding quote from the quotables table.
The SQL doesn't tell us anything except that quotables is a table and storedText is a column in it. The names in strings show up in the SELECT statement and come into existance when it completes.
"rows" come from mysql table. This is the name of column. For instance, if you have table with 2 columns, and one of them named like "price" you should use $var['price'] after using mysql_fetch_assoc to use it.
'storedText' the same.
ANS - 1
in while loop, we have assigned value to $row...
ANS - 2
If you have looked code carefully, on line no 8, you have again assigned value to $row.
in line no 8 mysql_fetch_array($result) will fetch all the values for 1st row in array format.
there must be one column in "quotables" table named "storedText" so that it is coming in the $row['storedText'].
you should refer php manual toi understand mysql_fetch_array and mysql_fetch_assoc functions..
refer this url : http://be.php.net/manual/en/book.pdo.php
Line 2 is relevant to a)
while ($row = mysql_fetch_assoc($rowcount))
the while-construct will repeat as long as the expression inside the parentheses evaluates to a true-ish value. In PHP; an assignment is also an expression, which evaluates to the value being assigned, i.e. $row. Before each iteration, the function is executed and tries to retrieve the next row from the database. When it fails, it will return false instead of a row, which then in turn make the loop end, because the assignment-expression will evaluate to false, which is the terminating condition for the while-statement.
b) line 9 -- where does "storedtext" come from? is it just made up on the spot?
It comes from a randomly fetched result from the database. It's the value of one column.
c) based on the code, do you have an idea what the database is supposed to look like. Would it just be a database called "text" with a table called "quotables" in it?
We only know that the database has at least two tables text and quotables, the latter of which has at least one column storedText.
What it does
It tries fetching a random quote. However, the logic is not sound and will most likely not work in all instances.
Why is it wrong?
Basically, it assumed that for each row in text, there is exactly one entry in quoteables. If that was so, you would not need two tables in the first place. Because of this, I assume that quoteables can contain any number of rows, possibly even less, in which case you would sometimes not get a single result from the query. This would have your query fail and your script, because you try to access "false["storedText"] so to speak.
A
$rowcount = mysql_query("select count() as rows from text");
// the $rowcount is an array, the lines below get the values (that actually is just one)
// and put into $max variable
while ($row = mysql_fetch_assoc($rowcount))
{
$max = $row["rows"];
}
B
//get the text from database based on randon limit offet
$result = mysql_query("select from quotables limit $rand, 1");
//put the value returned into $row variable
$row = mysql_fetch_array($result);
//get the storedText (that is a table column name), and put the value into $randomOutput
$randomOutput = $row['storedText'];
C:
Based on code I can't afirm what is the database model.

Select nth record from a SQL result set in php

I run a query and get a result set. I need to get the nth record from this result set. Any ideas how I can do this?
I cannot select the nth record from the database directly coz I need to filter it and don't know how many records there are in the result set. So I cannot be certain which number to pass to the mysql_result method i.e.
Based on certain conditions, get a few rows from a table
From these rows, select the nth row (the number n is not fixed. It depends on the number of records returned)
The basic idea is to get all results based on a set condition and get a random result from these.
Any ideas? Thanks.
Your question seems unclear. However here's a guess:
You want to select the record in the middle:
$count = mysql_num_rows($result);
$middle_name = mysql_result($result, intval($count/2), 'name');
Besides that, you can also do that if you have really less records:
$rs = array();
while ($row = mysql_fetch_assoc($result)){
$rs[] = $row;
}
and then you can use $rs[N-1] to reach Nth record.
Read mysql_data_seek from PHP Manual if you will fetch just one record.
The basic idea is to get all results based on a set condition and get a random result from these.
SELECT ... ORDER BY RAND() LIMIT 1
I know this is not best practice, but as the given information is rather sparse, this could be starting point for further reading. And to be honest, in an small enough application, this is often the easiest solution.

Categories