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>';
}
Related
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.
I've just started learning PHP so this is quite a struggle for me, any help is appreciated!
So, I've managed to select my database, table and get data from it. But I need to select more data from the older columns.
Here is some of the code:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//execute the SQL query and return records
$result = mysqli_query($conn, "SELECT username FROM interview");
while($rowval = mysqli_fetch_array($result))
{
$username= $rowval['username'];
$username2= $rowval['username'];
$username3= $rowval['username'];
$username4= $rowval['username'];
}
?>
And I am displaying the data in a button, I want $username to display the first column and $username2 to display the second column etc...
I fetch the data using this code:
<?php echo $username; ?>
<?php echo $username2; ?>
<?php echo $username3; ?>
<?php echo $username4; ?>
Thanks!
I would suggest you re-factoring your "while" loop the following way for better scalability:
$usernames=array();
while($rowval = mysqli_fetch_array($result))
{
$usernames[] = $rowval['username'];
}
Then, you'll be able to access usernames like:
echo 'The first user name is: '.$usernames[0];
echo 'The second user name is: '.$usernames[1];
echo 'The third user name is: '.$usernames[2];
My php skills are a bit rusty, so take this with a grain of salt:
At first it is important to get the language right. A database table consists of rows and columns, the columns are the ones you select with the the part after the SELECT statement, if you write SELECT username what you select is the username column.
SELECT username FROM interview;
So if you want to select more columns from your table you have to put them in your SELECT statement. Let's say you want to select the username and the status of the interview, you would need to include the status in your SELECT statement like this:
SELECT username, status from interview;
Then you can access the interview status just like you did it with the username.
$result = mysqli_query($conn, "SELECT username, status from interview;");
while($rowval = mysqli_fetch_array($result))
{
$username= $rowval['username'];
$status = $rowval['status'];
}
Remember that what you get as the $rowVal is just a single row of your table. So if you want to collect all usernames and statuses from your table you have to use a datastructure to collect them.
$queryResult = mysqli_query($conn, "SELECT username, status from interview;");
$result = array();
while($rowval = mysqli_fetch_array($queryResult))
{
$username= $rowval['username'];
$status = $rowval['status'];
// With this action we build an array, that has each row's result as value.
$result[] = array('username' => $username, 'status' => $status);
}
To access the results you can then query the $result array like this:
// The interview status of the first entry in your table
$result[0]['status'];
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.
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.
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>";