Change SQL query with different buttons for each query? - php

I'd like to be able to change the SQL query to another with the press of a button, I need about 8 buttons and 8 separate queries. If possible, I'd like to be able to do this without refreshing the page, just updating the table.
This is my current code:
<?php
include 'table/modes.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT m.MapName, SEC_TO_TIME(TRUNCATE(t.Time,3)) AS Time, p.User FROM times t INNER JOIN maps m ON t.MapID = m.MapID INNER JOIN players p ON p.PlayerID = t.PlayerID INNER JOIN (SELECT t.MapId, MIN(t.time) as time FROM times t WHERE t.style = 0 and t.type = 0 GROUP BY t.MapId ) tmin ON tmin.MapId = t.MapId and tmin.time = t.time";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table class='table table-striped table-fixedheader sortable'><thead><tr><th data-defaultsort='asc'>Map</th><th>Time</th><th>Player</th></tr></thead><tbody style='height:300px' class='searchable'>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["MapName"]."</td><td>".$row["Time"]."</td><td>".$row["User"]."</td></tr>";
}
echo "</tbody></table>";
} else {
echo "0 results";
}
$conn->close();
?>
Currently that fetches data for a table and displays it. I'd like buttons that execute different queries this and update the table without refreshing the page (not sure if possible).
How can this be achieved?
The main values I am looking to change in each query is this WHERE t.style = 0 and t.type = 0 too different numbers.

You can simply create a hidden input field to hold the type you want to change and when every you click the button you can change the value of the hidden field. During submision of the form the hidden input will go to the server with the value.

Related

Is it possible to loop through each row of a table in a database

I'm trying to loop through each row of a table in a database, then once I'm on a particular row get the value of a certain column. Is this possible? I've done a couple Google searches but nothing really concrete. I try using the mysqli_fetch_array() function but when I do I get the results of a column. I want to target each row. The code I have so far gets me the "nid" column. That's not what I want. I want to iterate through each row.
<?php
$serverName = "localhost";
$username = "user1";
$password = "sp#99#1";
$databaseName = "developer_site";
// Connection
$connection = new mysqli($serverName, $username, $password, $databaseName);
// Check Connection
if ($connection->connect_error) {
die("Connection failed:" . $connection->connect_error);
} // line ends if statement
$queryNodeRevision = "SELECT nid FROM node_revision";
// line above creates variable $queryNodeRevision > selects column "nid" from table "node_revision"
$results = mysqli_query($connection, $queryNodeRevision) or die("Bad Query: $results");
while ($row = mysqli_fetch_array($results)) {
echo "NID: ";
echo $row['nid'];
echo "<br/>";
}
?>
You can select rows by a certain condition with an SQL query alone and also select all columns.
SELECT * FROM node_revision where condition;
condition could be anything. For example another_row = 'something'.
But if, for some reason, you need to process the nid inside your php script to know if that row is the "particular" one you're searching, then you just select all the columns, or the ones you need.
$queryNodeRevision = "SELECT nid, col1, col2 FROM node_revision";
$results = mysqli_query($connection, $queryNodeRevision) or die("Bad Query: $results");
while ($row = mysqli_fetch_array($results)) {
if (condiiton) {
echo "Particular: ".$row['nid']
." ".$row['col1']
." ".$row['col2'];
}
}
condition could be something like $row['nid'] == 123 for example.
Hope it helps.

Using DISTINCT keyword with count in SQL Query

I have a page that is displaying a list of all company names (45 of them to be exact).
The database table has 43,815 results currently, so I only want to display them without duplicates (which is why I'm using the DISTINCT when I select) but I would also like to count how many results per company has and echo them out.
I'm tried using the count() as but it removes all the company results and just places the total (43,815).
My question is how would I display the companies using DISTINCT (because I don't want to have duplicates on the page) and then also echo out the total results of each company?
Any help is appreciated!
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT DISTINCT company FROM ads ORDER BY company ASC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
// Display the company name
echo $row["company"];
// I WOULD LIKE TO ECHO OUT HERE THE TOTAL OF EACH COMPANY HAS (COUNT) IN RESULTS!
}
} else {
echo "0 results";
}
$conn->close();
?>
I think that you should probably try to use the GROUP BY clause.
Without knowing your table markup try playing around with this:
$query = "SELECT
count(company) as count
FROM ads
GROUP BY company
ORDER BY company ASC"
Try:
SELECT
company,
COUNT(company)
FROM
ads
GROUP BY
company
ORDER BY
company
Use GROUP BY on your SELECT query, this should do what you are looking for, this will group all the same company's together and count them.
"SELECT COUNT(company) FROM ads GROUP BY company ORDER BY company ASC"

MySQL query with output to PHP page

I am trying to make simple page which will return values from MySQL table, but the problem is that if I want to use condotions in query then it doesn't work.
My PHP page:
<?php
$servername = "10.10.10.10";
$username = "username";
$password = "password";
$dbname = "GENERIC_TABLES";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT WO_NUM+1 from GENERIC_TABLES.WO_NUMBERS ORDER BY WO_NUM DESC limit 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> WO Number ". $row["WO_NUM"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
So, WO_NUM column has numbers like 1, 2, 3 etc.
I want to get the last one + 1
So if I do like:
$sql = "SELECT WO_NUM from GENERIC_TABLES.WO_NUMBERS ORDER BY WO_NUM DESC limit 1";
Then it works fine, but if I want to make it WO_NUM + 1 then it returns nothing.
Why it happens like that and is there any way to get what I want using MySQL?
I don't want to get WO_NUM and then using PHP make it + 1, since I also need INSERT to the table values and I would like to understand why it doesn't work.
As you realized, WO_NUM+1 changes the column name in the resulting array, so use an alias WO_NUM+1 as NEW_NUM. However I would not bother with the sorting and limit. Consider MAX():
SELECT max(WO_NUM)+1 as NEW_NUM from GENERIC_TABLES.WO_NUMBERS
As it has been pointed by AbraCadaver, I missed that if I am using WO_NUM + 1 then column name changing so that is why i didn't get any output, so using alias solved problem.

Replace value if exists in another query(table)?

So I am trying something totally new (for me). I have a PHP file where I try to retrieve the data of 2 tables and replace values if they match. Since I'm not really sure what I'm doing I'm kinda stuck:) Here is what i want:
I have 2 tables in my mysql database.
The table 'advertisement' has the column 'logo_fid'.
The table 'files' has the columns 'fid' and 'filepath'.
Now I would like to echo the values of the 'logo_fid' column in the 'advertisement' table.
Before that, however, I would like to see if in the table 'files' a corresponding value is stored in the 'fid' volumn and if so I would like to echo the value of 'filepath' instead of the value of 'logo_fid'.
So basically what I want is to replace the returned value of the logo_fid column, if this value matches with the value in the 'fid' column, with the corresponding 'filepath' value.
Hope I made myself clear. Anyway I have this code atm. Hope that anybody can help me out with this one. Thanks a lot!
<?php
//connection info xxxx
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//advertisement SELECT
$sql = "SELECT logo_fid FROM advertisement ORDER BY nid ASC";
$result = $conn->query($sql);
//advertisement SELECT
$sql2 = "SELECT fid, filepath FROM files";
$result2 = $conn->query($sql2);
if ($result->num_rows > 0 && $result2->num_rows > 0) {
// output data of each row
while(($row = $result->fetch_assoc()) && ($row2 = $result2->fetch_assoc())){
//So after i received all the info i'd like to check if the value of logo_fid matches with fid and if so replace the value with the value of filepath
if ($row["logo_fid"] == $row2["fid"]) :
echo $row2["filepath"];
else :
echo $row["logo_fid"];
endif;
echo '<br>';
}
} else {
echo "0 results";
}
$conn->close();
?>
Seems like this could be done as one query.
SELECT A.logo_Fid, F.Fid, F.filePath, coalesce(F.FilePath, Logo_Fid) as ValueYouWant
FROM advertisement A
LEFT JOIN files F
on A.logo_Fid = F.FID
Then you can echo ValueYouWant without the inline logic.
The join relates the two tables on the Fid and logo_fid.
if a match is found, Valueyouwant will contain the f.filepath, if no match is found logo_fid will be in valueyouwant.
Since this is using a LEFT join, all values from advertisement will be returned, and only related records from files will be returned.
so to display...
I don't do much PHP, but an online search that was accpted as an answer indicates it would be something like this...
$sql=" SELECT A.logo_Fid, F.Fid, F.filePath, coalesce(F.FilePath, Logo_Fid) as ValueYouWant
FROM advertisement A
LEFT JOIN files F
on A.logo_Fid = F.FID ORDER BY NID asc"
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo $row['ValueYouWant'];
echo '<br>';
}

PHP/MySQL: Match content of one table with another and print that instead

I have 2 tables, bs_reservations and bs_events. The first contains a bunch of IDs, the second both the (same) IDs and the corresponding titles. I'm trying to replace on-the-fly the IDs taken from first table with the corresponding titles, taken from the second table.
First table is bs_reservations which only has an eventID column. Here's the PHP code I use to fetch the IDs:
<?php
$servername = "localhost";
$username = "blabla";
$password = "blabla";
$dbname = "blabla";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM bs_reservations WHERE serviceID=3";
$result = $conn->query($sql);
if ($result->num_rows > 0) { echo "<table><tr><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["eventID"]. "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
The second table, bs_events has 2 columns, id and title. id corresponds to the same eventID of the first table, title is the corresponding title.
How can I modify the snippet above to match eventID from the first table with id of the second table and replace on-the-fly $row["eventID"] with the corresponding title?
Don't say to just use the second table as of course the first table has also other columns I'm fetching.
You can use the JOIN directive in your query:
$sql = "SELECT *
FROM `bs_reservations`
JOIN `bs_events` ON `bs_reservations`.`eventID` = `bs_events`.`id`
WHERE `bs_reservations`.`serviceID`=3";
You can then access the title attribute of each row just as if it was in the same table:
echo "<tr><td>" . $row["title"]. "</td></tr>";
Update:
If you need the events with no reservations yet as well, you can use a RIGHT OUTER JOIN:
$sql = "SELECT *
FROM `bs_reservations`
RIGHT OUTER JOIN `bs_events` ON `bs_reservations`.`eventID` = `bs_events`.`id`
WHERE `bs_reservations`.`serviceID`=3";
Use a join in your query.
SELECT r.*, e.title FROM bs_reservations as r JOIN bs_events as e on r.event_id = e.id WHERE r.serviceID = 3
Then in your loop you can echo the title. Assuming the reservations table doesn't have a title column, then you may want to rename it ..., e.title as eventTitle FROM ...
echo "<tr><td>" . $row["title"]. "</td></tr>";

Categories