I have two tables job which contains an attribute called employer_id_job that links it to the employer table. I am able to display the contents of job in a table using PHP by using the following code
<?php
$query = "SELECT * FROM job";
$result = mysql_query($query);
$num = mysql_numrows($result);
$count = 0;
while ($count < $num)
{
$title = mysql_result ($result, $count, "Title");
$date_posted = mysql_result ($result, $count, "Date_posted");
$application_deadline = mysql_result ($result, $count, "Application_deadline");
$description = mysql_result ($result, $count, "Description");
$years_of_experience = mysql_result ($result, $count, "Years_of_experience");
$education_level = mysql_result ($result, $count, "Education_level_required");
$contract = mysql_result ($result, $count, "Contract_type");
$company = mysql_result ($result, $count, "Company_name");
?>
<tr>
<td><font face = "Arial, Helvetica, sans-serif"><? echo $count + 1; ?></font></td>
<td><font face = "Arial, Helvetica, sans-serif"><? echo $title; ?></font></td>
<td><font face = "Arial, Helvetica, sans-serif"><? echo $company; ?></font></td>
<td><font face = "Arial, Helvetica, sans-serif"><? echo $description; ?></font></td>
<td><font face = "Arial, Helvetica, sans-serif"><? echo $date_posted; ?></font></td>
<td><font face = "Arial, Helvetica, sans-serif"><? echo $application_deadline; ?></font></td>
<td><font face = "Arial, Helvetica, sans-serif"><? echo $education_level; ?></font></td>
<td><font face = "Arial, Helvetica, sans-serif"><? echo $years_of_experience; ?></font></td>
<td><font face = "Arial, Helvetica, sans-serif"><? echo $contract; ?></font></td>
<?
$count ++;
}
?>
My method here breaks down when trying to assign a value to the $company variable, which is held in the employer table. It was my assumption that simply using the same notation as for the rest of my variables would cause the script to follow the foreign key to the employer table and grab the attributes there, but it hasn't done that.
How should I go about accessing the contents of a table related via a foreign key?
select * from job as j, company as c where j.company == c.company
I'm not sure what then name of your fields are so I made my best guess. This allows you to access both fields.
Related
I'm trying to make a table that shows the results from a query of MySQL, but I'm having a hard time to get it right...
I had the PHP code to show the content of the database table with this script;
<?php
// Grab the data from our people table
$sql = "SELECT * FROM people ORDER BY ID";
$result = mysql_query($sql) or die ("Could not access DB: " . mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo "<div class=\"picture\">";
echo "<p>";
// Note that we are building our src string using the filename from the database
echo "<img src=\"content/uploads/" . $row['filename']
. "\" alt=\"\" height=\"125\" width=\"200\" /><br />" . "<br />";
echo $row['fname'] . " " . "<br />" . "<br />";
echo "</p>";
echo "</div>";
}
?>
but that of course doesn't have tables which is pretty ugly as it displays everything underneath each other... so I tried to make a table for it and after a lot of research I found a script which should have displayed the content but I can't seem to implement it into my own code and ended up with the error:
Could not access DB: No database selected
Using this code:
<?php
$sql="SELECT * FROM people ORDER BY ID";
$result=mysql_query($sql) or die ("Could not access DB: " . mysql_error());
$num=mysql_numrows($result);mysql_close();?>
<table border="0" cellspacing="2" cellpadding="2">
<tr>
<td>
<font face="Arial, Helvetica, sans-serif">Value1</font>
</td>
<td>
<font face="Arial, Helvetica, sans-serif">Value2</font>
</td>
</tr>
<?php
$i=0;while ($i < $row) {$f1=mysql_fetch_assoc($result,$i,"field1");
$f2=mysql_fetch_assoc($result,$i,"field2");
$f3=mysql_fetch_assoc($result,$i,"field3");
$f4=mysql_fetch_assoc($result,$i,"field4");
$f5=mysql_fetch_assoc($result,$i,"field5");?>
<tr>
<td>
<font face="Arial, Helvetica, sans-serif"><?php echo $f1; ?></font>
</td>
<td>
<font face="Arial, Helvetica, sans-serif"><?php echo $f2; ?></font>
</td>
</tr>
<?php
$i++;}
?>
Not sure what is going on here
mysql_fetch_assoc($result,$i,"field1")
Mysql_fetch_assoc only accepts one argument
The correct way to use it is as demonstrated in the php man page
while ($row = mysql_fetch_assoc($result))
{?>
<tr>
<td>
<font face="Arial, Helvetica, sans-serif"><?php echo $row['value1']; ?></font>
</td>
<td>
<font face="Arial, Helvetica, sans-serif"><?php echo $row['value2']; ?></font>
</td>
</tr>
<?php
}
If you had errors and warnings turned on, then you would get helpful error messages telling you what was wrong with your code. It is always recommended to turn them on for development.
My question is that I know there are many different way to do the same thing, but I would suspect that there is a "standard" for building tables from queries.
Looking at the 2 query/table combinations, which one is the more acceptable one?
Is there an even more standardized version of building a table from a query?
I would like to know a "best practices" way of doing this.
I created a query a while back:
$query1="select concat(sp.first_name,' ',sp.last_name)as 'Player Name',st.name as 'Team', spt_league_id as 'League', ss.Season_name
from stats_player sp
inner join stats_player_team stp,stats_team st, stats_season ss
where stp.player_num = sp.player_num and st.team_num=stp.team_id and ss.season_index=stp.season_id and stp.season_id=$this_season
order by st.League_id,st.Team_num,sp.player_num";
$result=mysql_query($query1);
$num=mysql_numrows($result);
mysql_close();
and then built the table with this:
?>
<table border="1" cellspacing="2" cellpadding="2">
<tr>
<td><font face="Arial, Helvetica, sans-serif"><b>Player</b></font></td>
<td><font face="Arial, Helvetica, sans-serif"><b>Team</b></font></td>
<td><font face="Arial, Helvetica, sans-serif"><b>League</b></font></td>
</tr>
<?php
$i=0;
while ($i < $num) {
$f1=mysql_result($result,$i,"Player Name");
$f2=mysql_result($result,$i,"Team");
$f3=mysql_result($result,$i,"League");
?>
<tr>
<td><font face="Arial, Helvetica, sans-serif"><?php echo $f1; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><?php echo $f2; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><?php echo $f3; ?></font></td>
</tr>
<?php
$i++;
}
?>
I then ran across code written by someone else:
$query= "select first_name,last_name,email_address,name,captain_id,paid,p.player_num,league_id from stats_player p left join stats_player_team t on p.player_num=t.player_num left join stats_team s on t.team_id=s.team_num where season_id=$this_season and name is not NULL order by league_id,s.captain_id,name,first_name";
$results=mysql_query($query);
print "<table border=1>";
print "<tr><td>First Name</td><td>Last Name</td><td>captain</td><td>Email?</td><td>League</td><td>Team</td><td>pay</td><td>wks played</td></tr>";
while ($row=mysql_fetch_assoc($results)){
if($row['email_address'] != NULL ){
$email='y';
}
else {
$email='n';
}
if($row[captain_id]==$row[player_num]){ $iscapt="Captain"; }
else{$iscapt="";}
$paid=$row[paid];
if($paid){$playpaid="<td bgcolor=#99ff33>paid</td>";}
else {$playpaid="<td bgcolor=#ff6633>not paid</td>";}
printf ("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></td><td>%s</td>%s \n</tr>",$row['first_name'],$row['last_name'],$iscapt,$email,$row['league_id'],$row['name'],$playpaid);
}
print "</table>";
Always try to SEPARATE the HTML code from PHP code unless you dont have a choice.It looks clumsy and will have difficulty in handling things in future. Moreover it will also take more time in loading the page.
Your first code is more preferable.
If the output is identical and the performance is identical, then the more readable code is "better".
However, the first does not output valid HTML5 or XHTML because it uses deprecated attributes that should be done through CSS. Aside from the global attributes, border is the only valid attribute for table elements; though even border should be done using CSS. The WHILE loop in the first should be done with a FOR loop.
The PHP in all blocks use the depreciated mysql_query, so they really aren't proper.
The SQL in the all blocks are obviously vulnerable to SQL injection; you should be using prepared statements, parameterized queries, or AT LEAST a mysql_real_escape_string.
At the moment my produces results from a database and then inserts all of the results into one HTML table.
Is there any way that it would be possible so that for each result returned it created an individual HTML table (opposed to all of the results going into one HTML table)
My code:
<table class=\"board\" width='100%' border='0' align='center' cellpadding='1' cellspacing='1'>
");
$type = $_GET["type"];
if ($type == "" || $type == "request") {
$get = mysql_query("SELECT * FROM request WHERE type='Request' AND deleted != 'yes' ORDER BY id DESC");
} else {
if ($type == "shoutout") {
$get = mysql_query("SELECT * FROM request WHERE type='Shoutout' AND deleted != 'yes' ORDER BY id DESC");
} else {
if ($type == "competition") {
$get = mysql_query("SELECT * FROM request WHERE type='Competition' AND deleted != 'yes' ORDER BY id DESC");
} else {
if($type == "all") {
$get = mysql_query("SELECT * FROM request WHERE deleted != 'yes' ORDER BY id DESC");
}
}
}
}
$num = #mysql_num_rows($get);
if ($num == 0) {
echo ("<div class=\"board\"><center><font color=\"red\">There aren't any requests in this category!<br />
Why not ask listeners to send in their requests?</font></center></div>");
} else {
while ($r = mysql_fetch_array($get)) {
echo "
<tr>
<td><font face=\"verdana\" size=\"1\"><b>User</b></td>
<td><font face=\"verdana\" size=\"1\"><b>$r[habboname]</b></td>
</tr>
<tr>
<td><font face=\"verdana\" size=\"1\"><b>Date</b></td>
<td><font face=\"verdana\" size=\"1\">$r[date]</td>
</tr>
<tr>
<td><font face=\"verdana\" size=\"1\"><b>IP</b></td>
<td><font face=\"verdana\" size=\"1\">$r[ip]</td>
</tr>
<tr>
<td><font face=\"verdana\" size=\"1\"><b>Message</b></td>
<td><font face=\"verdana\" size=\"1\">$r[message]</td>
</tr>
<tr>
<td><font face=\"verdana\" size=\"1\"><b>Type</b></td>
<td><font face=\"verdana\" size=\"1\">$r[type]</td>
</tr>
<tr>
<!-- <td><font face=\"verdana\" size=\"1\"><b>Refferer</b></td>
<td><font face=\"verdana\" size=\"1\">";
if($r[refferer] == 1){ echo "Site.com</td>"; } else { echo "Site1.com</td>"; }
echo "--></tr>
<tr>
<td><font face=\"verdana\" size=\"1\"><b>Commands</b></td>
<td><font face=\"verdana\" size=\"1\">Delete - Ban - <!--Alert-->Nominate LoTW</font></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
";
$id = htmlspecialchars($_GET['id']);
$delete = mysql_query("UPDATE request SET deleted = 'yes' WHERE id = '$id'");
}
echo ("</table></div>");
}
break;
case 'delete':
If you mean to create as many tables as there are returned rows, just put the opening <table> into the while's beginning and the closing </table> to the end of while. However, I don't understand why this would be desired. Do you really want to create many tables with just one row? It kind of defeats the purpose of a table. Make a list or use span's or anything else than tables instead.
while ($r = mysql_fetch_array($get)) {
echo "<table class=\"board\">
<tr>
<td><b>User</b></td>
<td><b>$r[habboname]</b></td>
</tr>
<tr>
<td><b>Date</b></td>
<td>$r[date]</td>
</tr>
<tr>
<td><b>IP</b></td>
<td>$r[ip]</td>
</tr>
<tr>
<td><b>Message</b></td>
<td>$r[message]</td>
</tr>
<tr>
<td><b>Type</b></td>
<td>$r[type]</td>
</tr>
<tr>
<!-- <td><b>Refferer</b></td>
<td>";
if($r[refferer] == 1){ echo "Site.com</td>"; } else { echo "Site1.com</td>"; }
echo "--></tr>
<tr>
<td><b>Commands</b></td>
<td>Delete - Ban - <!--Alert-->Nominate LoTW</font></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>";
$id = htmlspecialchars($_GET['id']);
$delete = mysql_query("UPDATE request SET deleted = 'yes' WHERE id = '$id'");
}
echo "</div>"; //remove () after echo
Update. One another thing. Please don't use inline styling. You have table class="board" so you already probably know the power of CSS.
Second update. I removed <font ...> tags. Use CSS for example like this:
table.board{
width:100%;
border:0;
align:center;
cellpadding:1;
cellspacing:1;
}
table.board td{
font-family: Verdana, Geneva, Arial, sans-serif;
font-size: 1em;
}
CSS saves a lot of trouble when you want to change styling. And trust me, there will be a time when you want to change it (or your boss want's to bling-bling the site...).
ZZ-bb is absolutely right and as a hint try to put if/else construction in mysql - it will move faster or optimize it in php, like:
$get = mysql_query("SELECT * FROM request WHERE " . ($type == 'all' ? 'type = 1' : 'type = ucfirst($type)' ) . " AND deleted != 'yes' ORDER BY id DESC");
I'm exporting some data from MySQL which can be selected through checkboxes on a page to a .txt file.
Now I have a function to "black out" middle digits of the numbers from MySQL, this function is working on my page, there it looks like this:
<?php
$sql="SELECT * FROM table";
$result=mysql_query($sql);
// Count table rows
$count=mysql_num_rows($result);
?>
<?php function blankit($word) {
return substr($word, 0,2). str_repeat("X",strlen($word)-4) . substr($word, strlen($word)-2,strlen($word));
}
?>
<?php while($rows=mysql_fetch_array($result, MYSQL_ASSOC)) {
$code = ($rows['used'] == '') ? blankit($rows['code']) : $rows['code']; ?>
<tr class="first">
<td class="tc"><font face="Arial, Helvetica, sans-serif"><? echo $rows['id']; ?></font></td>
<td class="tc"><font face="Arial, Helvetica, sans-serif"><? echo $code; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><? echo $rows['date']; ?></font></td>
<td class="tc"><font face="Arial, Helvetica, sans-serif"><? echo $rows['ip']; ?></font></td>
<td class="tc"><font face="Arial, Helvetica, sans-serif"><? echo $setusedpscde; ?></font></td>
<td class="tc"><input name="checkbox[]" type="checkbox" class="checkbox" id="checkbox[]" value="<? echo $rows['id']; ?>"></td>
</tr>
<?php
}
?>
Now I want to apply this same function (blankit) when I export to the .txt file, my export code:
<?php
if ($_POST['exporttxt']) {
for($i=0;$i<count($_POST['checkbox']);$i++){
$export_id = $checkbox[$i];
$text = mysql_query("SELECT code FROM table WHERE id='$export_id'");
$text2 = mysql_fetch_assoc($text);
$text3 = $text2["code"];
$filename = "export";
$filedate = date("Y-m-d");
$fileext = ".txt";
$fileall = $filename.$filedate.$fileext;
ob_end_clean();
header("Content-Type: application/octet-stream");
header("Content-disposition: attachment;filename=\"$fileall\"");
header("Content-Type: application/force-download");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: ".strlen($output).";\n");
echo chunk_split($text3, 16, "\n");
}
}
?>
I tried changing
$text3 = $text2["code"];
to
$text3 = ($text2['used'] == '') ? blankit($text2['code']) : $text2['code'];
But this X'ed out all the middle digits of every number, even if used was not =''
What do I have to change here ?
The problem is that for 1st query you selected all columns and in 2nd only the code column
$text = mysql_query("SELECT code FROM table WHERE id='$export_id'");
In that case, $text2['used'] == '' is always true as the value is null. You have to add 'used' column
$text = mysql_query("SELECT used, code FROM table WHERE id='$export_id'");
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Is there some way to store:
A visitor's IP Address
What time a visitor visited my site
How many times they visited
I know there is a way to do this without PHP, just with Javascript and some text files.
How it would I do this in PHP?
It's a very easy task.
You can do this with the help of php. You can get many types of information about client visiting your site. You can get to know about the ip address, date, time, operating system, browser, isp of that ip address and many more things. You will have to use php and mysql !
firstly create a table in mysql.
create_table_track.php
<?php
$server = "localhost";
$username = "username";
$password = "password";
$database = "database name";
$connId = mysql_connect($server,$username,$password) or die("Cannot connect to server");
$selectDb = mysql_select_db($database,$connId) or die("Cannot connect to database");
$result = "CREATE TABLE track(
`id` int(6) NOT NULL auto_increment,
`tm` varchar(20) NOT NULL default '',
`ref` varchar(250) NOT NULL default '',
`agent` varchar(250) NOT NULL default '',
`ip` varchar(20) NOT NULL default '',
`ip_value` int(11) NOT NULL default '0',
`domain` varchar(20) NOT NULL default '',
`host_name` varchar(20) NOT NULL default '',
`tracking_page_name` varchar(10) NOT NULL default '',
UNIQUE KEY `id` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 ";
if (mysql_query($result))
{
print "Success in TABLE creation!......";
}
else
{
die('MSSQL error: ' . mssql_get_last_message());
}
?>'
This is the first part of getting the information about client.
This file will create a table named "track" in mysql database.
Now to store information in this table, you will have to create another file.
example.php
<html>
<?php
// fill in your databasa data here!
$server = "localhost";
$username = "username";
$password = "password";
$database = "database name";
$connId = mysql_connect($server,$username,$password) or die("Cannot connect to server");
$selectDb = mysql_select_db($database,$connId) or die("Cannot connect to database");
$tracking_page_name="example";
$ref=$_SERVER['HTTP_REFERER'];
$agent=$_SERVER['HTTP_USER_AGENT'];
$ip=$_SERVER['REMOTE_ADDR'];
$host_name = gethostbyaddr($_SERVER['REMOTE_ADDR']);
$strSQL = "INSERT INTO track(tm, ref, agent, ip, tracking_page_name, host_name) VALUES(curdate(),'$ref','$agent','$ip','$tracking_page_name','$host_name')";
$test=mysql_query($strSQL);
?>
</html>
Now the above file will extract information from client computer and store it in the database.
Now to show the information stored in database,, we wil use following file---
show track.php
<html>
<body>
<?php
$con = mysql_connect("localhost","user name","password");
mysql_select_db("database name", $con) or die( "Unable to select database");
$query="SELECT * FROM track";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
?>
<table border="1" cellspacing="2" cellpadding="2">
<tr>
<th><font face="Arial, Helvetica, sans-serif">id</font></th>
<th><font face="Arial, Helvetica, sans-serif">time</font></th>
<th><font face="Arial, Helvetica, sans-serif">http referer</font></th>
<th><font face="Arial, Helvetica, sans-serif">user agent</font></th>
<th><font face="Arial, Helvetica, sans-serif">ip address</font></th>
<th><font face="Arial, Helvetica, sans-serif">ip value</font></th>
<th><font face="Arial, Helvetica, sans-serif">domain</font></th>
<th><font face="Arial, Helvetica, sans-serif">tracking_page_name</font></th>
<th><font face="Arial, Helvetica, sans-serif">Host_name</font></th>
</tr>
<?php
$i=0;
while ($i < $num) {
$f1=mysql_result($result,$i,"id");
$f2=mysql_result($result,$i,"tm");
$f3=mysql_result($result,$i,"ref");
$f4=mysql_result($result,$i,"agent");
$f5=mysql_result($result,$i,"ip");
$f6=mysql_result($result,$i,"ip_value");
$f7=mysql_result($result,$i,"domain");
$f8=mysql_result($result,$i,"tracking_page_name");
$f9=mysql_result($result,$i,"host_name");
?>
<tr>
<td><font face="Arial, Helvetica, sans-serif"><?php echo $f1; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><?php echo $f2; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><?php echo $f3; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><?php echo $f4; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><?php echo $f5; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><?php echo $f6; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><?php echo $f7; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><?php echo $f8; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><?php echo $f9; ?></font></td>
</tr>
<?php
$i++;
}
?>
</body>
</html>'
There's no way to store anything on a client computer using pure javascript. It runs in a sandboxed environment that doesn't allow you to perform such tasks. You could send an AJAX request to a server side script that will perform the necessary steps to persists the data. Another option of course is to use some service like Google Analytics which will take care of persisting statistics about your site visits by including a simple script at the end of your pages.
as he said WITHOUT PHP!! (only textfiles) i would prefer using jsonp with a callback function and a webservice like ip-api.com or ipinfo.io
function fire() {
var url = "http://ipinfo.io/json?callback=func";
var script = document.createElement('script');
script.src = url;
script.async = true;
document.getElementsByTagName('head')[0].appendChild(script);
}
function func(response) {
alert(response.hostname); // for example hostname
}
document.onload = fire();
instead of response.hostname you can alert everything what the service gives you back like
{
"ip": "178.165.128.3",
"hostname": "178.165.128.3.wireless.dyn.drei.com",
"city": null,
"region": null,
"country": "AT",
"loc": "47.3333,13.3333",
"org": "AS12635 Hutchison Drei Austria GmbH"
}
the time you can get by
var d = new Date();
var n = d.getTime();
and the count how often visitor cames i would store in local storage..
you will need some kind of server side processing if you want to write to files on the server.
if you want client-side storage, it is a relativley new feature (HTML5), but doesn't allow access to the filesystem directly.
In PHP, If I understand what you are trying to do, what you are trying to accomplish is very easy.
To get the visitors IP Address, you would simply use the $_SERVER superglobal, like so:
<?php $_SERVER['ip_address']; ?>
Then, to get the time, you would simply use:
<?php time(); ?>
Now, the slightly more tricky part, how many times they visited. You need to put the above into a database, e.g. mysql.
Create a database schema, with the following columns: id, ipAddress, time and numOfVisits.
You would need to have some php logic at the start of your webpage to check if the users IP Address is already in the database, and if it is, increment the numOfVisits column. You would obviously need to log the output of time() into the time column also.
In essence, that's how you would do what you are asking in PHP.
Hope this helped :)