Switch Between two Seperate Table Queries PHP MySQL - php

I'm trying incorporate a "News Feed" into my site, pulling information from two different tables (Using two seperate queries). One feed pulls current stories "$newsfeed" and the other pulls history stories "$historyfeed". Both tables need to remain seperate. I'm attempting to place these queries in a random order for a set number or rows. For example, I want 5 stories listed, with history and news choosen randomly.
The order might be: History, News, History, History, History
the next visit might produce: News, News, New, History, News
This part seems to work fine...
However, I've been unable to move to the next row in the query. So five of the exact same news stories are produced, instead of moving to the next row of the query. See the example code below:
//DB connection established earlier
$newsfeed = mysql_query("SELECT * FROM newsfeed WHERE story_type='business'"); //News Story Query
$row_newsfeed = mysql_fetch_assoc($newsfeed);
$historyfeed = mysql_query("SELECT * FROM newsfeed WHERE story_type='business'"); //History Story Query
$row_historyfeed = mysql_fetch_assoc($historyfeed);
$storycount = 0;
while ($storycount < 5) {
$storytype = rand(1,2); //randomly select next story type
switch ($storytype){
case: "1" //if next story is a new story
storybubble($row_newsfeed); //function to echo newsfeed content
$storycount++;
break;
case: "2" //if next story is a history story
storybubble($row_historyfeed); //function to echo historyfeed content
$storycount++;
break;
default:
echo "Error";
} //switch statement
} //story count while statement

You create the variables at the top, and load stories into $historyfeed and $newsfeed; but you keep using the same variables in your loop. This should work a little better:
case: "1" //if next story is a new story
$row_newsfeed = mysql_fetch_assoc($newsfeed);
storybubble($row_newsfeed); //function to echo newsfeed content
$storycount++;
break;
case: "2" //if next story is a history story
$row_historyfeed = mysql_fetch_assoc($historyfeed);
storybubble($row_historyfeed); //function to echo historyfeed content
$storycount++;
It's populating the variables when they're needed, instead of at the start of the code.

mysql_fetch_assoc() returns one row of the result.
If you want to return the next row you need to call mysql_fetch_assoc() again.
So you could change your calls to storybubble to:
storybubble(mysql_fetch_assoc($row_newsfeed));
However, you'll probably be better off to build an array of the rows and then pull from that.
$newsfeed = array();
$historyfeed = array();
while($row = mysql_fetch_assoc($newsfeed)) {
$newsfeed[] = $row;
}
while($row = mysql_fetch_assoc($historyfeed)) {
$historyfeed[] = $row;
}
...
switch($storytype) {
case 1:
storybubble(array_shift($newsfeed));
break;
}
...

Related

Using a switch statement with fetch_array

Ok, I've created a simple page that allows me to calculate customer satisfaction for the leaders who work in my store. Basically, I have a mysql database that contains the names of all the leaders who work there, along with the dates and time that they work. I also have a database that contains the dates, and times of a customers visit and the rating that they gave their visit.
I've created a query that behaves in such that when I query a leader's name, it returns all of the ratings/scores that were submitted by customers on the dates and times that specific leader was working.
Customers usually rate their experiences from 1 - 10 with 10 being the best. I wanted to transform those scored responses to a simple lettered system where a score of 9-10 would equal "G" for Good, 7-8 would equal "O" for ok and anything below 6 would equal "B" for bad.
Using mysqli_fetch_array and a switch statement, I tried to convert the numbers to the letters. However, I don't seem to be getting any results from this. I've tested the query and the fetch_array and if I use them by themselves (without the switch statement), they produce the correct scored responses (ie. Paul's score 10, 9, 9). But when I insert the switch statement, they do not convert to letters and nothing appears on the screen. Question: Is there something wrong with the way i'm using this switch statement or mysqli_fetch_array. I'm very new to coding so I may have a misunderstanding of the way these are used.
here's the php
<html>
<body>
<?php
include("db.php");
echo $_POST['searched']; // temp. check to see if post came through
echo '<br>';
$searched = $_POST["searched"]; // create variable to put searched name in query.
$good = array(); //create array to store good scores
$ok = array(); //create array to store ok scores
$bad = array(); //create array to store bad scores
// Search the database and retrieve all ratings That matches a managers name
$query = "SELECT leaders.name, responses.score
FROM leaders
INNER JOIN responses
ON leaders.shift_date = responses.visit_date
AND leaders.shift_time = responses.visit_time
AND leaders.name = '$searched' ORDER BY leaders.id;";
$result = $db->query($query); //store that query
//iterate through result and grab each score
while ($row = $result->fetch_array()){ // place scores into an array
// use a switch statement to change numbered system to lettered
switch($row[1]) {
case 10:
case 9:
array_push($good, "G");
break;
//echo $row[1] . ' '; temp check to ensure array call was successful
echo $good[0] . ' ';
}
}
//echo "<script>window.location = 'http://localhost/~baronjon/ilotf/main.php'</script>";
?>
</body>
</html>
You have to switch on a specific field of the array and not the whole array.
Try this
//iterate through result and grab each score
while ($row = $result->fetch_array()){ // place scores into an array
// use a switch statement to change numbered system to lettered
switch($row['score']) {
case 10:
case 9:
array_push($good, $row);
break;
case 8:
case 7:
array_push($ok, $row);
break;
default:
array_push($bad, $row);
} // endswitch
}
print_r( $good );
print_r( $ok );
print_r( $bad );
Now you have the 3 new arrays each containing the result rows that fall into the 3 categories.
PS Dont use row[0] syntax, because as soon as you change your select statement and add another field to the front of the field list you will be testing the wrong field in your switch.

What is my last row_number in mysql query?

I have a query like this:
$sql = "SELECT * FROM doctors WHERE city ='$city' LIMIT 10 ";
$result = $db->query($sql);
And I show the result like this :
while($row = $result->fetch_object()){
echo $row->city;
}
The Problem :
Mysql , will search through my database to find 10 rows which their city field is similar to $city.
so far it is OK;
But I want to know what is the exact row_number of the last result , which mysql selected and I echoed it ?
( I mean , consider with that query , Mysql selected 10 rows in my database
where row number are:
FIRST = 1
Second = 5
Third = 6
Forth = 7
Fifth = 40
Sixth = 41
Seventh = 42
Eitghth = 100
Ninth = 110
AND **last one = 111**
OK?
I want to know where is place of this "last one"????
)
MySQL databases do not have "row numbers". Rows in the database do not have an inherent order and thereby no "row number". If you select 10 rows from the database, then the last row's "number" is 10. If each row has a field with a primary id, then use that field as its "absolute row number".
You could let the loop run and track values. When the loop ends, you will have the last value. Like so:
while($row = $result->fetch_object()){
echo $row->city;
$last_city = $row->city;
}
/* use $last_city; */
To get the row number in the Original Table of the last resultant (here, tenth) row, you could save the data from the tenth row and then, do the following:
1. Read whole table
2. Loop through the records, checking them against the saved data
3. Break loop as soon as data found.
Like So:
while($row = $result->fetch_object()){
echo $row->city;
$last_row = $row;
}
Now, rerun the query without filters:
$sql = "SELECT * FROM doctors";
$result = $db->query($sql);
$rowNumber = 0;
while($row = $result->fetch_object()) {
if($row == $last_row) break;
$rowNumber++;
}
/* use $rowNumber */
Hope this helps.
What you can do is $last = $row->id; (or whatever field you want) inside your while loop - it will keep getting reassigned with the end result being that it contains the value of the last row.
You could do something like this:
$rowIndex = 0;
$rowCount = mysqli_num_rows($result);
You'd be starting a counter at zero and detecting the total number of records retrieved.
Then, as you step through the records, you could increment your counter.
while ( $row = $result->fetch_object() ) {
$rowIndex++;
[other code]
}
Inside the While Loop, you could check to see whether the rowIndex is equal to the rowCount, as in...
if ($rowIndex == $rowCount) {
[your code]
}
I know this is a year+ late, but I completely why Andy was asking his question. I frequently need to know this information. For instance, let's say you're using PHP to echo results in a nice HTML format. Obviously, you wouldn't need to know the record result index in the case of simply starting and ending a div, because you could start the div before the loop, and close it at the end. However, knowing where you are in the result set might affect some styling decisions (e.g., adding particular classes to the first and/or last rows).
I had one case in which I used a GROUP BY query and inserted each set of records into its own tabbed card. A user could click the tabs to display each set. I wanted to know when I was building the last tab, so that I could designate it as being selected (i.e., the one with the focus). The tab was already built by the time the loop ended, so I needed to know while inside of the loop (which was more efficient than using JavaScript to change the tab's properties after the fact).

Getting value from multiple drop down menus in PHP

Ive been battling away with the following problem
Ive got a page where I pull names from players specific to their positions in a sport squad.
Example: I will display all the Wings in the squad using a dropdown where a coach can then pick his wing for the game.
There are dropdowns for each different position
The aim of the page is to let the coach quickly select his team for a fixture
After the coach selected his team he will, select the opponents for which the selected team will play against.
When he clicks submit the selected oppents and players will get stored in two arrays which will get called to display the team selected and their opponents on a new page. (After which it will get uploaded to the DB.)
I am having trouble getting the values from the select list to display on the new page.
I guess I have to do something like this on the new page:
foreach ($_REQUEST['opponents'] as $opponents){
print $opponents;
echo'<br>';
}
but it is not giving the desired results.
Strangely what gets printed is the variable name from the previous page select menu.
Upon further inspection I did a vardump on the new page and it says that $opponenets gets passed a value of string which is the variable name and not the value thereof?
My page looks like this
My question is how would I go abouts getting the values from the select dropdowns
if(isset($_POST["submit"]))
{
foreach ($_REQUEST['opponents'] as $against){
var_dump($against);
print $against;
echo'<br>';
}
}
else
{
echo'<h1>Select your Team</h1>';
$x = array("THP", "HKR", "LHP", "LH", "FLH"); //players positions gets assigned to x which will be used to query the database
echo '<form name="playerselect" method="post" action="">';
//query database with different query after each loop
for ($i = 0; sizeof($x) > $i; $i++)
{
//query where position field equeals variable x
$result = mysql_query("SELECT `name`, `position` FROM `player_info`
WHERE `position` = '$x[$i]'") or die(mysql_error()) ;
//Gets data from DB and assigns values to arrays below
while($row = mysql_fetch_array($result))
{
$playername[] = $row['name'];
$position[] = $row['position'];
}
//print player position
print $position[0];
echo'<br>';
//unset the array so that it is empty for the next query in the new loop
unset($position);
echo '<select name="players[]" >' ;
foreach ($playername as $name )
{
//Put playernames relevant to the position in the option element
echo'<option value="$name" selected="selected">'.$name;'</option>';
echo'<br>';
}
echo'</select>';
//unset array so that its contents is empty for the next query in the new loop
unset($playername);
echo'<br>';
}
You cannot. Your submit will only transmit select values. This is not a bug, it is a feature. You do not want to send data back and forth from/to the server/client which is known to both of them.
On the server you are free to query your database at any time. You can also cache your select list into the $_SESSION variable in your initial list read. However this is advanced fittling as your cache list may become outdated and also your server memory utilization must leave space for file caching (the SESSION cache goes to files).
If you go for the database query you may need some ID as sort of anchor. Just put the into the $_SESSION variable - eg.:
$_SESSION['positions']=$x;
In your example the $x seems to be static, which obviously reduces the need to cache it into the $_SESSION - however on other occasions you may need this method.

php query does not retrieve any data?

well, i wanna pull out some data from a mysql view, but the wuery dos not seem to retrieve anything ( even though the view has data in it).
here is the code i've been "playing" with ( i'm using adodb for php)
$get_teachers=$db->Execute("select * from lecturer ");
//$array=array();
//fill array with teacher for each lesson
for($j=0;$j<$get_teachers->fetchrow();++$j){
/*$row2 = $get_lessons->fetchrow();
$row3=$row2[0];
$teach=array(array());
//array_push($teach, $row3);
$teach[$j]=mysql_fetch_array( $get_teachers, TYPE );
//echo $row3;*/
$row = $get_teachers->fetchrow();
//$name=$row[0]+" "+$row[0]+"/n";
//array_push($teach, $row1);
echo $row[0]; echo " ";echo $row[1]." ";
//$db->debug = true;
}
if i try something like "select name,surname from users", the query partially works . By partially i mean , while there are 2 users in the database, the loop only prints the last user.
the original query i wanted to execute was this
$get_teachers=$db->Execute("select surname,name from users,assigned_to,lessons
where users.UID=assigned_to.UID and lessons.LID=assigned_to.LID and
lessons.term='".$_GET['term']."'");
but because it didnt seem to do anything i tried with a view ( when you execute this in the phpmyadmin it works fine(by replacing the GET part with a number from 1 to 7 )
the tables in case you wonder are: users,assigned_to and lessons. ( assigned_to is a table connecting each user to a lesson he teaches by containing UID=userid and LID=lessonid ). What i wanted to do here is get the name+surname of the users who teach a lesson. Imagine a list tha displays each lesson+who teaches it based on the term that lesson is available.
Looking at http://adodb.sourceforge.net/ I can see an example on the first page on how to use the library:
$rs = $DB->Execute("select * from table where key=123");
while ($array = $rs->FetchRow()) {
print_r($array);
}
So, you should use:
while ($row = $get_teachers->fetchrow()) {
instead of:
for ($j = 0; $j < $get_teachers->fetchrow(); ++$j) {
The idea with FetchRow() is that it returns the next row in the sequence. It does not return the number of the last row, so you shouldn't use it as a condition in a for loop. You should call it every time you need the next row in the sequence, and, when there are no more rows, it will return false.
Also, take a look at the documentation for FetchRow().
for($j=0;$j<$get_teachers->fetchrow();++$j){
... a few lines later ...
$row = $get_teachers->fetchrow();
See how you call fetchrow() twice before actually printing anything? You remove two rows from the result set for every 1 you actually use.
while ($row = $get_teachers->fetchrow()) {
instead and don't call fetchrow() again within the loop.
Because you're fetching twice first in the loop
for($j=0;$j<$get_teachers->fetchrow();++$j){
... some code ...
// And here you fetch again
$row = $get_teachers->fetchrow();
You should use it like this
while ($row = $get_teachers->fetchrow()) {

PHP, MySQL Per row output

Been all over the place and spent 8 hours working loops and math...still cant get it...
I am writing a CP for a customer. The input form will allow them to add a package deal to their web page. Each package deal is stored in mysql in the following format
id header item1 item2 item3...item12 price savings
The output is a table with 'header' being the name of the package and each item being 1 of the items in the package stored in a row within the table, then the price and amount saved (all of this is input via a form and INSERT statement by the customer, that part works) stored rows as well.
Here is my PHP:
include 'dbconnect.php';
$query = "SELECT * FROM md ";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
//Print 4 tables with header, items, price, savings
//Go to next row (on main page) and print 4 more items
//Do this until all tables have been printed
}
mysql_free_result($result);
mysql_close($conn);
Right now the main page is simpley a header div, main div, content wrap and footer div.
Ideal HTML output of a 'package' table, not perfect and a little confusing
$header
$item1
$item2
ect...
$price$savings
I basically want the PHP to print this 4 times per row on the main page and then move to the next row and print 4 times and continue until there are no more items in the array. So it could be row 1 4 tables, row 2 4 tables, row 3 3 tables.
Long, confusing and frustrating. I about to just do 1 item per row..please help
Jake
You say "tables", but do you mean cells?
The basic flow would be:
$res = mysql_query(...) or die(mysql_error());
if (mysql_numrows($res) == 0) {
... say there's nothing to show ...
} else {
... print table header ...
while($row = mysql_fetch_assoc($res)) {
... print row ...
}
... print table footer
}
if i get your question right you need to use a loop, something like a for
while ($row = mysql_fetch_array($result)) {
for($i=1; $i<=3; $i++){
//print table (change $i values to change number of loops)
}
}
if i didnt get it right, please post an example of how the table should look like.
$items_per_line=4;
$counter=$items_per_line;
while ($row = mysql_fetch_array($result)) {
if($counter <1){
$counter=$items_per_line;
// goto next pages
}
// print header etc.
$counter--;
}

Categories