I'm currently trying to link some databases up for a project I'm working on for my business. Here's my below SQL I'm using for my PHP website.
$sql = "SELECT lname, fname, designation, agency, mobile, direct, email FROM contacts";
$result = $conn->query($sql);
At the moment my output goes like this to show what's in each row using e.g. $lname=$lname["variable"]
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
/* Print the row */
echo "<tr>"."<td>". $lname . "</td><td>" . $fname . "</td><td>" . $designation . "</td><td>" . $agency . "</td><td>" . $mobile . "</td><td>" . $direct . "</td><td><a href='mailto:" . $email . "''>". $email. "</a><br>";
}
}
I have another "clients" table, where each agency has an id - one that matches with $agency at this point. What I want to do is post the corresponding companyname column to that id.
How would I modify my code to do so (and access the column/rows from the secondary table)?
If I've understood the question correctly, the answer should look something like
SELECT ct.lname, ct.fname, ct.designation, ct.agency, ct.mobile,
ct.direct, ct.email, cl.company_name
FROM contacts ct
JOIN clients cl ON ct.agency = cl.id
The crux of it is the SQL JOIN clause.
Related
This is my php code for displaying the table from mySQL workbench:
$stmt = $pdo->prepare(' SELECT jobs.*, categories.category_name
FROM jobs
LEFT JOIN vacancies.categories ON categories.category_id = jobs.category_id
WHERE jobs.category_id =:category_id');
$choice = 0;// just a temp for test
$criteria = [
'category_id' => $choice,
];
$stmt -> execute($criteria);
while ($row = $stmt->fetch()){
echo '<br>' . $row['id']. ' ' . $row['title']. ' ' . $row['salary']. ' ' . $row['location']. ' ' . $row['description']. '<br> category is:'.$row['category_name'].'</br>';
}
Now if I run this and check my webpage it only shows the jobs that hve the category_id of the $choice I put but I want to display all of the job table.
I have a category table with 6 categories (0 is the start) and in my other table that is called jobs. I have 7 jobs with their details.
I hope someone understand what I am trying to say and can help me out. Ask me anything if I don't give out enough.
You are using a prepared query to norrow the results to a defined criteria. If you want to display all the jobs you should simply remove the WHERE tag and use a simple query
$stmt = $pdo->query(' SELECT jobs.*, categories.category_name
FROM jobs
LEFT JOIN vacancies.categories ON categories.category_id = jobs.category_id');
echo '<table>';
while ($row = $stmt->fetch()){
echo '<tr><td>' . $row['id']. '</td><td>' . $row['title']. '</td><td>' . $row['salary']. '</td><td>' . $row['location']. '</td><td>' . $row['description'].'</td><td> category is:'.$row['category_name'].'</td></tr>';
}
echo '</table>';
I am using these two MySQL statements to get all messages between two users, but I am running into a pretty big problem when it comes to manipulating the data later in the code since it's not in order by ID. Is there any way to combine these statements AND order the results by ID?
$sql = "SELECT * FROM messages WHERE sender='" . $username . "' AND receiver='" . $chatPartner . "'"
$sqlTwo = "SELECT * FROM messages WHERE sender='" . $chatPartner . "' AND receiver='" . $username . "'"
Essentially, I need every occurrence of a message between two people, but sorted by ID. As of right now, I am joining the arrays to get my full list, but it's not in order by ID.
SELECT * FROM messages
WHERE (sender='" . $username . "' AND receiver='" . $chatPartner . "'")
OR (sender='" . $chatPartner . "' AND receiver='" . $username . "'")
ORDER BY id DESC
How about just combine both into 1 query ?
$sql = "SELECT * FROM messages WHERE (sender=" . $username . " OR sender =". $chatPartner .") AND (receiver=" . $chatPartner . " OR receiver=" . $username .") ORDER BY id"
You could also write a shorter version of #dtj's answer using row constructors.
SELECT *
FROM messages
WHERE (sender, receiver) IN (($username, $chatPartner),($chatPartner, $username))
ORDER BY id DESC
In my opinion it looks a bit nicer in code and makes it more readable, but remember that it doesn't improve performance of execution.
I have following code. With a single select query and an update query.It is working fine when i remove the update query. When i run following complete code then nothing happens.
Please help me I want to update table with every cycle of select query. Is there any way to execute following code.
$query = "SELECT * FROM ab_rec WHERE username='$userid'" or die(mysql_error());
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results
$t_name=$row['testname'];
$first_url=$row['first_url'];
$thanks_url=$row['thanks_url'];
$start_date=$row['start_date'];
$parse_first_url = parse_url($first_url); //parsing URL of first page for removing main domain name from it.
$parse_thanks_url = parse_url($thanks_url);
$final_first_url = $parse_first_url['path'] ; //Finally parsed URLs are stored into new variables
$final_thanks_url = $parse_thanks_url['path'] ;
$row['unique_visits'] = calculate_visitors($final_first_url, $start_date);
$row['conversions']= calculate_visitors($final_thanks_url, $start_date);
$row['conversion_percent'] = ($conversions/$unique_visits_first)*100;
$query1="UPDATE `ab`.`ab_rec` SET unique_visits=$row['unique_visits'], conversions=$row['conversions'] , conversion_percent=$row['conversion_percent'], WHERE testname=$row['testname'] " or die(mysql_error());
$result2=mysql_query($query1, $connection);
echo "<tr><td>" . $checkbox . "</td><td>" ."<a href='my_test.php?test_name=$t_name'>".$row['testname'] . "</a></td><td>" . $row['date_of_creation'] . "</td><td>" . $row['unique_visits'] . "</td><td>" . $row['conversions'] . "</td><td>" . $row['conversion_percent'] ."%". "</td></tr>"; //$row['index'] the index here is a field name
}
This:
$query1="UPDATE `ab`.`ab_rec` SET unique_visits=$row['unique_visits'],
conversions=$row['conversions'] , conversion_percent=$row['conversion_percent'],
WHERE testname=$row['testname'] " or die(mysql_error());
$result2=mysql_query($query1, $connection);
Should be:
$query1="UPDATE `ab`.`ab_rec` SET unique_visits=$row['unique_visits'],
conversions=$row['conversions'] , conversion_percent=$row['conversion_percent']
WHERE testname='{$row['testname']}'";
echo $query1; //POST THIS RESULT
$result2=mysql_query($query1, $connection) or die(mysql_error());
I'm learning PHP and Zend Framework. The following PHP function is supposed to fill a temporary table using "INSERT INTO ... SELECT" style query. However, when I SELECT * from the newly appended table, I see that most but not all of the new records have been duplicated once. I have deleted the contents of the table each time I run this scripts. Anyone know why there would be duplicates?
public function fillTableByOfficeName($officeName) {
if ($officeName != '') {
$officePhrase = "b.oof_name ='" . $officeName . "' AND ";
} else {
$officePhrase = '';
}
$whereAddenda = $officePhrase .
"a.fil_bool_will_file_online = false AND " .
"a.fil_bool_confirmed = false AND " .
"a.fil_bool_duplicate = false AND " .
"a.fil_bool_not_found = false AND " .
"(a.fil_res_id_fk NOT IN (4,7,10) OR a.fil_res_id_fk IS NULL) AND " .
"a.fil_will_recorder_rec_id IS NULL AND " .
"d.tag_description NOT IN (
'Already a trust client',
'Not received from local office',
'Southtrust client (already centralized)')";
//"a.fil_date_of_transfer_to_will_recorder IS NULL";
$sql = "INSERT INTO adds(fil_id,REC_ID,FIRST_NAME,LAST_NAME,MIDDLE_INITIAL,SSN," .
"MAILING_ADDRESS_1,MAILING_ADDRESS_2,CITY,STATE,ZIP_CODE,PHONE_NUMBER,BIRTH_DATE," .
"ORIGINATION_OFFICE,FILE_LOCATION,WILL_DATE,LAST_CODICIL_DATE,TRUST_DATE,REV_TRUST,POA_DATE) " .
"SELECT a.fil_id_pk, " .
"a.fil_will_recorder_rec_id, " .
"a.fil_first_name, " .
"a.fil_last_name, " .
"a.fil_middle_name, " .
"a.fil_ssn, " .
"a.fil_mailing_address_1, " .
"a.fil_mailing_address_2, " .
"a.fil_city_address, " .
"a.fil_state_address, " .
"a.fil_zip_code_fk, " .
"a.fil_phone_number, " .
"a.fil_date_of_birth, " .
"b.oof_name, " .
"a.fil_box_id_fk, " .
"a.fil_date_of_will, " .
"a.fil_date_of_last_codicil, " .
"a.fil_date_of_trust, " .
"a.fil_notes, " .
"a.fil_date_of_poa " .
"FROM files a, origination_offices b, nn_files_tags c, tags d " .
"WHERE " .
"a.fil_oof_id_fk = b.oof_id_pk AND " .
"a.fil_id_pk = c.fil_id_fk AND " .
"d.tag_id_pk = c.tag_id_fk AND " .
$whereAddenda;
$this->getAdapter()->query($sql);
return $this;
}
The way you are joining the table will give you the cartesian product of the rows from the tables (all pairs of matching rows are returned).
With no specific knowledge of the domain, I would guess at the tags table - if you've got multiple tags for a particular file, you will get multiple copies of the file in your result set (one per each matched tag).
As you're not using tags fields in the result set, just the where clause, the solution would be to get rid of tags / nn_files_tags from the main query, and in your where clause, use NOT EXISTS to check for matching rows in the tags table, something like:
AND NOT EXISTS (SELECT tag_id_pk FROM tags WHERE tags.tag_id_pk ...
You are using C for a many to many relationship. For example, if you have invoices between companies and customers and you select from join of them, you will get as many rows as you have invoices. From that, if you only select the company name and costumer name, you will have many duplicates because the same pair has produced many invoices.
This is the same issue you have here.
As asc99c said, you could use an inner select to make your WHERE clause without joining on that relationship or you could use the DISTINCT key word (which effectively is a group by on everything in your SELECT clause). I would think the INNER SELECT solution more efficient (yet I could be totally wrong about that), but the DISTINCT way is 8 key press away...
Total newbie trying to learn... thanks for all the help so far!
UPDATE - updated code below - Thanks Phill
I'm now trying to get the relevant horse information from a table horses which I can join to race_form with the horse_name field. I want to then display the information for each horse in the race below the while($racecard) info. Does this make it a bit clearer?
I thought I could just do another query and then a while loop with mysql_fetch_array below the one I have already and that would display it and then move onto the next race, but that apparently doesn't work...?!
I'm wondering if you can run 2 while loops after each other inside a while loop? I am working on a horse racing formguide - I can display each race list, but underneath I want to display individual horse details on each horse in the race. Anyway if you look at this page you can see what I'm trying to do:
http://tasmanianracing.com/superform/formguide.php?meetingID=21042011LAUN&Submit=View+Form
Problem is, any time I put a second while loop after the race list, it won't show up. I'm trying to run a query to get the horse details from my horse table and then run a while for each horse in the race, but nothing shows up.
I hope this is clear enough ... my snippet of code is below - please let me know if I've missed out something important:
echo "<table width='990' border='1' cellspacing='2' cellpadding='2'>";
$racedetails = mysql_query("SELECT *
FROM race_info
WHERE meetingID = ('" . $safemeetingID . "')");
while($row = mysql_fetch_array($racedetails))
{
echo "<tr><td>Race " . $row['race_number'] . " at " . $row['start_time'] . " " . $row['class'] . " over " . $row['distance'] . "m</td></tr>";
$racecard = mysql_query("SELECT *
FROM race_form
INNER JOIN race_info ON race_form.raceID = race_info.raceID
WHERE race_form.raceID = ('" . $row['raceID'] . "')");
while($row = mysql_fetch_array($racecard))
{
echo "<tr><td>" . $row['number'] . "</td><td>" . $row['past10'] . "</td><td>" . $row['horse_name'] . "</td></tr>";
}
echo "</table><br>";
echo "<br>I wish I could put in some horse form here...<br>";
echo "<table width='990' border='1' cellspacing='2' cellpadding='2'>";
}
echo "</table>";
You'll probably need to change the names of some of the $row variables, they may interfere with each other.
For example:
while($row_races = mysql_fetch_array($totalraces)){
while($row_details = mysql_fetch_array($racedetails)){
while($row_card = mysql_fetch_array($racecard)){
I think you can get rid of one of your queries:
The first query gets the number of races by selecting a COUNT, This returns one record with the count value.
// This returns one record with the count
$total_races = "SELECT COUNT(race_number) AS totalraces
FROM race_info WHERE meetingID = ('".$safemeetingID."') ";
Next you iterate over the the same records as the rows returned for the race details are the same as the count.
// This looks to return the record(s) with the race details
$race_details = "SELECT * FROM race_info
WHERE meetingID = ('" . $safemeetingID . "')";
I think you can just use this to get the desired results: (I agree to rename the $row variable(s) to something descriptive for each while loop)
$racedetails = mysql_query("SELECT *
FROM race_info
WHERE meetingID = ('" . $safemeetingID . "')");
while($details_row = mysql_fetch_array($racedetails))
{
echo "<tr><td>Race " . $details_row['race_number'] . " at " . $details_row['start_time'] . " " . $details_row['class'] . " over " . $details_row['distance'] . "m</td></tr>";
$racecard = mysql_query("SELECT *
FROM race_form
INNER JOIN race_info ON race_form.raceID = race_info.raceID
WHERE race_form.raceID = ('" . $details_row['raceID'] . "')");
while($rc_row = mysql_fetch_array($racecard))
{
echo "<tr><td>" . $rc_row['number'] . "</td><td>" . $rc_row['past10'] . "</td><td>" . $rc_row['horse_name'] . "</td></tr>";
}
echo "</table><br>";
echo "Testing<br>Testing<br>I wish I could put in some horse form here...<br>";
echo "<table width='990' border='1' cellspacing='2' cellpadding='2'>";
}
NOT TESTED/PSEUDO CODE
"SELECT *
FROM horses AS h,
INNER JOIN race_info AS ri ON race_form.raceID = race_info.raceID
WHERE horse_name IN (
SELECT horse_name
FROM race_form AS srf
WHERE h.horse_name = srf.horse_name
)
AND race_form.raceID = ('" . $details_row['raceID'] . "')"
The idea is to join the two queries into one, I know this is not the correct syntax but it might give you an idea on how to go about it.
Or you can do another query while loop for the horse names
$racedetails = mysql_query("SELECT *
FROM race_info
WHERE meetingID = ('" . $safemeetingID . "')");
while($details_row = mysql_fetch_array($racedetails))
{
echo "<tr><td>Race " . $details_row['race_number'] . " at " . $details_row['start_time'] . " " . $details_row['class'] . " over " . $details_row['distance'] . "m</td></tr>";
$racecard = mysql_query("SELECT *
FROM race_form
INNER JOIN race_info ON race_form.raceID = race_info.raceID
WHERE race_form.raceID = ('" . $details_row['raceID'] . "')");
while($rc_row = mysql_fetch_array($racecard))
{
echo "<tr><td>" . $rc_row['number'] . "</td><td>" . $rc_row['past10'] . "</td><td>" . $rc_row['horse_name'] . "</td></tr>";
$horses = mysql_query("SELECT *
FROM horses
WHERE horse_name = ('" . $rc_row['horse_name'] . "')");
while($horse_row = mysql_fetch_array($horses))
{
// echo horse details here
}
}
echo "</table><br>";
echo "Testing<br>Testing<br>I wish I could put in some horse form here...<br>";
echo "<table width='990' border='1' cellspacing='2' cellpadding='2'>";
}
I theory you could and in practice you can, but a while in a while in a for in a while seems a little bit over the top...
I'm sure we can help you make it more efficient if you explain what it is you're trying to do.