I have an mysqli_query that pulls 3 columns and 10 rows from my table. I would to assign a variable to each row of the query. I could do 10 seperate querys and assign each to a variable, but i assumed that would be frowned upon. (note: connection info in seperate file and not shown here).
<?php
$playoffseedings = mysqli_query($con, "SELECT playoffseed, ttName, ttsUID
FROM standings
WHERE ttsUID = $season_view
AND playoffseed > 0
ORDER BY playoffseed
LIMIT 10");
$seedings = array($playoffseedings);
FOREACH($seedings as $ps){
$num_rows = 1;
while($row = mysqli_fetch_array($ps)){
$num_rows++;
echo $row['playoffseed'].$row['ttName'];
echo "<br>";
}}
?>
The FOREACH used above works fine and returns 10 rows of the data I queried. So that's cool. But I need to be able to display different rows in different places on my page. So I thought assigning each row to a different variable would work well.
I tried adding something such as this to assign a variable to each row so that I'd have 10 different variables $seed1, $seed2, $seed3..., each $seedx would be an array of playoffseed, ttName, and ttsUID.
FOREACH($seedings as $ps){
$num_rows = 1;
while($row = mysqli_fetch_array($ps)){
$num_rows++;
$seed$num_rows = $row[$num_rows];
}}
I'd like to know how to do the above, but also, I was confused on my journey as to why I couldn't echo a row from the an array using something like
echo $seedings[1];
echo $seedings[7]['playoffseed'];
Why wouldn't 'echo $seedings[1];' return the result of the second row of the $seedings array? I got a blank.
And why wouldn't 'echo $seedings[7]['playoffseed'];' return the playoffseed of the 8th row? Again, blank.
I felt the 2 questions were tied together because I thought I could either refer to the data I wanted to later with either a variable (ie. $seed3), or I could possibly refer to the data I need using the index (keys?) of the array (ie $seedings[7]['playoffseed']).
First post! Thanks for the help. Usually always find what I need after a few hours of searching. Stuck on this one after a few days of looking.
Edit (In an attempt to clarify):
My query returns a table (multidimensional array?) like this...
ttsUID ttName playoffseed
1993 Buffalo 1
1993 Miami 2
1993 Detroit 3
1993 Denver 4
1993 Chicago 5
...and so on. 10 rows total
After calling that query I'd like to set variables ($seedx) such as this...
$seed1 = (1993, Buffalo, 1)
$seed2 = (1993, Miami, 2)
$seed3 = (1993, Detroit, 3)
...and so on until $seed10
So each $seedx variable is an array which is pulled from the multidimensional array. That's pretty much it.
Alternatively I could make 10 separate querys to the database and increment 'AND playoffseed = 1' each time such as this...
$seed1 = mysqli_query($con, "SELECT playoffseed, ttName, ttsUID
FROM standings
WHERE ttsUID = $season_view
AND playoffseed = 1");
$seed2 = mysqli_query($con, "SELECT playoffseed, ttName, ttsUID
FROM standings
WHERE ttsUID = $season_view
AND playoffseed = 2");
but I didn't think querying the database 10 times was the way to go.
In the end I was hoping to get 10 variables ($seed1, $seed2,...$seedx) which would each be an array that includes (ttsUID, ttName, playoffseed).
still i am not sure how you want to store the data,but i hope this helps you
$playoffseedings = mysqli_query($con, "SELECT playoffseed, ttName, ttsUID
FROM standings
WHERE ttsUID = $season_view
AND playoffseed > 0
ORDER BY playoffseed
LIMIT 10");
while($row = mysqli_fetch_assoc($playoffseedings))
{
$seed[$row['ttName']] = $row['ttsUID'];
$seed[$row['playoffseed']] = $row['ttsUID'];
}
this will have data like below
(for example)
$seed['ttname123']= ttsuid123
$seed['playoffseed123']= ttsuid123
$seed['ttname456']= ttsuid456
$seed['playoffseed456']= ttsuid456
........
......
Related
I am making a golf leaderboard in which I take all the hole scores from a specific matchid and group them by the userid. This part works just fine.
I do so like this:
$playersArray = array();
$sql = "SELECT *, SUM(point) AS points, COUNT(*) AS holes, COUNT(*)*2-SUM(point) AS topar FROM fb_score WHERE matchid=$matchid GROUP BY userid";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
$playersArray[] = $row;
}
}
Now, my question is, is there a waythat I can create an array of all the "point" for each user and get that into the $row?
Lets say that the SUM(point) is summed by lets say 3 points (3, 5, 4). Can I get this out in the result. As it is now I only get the latest $row for each user, but with the added "points", "holes" and "topar".
Hope this question makes sense :-/
Any help is appreciated and thanks in advance :-)
May be a bit hacky but it works. Simply GROUP_CONCAT the values and you get them in your $row var and you will be able to explode them in an array.
select *, GROUP_CONCAT(CONVERT(point,CHAR)) as all_points from fb_score GROUP BY userid
I have a query like this
$sql = "SELECT SUM(CASE WHEN jr_softwarecheck LIKE \'%sony\' AND
jr_othersoftware LIKE \'%sony%\' THEN 2 ELSE 1 END) AS totalcount FROM
jos_jreviews_content WHERE jr_softwarecheck LIKE \'%sony%\' OR
jr_othersoftware LIKE \'%sony%\'";
I want to output results in HTML pages. I run a Joomla based site.
How can I do that?
Sorry but I'm not so skilled in PHP, I'm learning.
Expected result in HTML page (frontend), example:
SONY Products: 105
Thanks in advance to all!
In your case, use it like this:
$sql = "SELECT SUM(CASE WHEN jr_softwarecheck LIKE \'%sony\' AND jr_othersoftware LIKE \'%sony%\' THEN 2 ELSE 1 END) AS totalcount FROM jos_jreviews_content WHERE jr_softwarecheck LIKE \'%sony%\' OR jr_othersoftware LIKE \'%sony%\'";
$res = mysql_query($sql); // This will run the query on the connected datababse
if($row = mysql_fetch_array($res)){ // Since you are using just a SUM to count results, you don't need to loop
echo "Sony Products: ".$row['totalcount']; // $row['totalcount'] is the result of the totalcount from your MySQL query put into the $row variable
}
I hope this helps you out :)
$result = mysql_query($sql) or die (mysql_error());
while($row = mysql_fetch_assoc($result)){
//do something
}
Trying to search through a column in a db, and pull out the total number of males, and total number of females.
This data is stored in the db as f and m in the whatsex column.
$query = "SELECT whatsex, COUNT(*) FROM soberdata GROUP BY whatsex";
$result = mysqli_query($connection,$query) or die(mysql_error());
$sexdb = mysqli_fetch_array($result);
$totalmale = $sexdb['m'];
$totalfemale = $sexdb['f'];
echo $totalfemale." & ".$totalmale;
This code outputs nothing. What am I doing wrong?
$sexdb have only "whatsex" and "COUNT(*)" columns. You should use one of them
try
print_r($sexdb);
and look if some of results meet your needs
Your query is going to return a whatsex value, and a COUNT(*) value, not m or f. Doing a var_dump($sexdb) would show you what's in the array.
You are treating a multi-dimensional array as flat. You could do this to flatten it
$query = "SELECT whatsex, COUNT(*) as total FROM soberdata GROUP BY whatsex";
while ($row = mysqli_fetch_array($result)) {
$$row['whatsex'] = $row['total']; // this makes a variable ($m or $f) using the value of the row
}
$totalmale = !empty($m) ? $m : 0;
$totalfemale = !empty($f) ? $f : 0;
You should empty check the results of the db in case there is no male or female entries to avoid errors.
Will this query work? Is it most efficient?
SELECT * FROM `posts`
WHERE MATCH (`title`, `body`)
AGAINST ('search terms' IN BOOLEAN MODE)
AND `price` BETWEEN '100' AND '1000'
AND (`postinto` = 'cat1' OR `postinto` = 'cat2')
AND (`location` = 'loc1' OR `location` = 'loc2')
ORDER BY `id` DESC
LIMIT 0, 100;
Note: values for postinto and location will be contained in a PHP arrays, so if this will work I plan on looping their the arrays to generate the query terms. Is there a way to pass the entire array to MySQL? Also, these two conditions have a possibility of being quite long (a dozen values). Is there a better way?
specifically my question is about this:
AND (`postinto` = 'cat1' OR `postinto` = 'cat2')
AND (`location` = 'loc1' OR `location` = 'loc2')
an example of possible values would be "community|groups", "buy-sell-trade|electronics" where before the | is a category and after | is a sub category. If I am searching an entire category I would want to change that part of the query to:
AND (`postinto` LIKE 'category|%' OR `postinto` = 'this'
I have the proper indexes for the fulltext search, my question is about the OR clause. Is there a maximum number of times you can use OR in one query? Is this syntax even correct?
Thanks
Actually there is. The IN statement can help you here.
Your query would then become like this:
SELECT * FROM `posts`
WHERE MATCH (`title`, `body`)
AGAINST ('search terms' IN BOOLEAN MODE)
AND `price` BETWEEN '100' AND '1000'
AND `postinto` IN ('cat1', 'cat2')
AND `location` IN ('loc1', 'loc2')
ORDER BY `id` DESC
LIMIT 0, 100;
You can use AND and OR in a WHERE as often as you want, but to keep your sanity you need to obey a few simple rules.
1) Do not mix them, constructing a query with WHERE AND OR AND OR will probably work but the results will be unpredictable and the result set may contain multiple instances of the same record! (You are effectively turning the OR construct into an EITHER!
2) I would recommend always putting all of the OR statements before any AND statements. It will be easier for you to understand and for anybody else to maintain.
3) It is probably not a necessity but I always if possible enclose the OR statements in brackets.
I Maintain a Sports database and run some queries that can have multiple options in the select.
Hopefully the following examples will simplify the explanation.
// Make the query to retrieve the set of Singles Games.
$query = "SELECT * from Games WHERE Season = '$season'
AND GameNo < 8
OR Player1 = '$playerName' ORDER by MatchNo ASC";
$result = #mysql_query($query); // Run the query.
$num = mysql_num_rows($result);
This will run, it is syntactically correct but the results will be unpredictable!
If in these circumstances you wish to put the OR after the AND then you need to 'AND' the OR.
// Make the query to retrieve the set of Singles Games.(This is correct)
$query = "SELECT * from Games WHERE (Player1 = '$playerName'
OR Player3 = '$playerName') AND Season = '$season'
AND GameNo < 8 ORDER by MatchNo ASC";
$result = #mysql_query($query); // Run the query.
$num = mysql_num_rows($result);
This will run and produce a list of Singles games in which a player has participated.
The following is the same statement with the OR after the AND. Notice you need to AND
the OR to the end of the statement.
// Make the query to retrieve the set of Singles Games.(This is also correct)
$query = "SELECT * from Games WHERE Season = '$season'
AND GameNo < 8 AND (Player1 = '$playerName'
OR Player3 = '$playerName') ORDER by MatchNo ASC";
$result = #mysql_query($query); // Run the query.
$num = mysql_num_rows($result);
This will run and produce a list of Singles games in which a player has participated.
Finally a couple of examples, why I prefer the OR first
$query = "SELECT * from Games WHERE (Player1 = '$playerName'
OR Player2 = '$playerName' OR Player3 = '$playerName'
OR Player4 = '$playerName') AND Season = '$season'
AND GameNo > 7 ORDER by MatchNo ASC";
$result = #mysql_query($query); // Run the query.
$num = mysql_num_rows($result);
This will produce a result set containing all the League doubles that a player has participated in. Either as home player1 or 2, or away player 3 or 4.
To produce a query with multiple separate OR statements. Then place an AND between the OR
statements.
$query = "SELECT * from CupGames WHERE (Player1 = '$playerName'
OR Player2 = '$playerName' OR Player3 = '$playerName'
OR Player4 = '$playerName' OR Player5 = '$playerName'
OR Player6 = '$playerName') AND (CupID = 'CS' OR CupID = 'ND')
AND Season = '$season' AND GameNo < 4 ORDER by CupRound ASC";
$result04 = #mysql_query($query); // Run the query.
$num = mysql_num_rows($result04);
This will produce a result set containing all the Cup Triples that a player has participated in. Either as home player1,2 or 3, or away player 4, 5 or 6. In either of
the two selected cups. CS(Coronation Shield) or ND(Norman Day Cup) for the selected season.
If you wish to keep your hair I suggest following these rules.
(I have retired from IT and have a full head of hair!)
Best of Luck!
$count =0;
$result1 = mysql_query("SELECT fwid FROM sbsw WHERE fword = '".$searchText."'");
while ($result2= mysql_fetch_array($result1))
{
$result3 = mysql_query("SELECT fsyn FROM wrsyn WHERE fwid = '".$result2[$count]."'");
$result4= mysql_fetch_array($result3);
print $result4[$count].'<br>';
$count++;
}
mysql_free_result($result1);
mysql_free_result($result3);
Let's have a look at how mysql_fetch_array works - for example if you have table structure like
id | name | surname | role
1 John Smith user
2 Peter Qeep user
3 Mark Ziii admin
When you execute a query SELECT * FROM table and then loop $result = mysql_fetch_array($query), $result will always be an array(4) containing
[0] => id,
[1] => name,
[2] => surname,
[3] => role
Therefore, when you execute the query $result3 = mysql_query("SELECT fsyn FROM wrsyn WHERE fwid = '".$result2[$count]."'");, in the first iteration, $count will be 0 which is the key for the result returned by the previous query, however in any further iteration it will increase and that will lead to an undefined key. This means that you have to stop using the variable $count and just use $result2[0] instead.
Also, way better approach to this would be using MySQL JOIN, in your example it would be SELECT w.fsyn FROM sbsw s JOIN wrsyn w ON s.fwid = w.fwid WHERE s.fword = "'.$searchText.'";
Please, use reasonable variable names and indent properly. You're getting one column from each row as you're only printing out once for each iteration over your rows.
Basically: For each row, print the value of a column.
The $count-variable decided which column, but it obviously didn't make sense at it counts the row you're at.
Something like this should do it: (not tested)
$result1 = mysql_query("SELECT fwid FROM sbsw WHERE fword = '".$searchText."'");
while ($result2= mysql_fetch_array($result1))
{
$result3 = mysql_query("SELECT fsyn FROM wrsyn WHERE fwid = '".$result2['fwid']."'");
$result4= mysql_fetch_row($result3);
for($x = 0; $x < count($result4); $x++){
print $result4[$x].'<br>';
}
}
mysql_free_result($result1);
mysql_free_result($result3);
Oh and I changed fetch_array to fetch_row in the inner loop to ease iteration.