Reference child table with a main table - php

In my database I have a jobs table which you can say is the main table in my database. I have a column called category and this column points to a table called category which holds different categories.
Picking up the concept of foreign keys,I made turned the column categories into a foreign key, which looks at the categories table.
In my categories table I make sure it points to the ID.
When I run my webpage it prints out the value 1 in the category column, when in theory should it not print "Driving"?
function getJobDetails($job,$cat){
//this connects to the database
include "connectToDatabse.php";
//show me the results from job, where category is like cat vice versa
$results = $pdo->query("SELECT * FROM job WHERE category LIKE '$cat%' OR title LIKE '$job'");
$str = "<table>"; //prints out table
$str .= "<td>" ."Title" . "</td>"; //first row
$str .= "<td>" ."Reference" . "</td>"; //N row...
$str .= "<td>" ."Salary(£)" . "</td>";
$str .= "<td>" ."Description" . "</td>";
$str .= "<td>" ."Category" . "</td>";
foreach ($results as $row) {
$ref = $row['reference'];
$link = "<form method='get' action='apply.php' name='edit'>
<input type='hidden' name='referenceNumber' value='$ref'>
<input type='submit' value='$ref'>
</form>";
$str .= "<tr>";
$str .= "<td>" . $row['title'] . "</td>";
$str .= "<td>" . $row['reference'] . "</td>";
$str .= "<td>" . $row['salary'] . "</td>";
$str .= "<td>" . $row['description'] . "</td>";
$str .= "<td>" . $row['category'] . "</td>";
$str .= "<td> " .$link . "</td>";
$str .= "</tr>";
}
$str .= "</table>";
echo $str;
}
The above code is a function that returns the data in the job table.
Edit: referring to the question, since the categories column is pointing to the category table, should it not refer the data back to the job table?

No it shouldn't. You're missunderstanding foreign-keys. They do not change the data you get, they only tell the database system 'hey, this references somthing else, if this other entry gets updated or deleted, please do X (update, delete, ...) with this entry here'. You'd still need a join to get the expected result:
SELECT ..., category.title FROM job LEFT JOIN category ON category.id = job.category

Related

How to escape SELECT COUNT (*) and create a table

I am fairly new to working with PHP and WordPress. I tried exploring how to escape and sanitize, and I got a little confused along the way.
I'd like to echo out the contents of an entire table from the database. I am unsure whether there is a better way of both creating a table in a more structured way, and I can't figure out how to escape the data when I don't select specific data from the database. Maybe i'm just confused. Any help or pointers is highly appreciated.
I found the code somewhere on Stack Overflow, edited a little and tried to understand it. I understand it now, but I am still confused on where to go from here.
<?php
$results = $wpdb->get_results( "SELECT * FROM user"); // Query to fetch data from database table and storing in $results
if(!empty($results)) // Checking if $results have some values or not
{
echo "<table width='100%' border='0' id='userTable'>"; // Adding <table> and <tbody> tag outside foreach loop so that it wont create again and again
echo "<tbody>";
echo "<tr>"; // Adding rows of table inside foreach loop
echo "<th>E-mail</th>" . "<th>Fornavn</th>" . "<th>Efternavn</th>" . "<th>Registreret den</th>";
echo "</tr>";
foreach($results as $row){ //putting the user_ip field value in variable to use it later in update query
echo "<td colspan='3'><hr size='2'></td>";
echo "<tr>";
echo "<td>" . esc_attr($row->email) . "</td>" . "<td>" . $row->firstname . "</td>" . "<td>" . $row->lastname . "</td>" . "<td>" . $row->signuptime . "</td>"; //fetching data from user_ip field
}
echo "</tbody>";
echo "</table>";
}
?>
This part...
foreach($results as $row){
//putting the user_ip field value in variable to use it later in update query
echo "<td colspan='3'><hr size='2'></td>";
echo "<tr>";
echo "<td>" . esc_attr($row->email) . "</td>" . "<td>" . $row->firstname . "</td>"
. "<td>" . $row->lastname . "</td>" . "<td>" . $row->signuptime . "</td>";
//fetching data from user_ip field
}
...would product html like
{3 columns}{content}{3 columns end}{row start}
{column start}{content}{column end} * 4
{3 columns}{row start}
{column start}{content}{column end} * 4
{3 columns}{row start}
{column start}{content}{column end} * 4
etc
What you want in your loop is probably:
{row start}{4 columns}{content}{4 columns end}{row end}
{row start}{column start}{content}{column end} * 4{row end}
which would look like this:
foreach($results as $row){
//putting the user_ip field value in variable to use it later in update query
echo "<tr><td colspan='4'><hr size='2'></td></tr>";
echo "<tr><td>" . esc_attr($row->email) . "</td>" . "<td>" . $row->firstname . "
</td><td>" . $row->lastname . "</td>" . "<td>" . $row->signuptime . "</td></tr>";
//fetching data from user_ip field
}
In your SQL-statement on your first row: SELECT * FROM user , all fields are returned into the $results array of objects. If you want to specify which fields are returned you simply include them instead of the *, e.g. SELECT id, email, firstname, lastname FROM user

Filtering MySQL Database by field result

I am pulling stock data off of a trading API through a loop based on an aray of stock symbols. This spits out xml data which I then parse and input into a MySQL database for analysis later. This is an example of the fields I'm inserting into the database (I can add more):
$sql = "INSERT into securities (symbol, ask, ask_time, asksz)
VALUES ('$symbol', '$ask', '$ask_time','$asksz')";
My current query pulls all of the data and lists it in rows, entry after entry into a table:
$sql = "SELECT id, symbol, ask, ask_time, asksz FROM securities";
if($result = mysqli_query($conn, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>symbol</th>";
echo "<th>ask</th>";
echo "<th>ask_time</th>";
echo "<th>asksz</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['symbol'] . "</td>";
echo "<td>" . $row['ask'] . "</td>";
echo "<td>" . $row['ask_time'] . "</td>";
echo "<td>" . $row['asksz'] . "</td>";
echo "</tr>";
}
echo "</table>";
Is there a way to compare two separate stocks side by side? For instance, structure my query in order to pull those 4 fields only for 'AAPL', then in the same row pull the same data for 'GOOG'?

Read More Button

I have the below table in my site...
and what I want is that when i click on the read more link to redirect me to the page view_announcement.php and in this page to display me the whole data for this specific row.
For example, if we click on the link in the second row I want in the view_announcement.php to load all the data for this specific row.
My code in order to display this table is this...
<?php
$q = ($_GET['q']);
$con = mysqli_connect('localhost','root','smogi','project');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"project");
$sql="SELECT author,category,subject,content FROM announcements WHERE category = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>Author</th>
<th>Category</th>
<th>Subject</th>
<th>Content</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['author'] . "</td>";
echo "<td>" . $row['category'] . "</td>";
echo "<td>" . $row['subject'] . "</td>";
echo "<td>" . 'Read More' . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
The view_announcement.php file doesn't contain any code yet because i dont know what to write.
One way to do it is to append a query variable to the "Read More" links. You'll probably need a unique identifier, such as an ID number, on your announements table. If you don't have one yet, I suggest adding one and setting it up to auto-increment.
You would want to modify your query to include the unique ID number:
$sql="SELECT id,author,category,subject,content FROM announcements WHERE category = '".$q."'";
Then you would modify the loop which prints your table out to include those unique IDs in the URL to view_announcement.php
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['author'] . "</td>";
echo "<td>" . $row['category'] . "</td>";
echo "<td>" . $row['subject'] . "</td>";
echo "<td>" . 'Read More' . "</td>";
echo "</tr>";
}
And in your file view_announcement.php, you would make another SQL query to get the full data for a specific row, like this:
$sql="SELECT * FROM announcements WHERE ID = '".$_GET['id']."'";
If you click any button, that redirects to view_announcement.php file, where you can get the subject values.
Use that subject values in your query to get all the details which relates to that subject.

Accessing multiple sql files in one php document

I am trying to be able to access multiple dates and be able to map them to one player, and one country. The multiple years are in one table on the database, this table then uses foreign keys to attach the other two tables (player, country). How can access all of the years that the one individual won without adding it as a separate table?
below is my sql and php.
Many thanks in advance
$sql = "SELECT w.year, p.wikilink, c.countryname, c.countrylink, c.region, c.regionlink, p.playername, c.flag
FROM worldchampionperiod AS w
LEFT JOIN country AS c
ON w.Country_idcountry = c.idcountry
LEFT JOIN player AS p
ON w.player_idplayer = p.idplayer
GROUP BY p.idplayer
ORDER BY year";
$result = $conn->query($sql);
if ($result->rowCount() > 0) {
// output data of each row
while($row = $result->fetch()) {
echo "<tr>";
// echo "<td>" <a href=$row[""]>delete</a>. $row["playername"] . "</td>";
echo "<td>" . $row["playername"] . "</td>";
echo "<td>" . $row["year"] . "</td>";
//echo "<td>" . $row["countryname"] . <a href="'. $row["countrylink"] .'"> . "<br>" . $row["region"] . '<a href="'. $row["regionlink"] .'">' "</td>";
echo "<td>". ''. $row["countryname"].'' ."<br>" . ''. $row["region"].'' . "<br>" . '<img src="' .$row["flag"].'"width=30px>' . "</td>"; "</td>";
echo "</tr>";

How to put a break in the output when specific values change using mysqli php

I am building a website to list statistics for bowling tournaments over the last 24 years. Using the following code generates a long, single table showing all the data. I would like to put a break in the table when the $row['season'] value changes, i.e., from 1990-1991 to 1991-1992, and for each subsequent change of seasons and echo either an html horizontal line between seasons or put the value of the season from the database, i.e., 2013-2014 at the top of each table segment. After a week of searching the web haven't figured out an answer. Here's the code I have now. Needs to be mysqli.
$result = mysqli_query($conn,"SELECT * FROM members INNER JOIN scores ON members.id=scores.memberID WHERE format LIKE '%s%' ORDER BY year, STR_TO_DATE( month, '%b' ), format ASC;");
echo "<table border='0'>
<tr>
<th>Name</th>
<th>Hometown</th>
<th>Month</th>
<th>Year</th>
<th>Season</th>
<th>Center</th>
<th>Center City</th>
<th>Format</th>
</tr>";
foreach($result as $row) {
echo "<tr>";
echo "<td>" . $row['firstName'] . " ". $row['lastName'] . "</td>";
echo "<td>" . $row['hometown'] . "</td>";
echo "<td>" . $row['month'] . "</td>";
echo "<td>" . $row['year'] . "</td>";
echo "<td>" . $row['season'] . "</td>";
echo "<td>" . $row['center'] . "</td>";
echo "<td>" . $row['centerCity'] . "</td>";
echo "<td>" . $row['format'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($conn);
The answer is actually already given but it looks like your new with php so here is a smal example i hope its useful to you.
You need to insert some if statements to check if there is any change of year. same goes for any other checks you want to perform.
this is something you could do...
<?php
$lastYear = null;//you can also set the first year manually of course
foreach($result as $row) {
//set the first year
if($lastYear == null){$lastYear = $row['year'];}
//check if the year changed or not
if($lastYear == $row['year']){
//if the year didnt change... do something
}else{
//your year changed... do something different
$lastYear = $row['year']; //update your 'last'year
}
}
?>
I hope this will help you.

Categories