I am making an exercise related app. My plans are for day A and day B. I have a database with a list of exercises in it. When I try to search for a given exercise, it is drawn for day A. But when I try to draw it for day B, it happens that the two are the same data. I tried to compare these two data, but I still fail.
$e_legs_B = "SELECT * FROM exercises WHERE body_part = 'Quad' AND difficulty = 'Easy' ORDER BY RAND() LIMIT 1";
$e_legs_B_run = mysqli_query($conn, $e_legs_B);
Then in body my code looks like this.
<?php
$rows = $e_legs_B_run->fetch_assoc();
$name = $rows['name'];
echo "<option value = '$name'>$name</option>";
?>
Select data for day a and b in one query and split the result.
Or store the id's from day a in an array and exclude them in the second query for day b.
Related
Good afternoon lads, I am trying to make a page where I can check which bosses I did today. I have two tables (table with bosses and table with boss times). Now I need to show all bosses but for each of them I only want to show the closest time when the boss is going to spawn.
The select so far looks like that:
$timePlus = strtotime($currentTime) + 60*60*2.2;
$timePlusForm = date("H:i:s", $timePlus);
$userNametoLower = strtolower($userName);
$userTableName = "".$userNametoLower."_bosses";
$currentTime = date("H:i:s", time());
"SELECT `bossTime`.`ID`, `bossTime`.`bossID`, `bossTime`.`time`, `$userTableName`.`ID`, `$userTableName`.`name`,
`$userTableName`.`zone`, `$userTableName`.`map`, `$userTableName`.`waypointCode`, `$userTableName`.`bossDone`
FROM `bossTime` LEFT JOIN `$userTableName` ON `$userTableName`.`ID` = `bossTime`.`bossID`
WHERE `bossTime`.`time` BETWEEN '$currentTime' AND '$timePlusForm'
GROUP BY `bossTime`.`bossID`
ORDER BY `bossTime`.`time` ASC";
The problem is that this select does not pick the next closest value from time table. I also tried BETWEEN and it also didn't work (some bosses got correct closest time but other got the second closest). Any idea how to solve this is welcomed.
I removed GROUP BY and changed the condition to WHERE bossTime.time >= '$currentTime' AND bossTime.time <='$timePlusForm' and for some reason it works
I want to read the last 3 rows of my table seperate and then place them in 3 different div's of a slider. The problem is that i cant use 'where id=xxx' because i insert rows dynamically every time that i make a post item.
if i use query('select * from news order by id desc limit 3') and then a loop while ($result->fetch_assoc()) then i have the last 3 rows.
My problem is that i want to place every row in a different div so that i will have 3 divs.
I suppose i must do 3 different queries for that but i dont know how.
I have this one right now.
$result = $myDb->query('select * from news order by id desc');
while ($nI = $result->fetch_assoc()) {
$title = $nI['title'];
$date = $nI['date'];
$author = $nI['author'];
$mainobjective = $nI['mainobjective'];
$contents = $nI['contents'];
$keywords = $nI['keywords'];
and then i have my html where with the use of echo i place every variable in the div i want.
It sounds like the problem you are describing is more with your PHP code, that you haven't posted, than your MySQL. Don't read them separately. Use a single query to get all 3 and then iterate through them separately with PHP.
You can use the query you already had:
$result = $myDb->query('SELECT * FROM news ORDER BY id DESC LIMIT 0,3');
Make sure you are placing the results in separate containers in PHP:
foreach($result as $row)
{
echo "<div>".$row."</div>";
}
I have a table that has rows like CALL_ID, Timestamp, Date, First_Name, Last_Name, Status and so on..
What I need to do is draw graphs based on the data, filtered according to their dates.
That is for the Month-to-date graph, I need to show the number of rows matching status=approved for each day of the month uptil current date.
And, for the Year-to-date graph, I need to show the number of rows matching Status=approved for each month of the year uptil current month.
My idea of doing it is this -
For Month-to-date:
$temp = date("Y-m-");
while($i<=date("d"))
{
$query = "SELECT call_id FROM main WHERE status='approved' AND date='".$temp.$i."'";
$result = mysql_query($query, $link) or die("",mysql_error());
$count[i]= mysql_num_rows($result);
}
For Date-to-year:
while ($i <= date("m"))
{
$query = "SELECT call_id FROM main WHERE status='approved' AND date BETWEEN'".$today_y."-".$i."-01' AND '".$today_y."-".$i."-31";
$result = mysql_query($query, $link) or die("",mysql_error());
$count_y[i]= mysql_num_rows($result);
}
And then I was thinking of pushing these counts present in the array by a "while" loop into another temporary tables (one for MTD and one for YTD) and then using PHP libchart to draw the graph from those tables.
Is there a better way to do this? Or is this the only way?
You can accomplish this a lot easier just using mysql and getting rid of a lot of your php loops. Something like this for month-to-date:
$query="SELECT COUNT(call_id) as 'num_records', date FROM main WHERE status='approved' AND CONCAT(YEAR(date),MONTH(date)) = CONCAT(YEAR(NOW()),MONTH(NOW())) GROUP BY date
That query will give a row showing the date and the total records for that day, for every day month-to-date.
I'm trying to do two separate database quires and return the results to a form. Each result is written to a table.
I want to be able to combine the two queries into one and order the results by task number.
FIRST QUERY:
//Booking
$Date= date("d/m/Y");
$driver = $_SESSION['username'];
$dbTaskRecords = "SELECT * FROM booking WHERE driver='$driver' AND Date= CAST('$Date_search' AS DATE) ORDER BY TaskNo ASC";
$dbTaskRecords_result = mysql_query($dbTaskRecords);
SECOND QUERY:
//Return Booking
$dbTaskReturn = "SELECT * FROM returnbooking WHERE driver='$driver' AND Date= CAST('$Date_search' AS DATE) ORDER BY TaskNo ASC";
$dbTaskReturn_result = mysql_query($dbTaskReturn);
The results are then outputted to the page through a while statement.
$i=0;
while ($row = mysql_fetch_array($dbTaskRecords_result)){
//Control Structure for Move Time on first Job of day
if ($i==0 ){
$time = $row["Time"];
//$time = 'N/A';
}else{
$time = 'N/A';
}
//Get Rego from trucks table
$truckID = $row["TruckID"];
$Rego_select = mysql_query("SELECT VechicleRegistration FROM trucks WHERE TruckID = '$truckID'" )
or die("Problem reading table: " . mysql_error());
$Rego = mysql_result($Rego_select,0);
//Get unregisted from trucks table
$Unregisted_select = mysql_query("SELECT Unregistered FROM trucks WHERE TruckID = '$truckID'" )
or die("Problem reading table: " . mysql_error());
$Unregisted = mysql_result($Unregisted_select,0);
$id_note = $row["BookingID"];
echo '<td><a href="taskpage.php?id='.$id_note.'"><button>'. $row['TaskNo']."</button><a/></td>";
echo "<td>". $time . "</td>"; // Time Frame
echo "<td>". $Unregisted."</td>"; // Pickup
echo "<td>". $Rego."</td>"; // Unregisted
echo "<td>".$row["PickupLocation"] . "</td>"; // Rego
echo "<td>".$row["DropOffLocation"] . "</td></tr>"; // Delivery
$i=$i+1;//Control Set
}
echo'</tr>';
I repeat this same output code for the results from the return booking.
Is it possible to combine both queries into one so that the result set from both tables can be ordered by ASC and outputted by the above while statement.
This is one of the many reasons to avoid Select *. You can simply use a union
Select Time, TruckId, TaskNo, PickupLocation, DropOffLocation
From booking
Where driver='$driver'
And Date= CAST('$Date_search' AS DATE)
Union All
Select Time, TruckId, TaskNo, PickupLocation, DropOffLocation
From returnbooking
WHERE driver='$driver'
And Date= CAST('$Date_search' AS DATE)
Order By TaskNo Asc
In this solution, you need to enumerate the columns and ensure that the type of the columns, in the order in which they are enumerated in the two Select clauses are identical.
From what I can tell you have three options to accomplish what you are after.
You could use a join, assuming the two tables have a foreign key.
You could use a union to append the two result sets.
You could output both queries into an array and iterate through that array for your output. This is probably less efficient then a union, but gives you greater separation between the two result sets.
Using multiple smaller tables keep your data organized and ensures the column names are the same.
If we have for instance a company with a bunch of customers, and where customers could be private clients or companies, using a seperate table for those adresses and 2 reference tables with either client_id and adres_id or company_id and adres_id, the adres will always have the same column names.
Not only that, but if certain information is limited you don't run the risk of storing empty space...
In the end you should really stick to SQL for getting ALL the data you need in one go and use PHP (or other server side scripts) for formatting this data to the user. It isn't much of a problem for an internal or private website, but when you have more users you will want to limit the amount and size of your data transfers.
Using only 1 long query is often better than several smaller.
Hey guys, I created a list for fixtures.
$result = mysql_query("SELECT date FROM ".TBL_FIXTURES." WHERE compname = '$comp_name' GROUP BY date");
$i = 1;
$d = "Start";
while ($row = mysql_fetch_assoc($result))
{
$odate = $row['date'];
$date=date("F j Y", $row['date']);
echo "<p>Fixture $i - $d to $date</p>";
}
As you can see from the query, the date is displayed from the fixtures table.
The way my system works is that when a fixture is "played", it is removed from this table. Therefore when the entire round of fixtures are complete, there wont be any dates for that round in this table. They will be in another table.
Is there anyway I can run an other query for dates at the same time, and display only dates from the fixtures table if there isnt a date in the results table?
"SELECT * FROM ".TBL_CONF_RESULTS."
WHERE compid = '$_GET[id]' && type2 = '2' ORDER BY date"
That would be the second query!
EDIT FROM HERE ONWARDS...
Is there anyway I can select the date from two tables and then only use one if there are matches. Then use the rows of dates (GROUPED BY) to populate my query? Is that possible?
It sounds like you want to UNION the two result sets, akin to the following:
SELECT f.date FROM tbl_fixtures f
WHERE f.compname = '$comp_name'
UNION SELECT r.date FROM tbl_conf_results r
WHERE r.compid = '$_GET[id]' AND r.type2 = '2'
GROUP BY date
This should select f.date and add rows from r.date that aren't already in the result set (at least this is the behaviour with T-SQL). Apparently it may not scale well, but there are many blogs on that (search: UNION T-SQL).
From the notes on this page:
//performs the query
$result = mysql_query(...);
$num_rows = mysql_num_rows($result);
//if query result is empty, returns NULL, otherwise,
//returns an array containing the selected fields and their values
if($num_rows == NULL)
{
// Do the other query
}
else
{
// Do your stuff as now
}
WHERE compid = '$_GET[id]' presents an oportunity for SQL Injection.
Are TBL_FIXTURES and TBL_CONF_RESULTS supposed to read $TBL_FIXTURES and $TBL_CONF_RESULTS?
ChrisF has the solution!
One other thing you might think about is whether it is necessary to do a delete and move to another table. A common way to solve this type of challenge is to include a status field for each record, then rather than just querying for "all" you query for all where status = "x". For example, 1 might be "staging", 2 might be "in use", 3 might be "used" or "archived" In your example, rather than deleting the field and "moving" the record to another table (which would also have to happen in the foreach loop, one would assume) you could simply update the status field to the next status.
So, you'd eliminate the need for an additional table, remove one additional database hit per record, and theoretically improve the performance of your application.
Seems like what you want is a UNION query.
$q1 = "SELECT DISTINCT date FROM ".TBL_FIXTURES." WHERE compname = '$comp_name'";
$q2 = "SELECT DISTINCT date FROM ".TBL_CONF_RESULTS.
"WHERE compid = '$_GET[id]' && type2 = '2'";
$q = "($q1) UNION DISTINCT ($q2) ORDER BY date";