I have a BusinessID in both my staff and business table and I'm wanting to display the staff members for everyone in a particular business. The query below gives me this error.
ERROR: Could not able to execute SELECT * FROM business b inner join BusinessID b ON b.BusinessID = s.BusinessID WHERE b.BusinessID = 1. Not unique table/alias: 'b'
This is my foreign key file
<html>
<body>
<?php
include_once("connect.php");
$BusinessID = $_GET['BusinessID'];
$sql= "SELECT *
FROM business b
inner join BusinessID b
ON b.BusinessID = s.BusinessID
WHERE b.BusinessID = $BusinessID";
if($result = $conn->query($sql)){
if($result->num_rows > 0){
echo "<table>";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>BusinessID<th>";
echo "</tr>";
while($row = $result->fetch_array()){
echo "<tr>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['BusinessID'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
$result->free();
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . $conn->error;
}
// Close connection
$conn->close();
?>
</body>
</html>
Below is the fix
$sql= "SELECT *
FROM staff
WHERE BusinessID = $BusinessID";
You need to use a join statement
Select *
From staff as S
Join business as B
on s.businessID=b.businessID
--Where clause <--- If you want to filter by anything.
You say you "have a BusinessID". If it were in $BusinessID, the form of query you want seems to be:
query select * from staff where s.BusinessID = $BusinessID
However be warned of SQL code injection as addressed at How can I prevent SQL injection in PHP? (See also the coincidental meta post from today Should the answer be the simplest ever possible, even at the expense of quality/security?) The correct way to deal with this in a PHP context is to query via prepared statements.
Related
I want to fetch data with AM/PM format, but before that, i need to choose a database to make this.
$event_name='database_name';
I also using INNER JOIN .
Can anybody know how to format time in this case?
$event_name='database name';
$conn = mysqli_connect($servername, $username, $password);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());}
$sql = "SELECT $event_name.student_login.LOG_IN, $event_name.student_login.TIME_FORMAT(LOG_IN,"%r"), event_attendance.student_data.* FROM event_attendance.student_data
inner JOIN $event_name.student_login ON $event_name.student_login.SERIAL = event_attendance.student_data.SERIAL order by $event_name.student_login.LOG_IN DESC";
//using (SERIAL)
$result = mysqli_query($conn, $sql);
$i = 1;
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<td width='2'><center><B>".$i; $i++; echo"</B></center></td>";
echo "<td>" . $row["ID"]."</td>";
echo "<td>" . $row["LASTNAME"].", ". $row["FIRSTNAME"]." ". $row["MIDDLENAME"]."."."</td>";
echo "<td><center>" . $row["COURSE"]."</center></td>";
echo "<td><center>" . $row["YEAR"]."</center></td>";
echo "<td><center>" . $row["LOG_IN"] ."</center></td>";
echo "<td><center>" . $row["DATE"]."</center></td><tr>";
}
}
my code didn't work with this.
$event_name.student_login.TIME_FORMAT(LOG_IN,"%r")
TIME_FORMAT is an in-built MYSQL function and not a function of the table $event_name.student_login so using $event_name.student_login.TIME_FORMAT(LOG_IN,"%r") is wrong
Secondly, your query is in double quotes so you cannot directly use another double quote in the query string. So you need to change $event_name.student_login.TIME_FORMAT(LOG_IN,"%r") to TIME_FORMAT($event_name.student_login.LOG_IN, '%r')
Try this
$sql = "SELECT $event_name.student_login.LOG_IN, TIME_FORMAT($event_name.student_login.LOG_IN, '%r'), event_attendance.student_data.* FROM event_attendance.student_data inner JOIN $event_name.student_login ON $event_name.student_login.SERIAL = event_attendance.student_data.SERIAL order by $event_name.student_login.LOG_IN DESC";
or the cleaner version using alias
$sql = "SELECT sl.LOG_IN, TIME_FORMAT(sl.LOG_IN, '%r'), sd.* FROM event_attendance.student_data sd inner JOIN $event_name.student_login sl ON sl.SERIAL = sd.SERIAL order by sl.LOG_IN DESC";
I have 3 tables, members, teams & team_members.
team_members houses the ids from both the members & teams and stores them per row.
The schema of theteam_members table:
teams table:
What I'd like to be able to do is create a join where i can output the team_name from the teams table and then underneth show the members_firstname associated with that that team. So example:
Team 1
joe bloggs
jon doe
Team 2
charlie chaplin
hulk hogan
My php code looks like this:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$sql = "SELECT t.team_name, group_concat(m.firstName)
FROM members AS m
JOIN team_members AS tm
ON tm.member_id = m.member_id
JOIN teams as t
on t.team_id = tm.team_id
GROUP BY t.teamname";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo $row["member_id"] . '<br>';
echo $row["team_id"] . '<br><br>';
}
}
?>
Now I get:
Notice: Trying to get property of non-object in -- on line 30 which is:
if($result->num_rows > 0){
You should use two joins to piece together the three tables.
SELECT t.team_name as team_name, group_concat(m.firstName) as team_members
FROM members AS m
JOIN team_members AS tm
ON tm.member_id = m.member_id
JOIN teams as t
on t.team_id = tm.team_id
GROUP BY t.team_name
You then should check the status of your query before trying to work with it.
if(!$result = $conn->query($sql)) {
die(printf("Errormessage: %s\n", $conn->error));
}
Then loop through the results, and split the grouped values by the comma.
while($row = $result->fetch_assoc()){
echo $row["team_name"] . '<br>';
$names = explode(',', $row['team_members']);
foreach($names as $name) {
echo $name . '<br>';
}
echo '<br>';
}
You also could use <br> as the separator in the group_concat. You can read more about that function here, http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat. If you did that you can get rid of the foreach and explode because the $row['team_members'] would be built with a linebreak for each member.
The easy way to do this in PHP is width two nested loops in first you go trought the team table and print it in the second you print all the playes width theat team id...
Something like:
do{
echo $row_team;
do{
echo $row_playa;
}while($row_plya = mysql_fetch_assoc($playas)); // whear pleya.team_id = $row_team.id
}while($row_team = mysql_fetch_assoc($teams));
I cannot figure out why this sql query isn't working and why it doesn't filter by the keyword coming from URL.
Here is my code:
include("menujednoty.php");
$hostname="localhost";
$username="kintrogorgo";
$password="password";
$keyword = $_GET['a.tovar'];
$db = "jednoty";
$dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password);
foreach($dbh->query ('SELECT a.tovar ,
( select sum(b.kusy) from jednotypredaj as b where b.tovar=a.tovar and b.co="prijem" ) as prijem_ks,
( select sum(c.kusy) from jednotypredaj as c where c.tovar=a.tovar and c.co="predaj" ) as predaj_ks, kod
FROM jednotypredaj WHERE
(a.tovar LIKE '%$keyword%' ) as a GROUP BY a.tovar ORDER by a.tovar ASC') as $row)
{
echo "<tr>";
echo "<td>" . $row['tovar'] . "</td>";
echo "<td>" . $row['prijem_ks']. "</td>"; //Tu by mali bit predane kusy
echo "<td>" . $row['predaj_ks'] . "</td>";
echo "<td>" . $row['kod'] . "</td>";
echo "<td>" . ($row['predaj_ks']-$row['prijem_ks'] . "</td>");
echo "<td>" . (100/$row['prijem_ks']*$row['predaj_ks'] . "</td>");
echo '<td>Zobraziť</td>';
//echo '<td>In Development</td>';
//echo '<td>In Development 2</td>';
The quotes are breaking the SQL syntax, rewrite as a prepared statement to make it easier:
$stmt = $dbh->prepare('SELECT a.tovar ,
( select sum(b.kusy) from jednotypredaj as b
where b.tovar=a.tovar and b.co=:received ) as prijem_ks,
( select sum(c.kusy) from jednotypredaj as c
where c.tovar=a.tovar and c.co=:paid ) as predaj_ks, kod
FROM jednotypredaj WHERE
(a.tovar LIKE :keyword ) as a
GROUP BY a.tovar ORDER by a.tovar ASC');
$stmt->execute(array('received' => 'prijem','paid' => 'predaj','keyword' => $keyword));
foreach ($stmt as $row) {
echo "<tr>";
echo "<td>" . $row['tovar'] . "</td>";
...
Reconsider your SQL statement as you can either run correlated subqueries or conditional aggregates. Also, you table alias, a, was incorrectly positioned after WHERE clause:
Correlated subqueries (retains unit level records with kod column)
SELECT a.tovar,
(select sum(b.kusy) from jednotypredaj as b
where b.tovar=a.tovar and b.co='prijem') as prijem_ks,
(select sum(c.kusy) from jednotypredaj as c
where c.tovar=a.tovar and c.co='predaj') as predaj_ks,
a.kod
FROM jednotypredaj as a
WHERE (a.tovar LIKE '%$keyword%')
ORDER by a.tovar ASC
Conditional aggregates (group by aggregate records w/o kod unless added as a group)
SELECT a.tovar,
SUM(CASE WHEN a.co='prijem' THEN a.kusy ELSE NULL END) as prijem_ks,
SUM(CASE WHEN a.co='predaj' THEN a.kusy ELSE NULL END) as predaj_ks
FROM jednotypredaj as a
WHERE (a.tovar LIKE '%$keyword%')
GROUP BY a.tovar
ORDER by a.tovar ASC
MySQL may allow kod in SELECT clause and not in GROUP BY clause of aggregate query if your instance has the ONLY_FULL_GROUP_BY setting turned off but is not recommended and not ANSI-SQL compliant.
And as mentioned parameterize these queries in PHP script, binding string literals, that helps avoid quote handling and SQL injection.
I'm joining 5 tables in vTiger in order to get all the info I need. However, there is an option that certain columns will be empty. In that case, my SELECT statement fails and I can't retrieve the rest of the results. How do I bypass this by adding a "Doesn't exist" default value if the column is blank?
$results = mysql_query("SELECT
vtiger_potentialscf.potentialid,
vtiger_potential.potentialname,
vtiger_contactdetails.accountid,
vtiger_contactdetails.salutation,
vtiger_contactdetails.firstname,
vtiger_contactdetails.lastname,
vtiger_account.accountname,
vtiger_crmentity.smownerid,
vtiger_crmentity.crmid,
vtiger_crmentity.label,
vtiger_users.id,
vtiger_users.email1
FROM vtiger_potential
INNER JOIN vtiger_potentialscf ON vtiger_potentialscf.potentialid = vtiger_potential.potentialid
INNER JOIN vtiger_crmentity ON vtiger_potential.potentialid = vtiger_crmentity.crmid
INNER JOIN vtiger_users ON vtiger_crmentity.smownerid = vtiger_users.id
INNER JOIN vtiger_contactdetails ON vtiger_potential.related_to = vtiger_contactdetails.accountid
INNER JOIN vtiger_account ON vtiger_account.accountid = vtiger_potential.related_to
WHERE `cf_919` = DATE(NOW())");
while ($row = mysql_fetch_assoc($results)) {
echo $row['email1'] . "<br />";
echo $row['smownerid'] . "<br />";
echo $row['potentialname'] . "<br />";
echo $row['accountid'] . "<br />";
echo $row['salutation'] . "<br />";
echo $row['firstname'] . "<br />";
echo $row['lastname'] . "<br />";
echo $row['accountname'] . "<br />";
In this case, I can have the vtiger_contactdetails empty. Any suggestion on how to get the rest of the content and just echo that these aren't available?
You could use left join.
Have a look http://www.w3schools.com/sql/sql_join_left.asp
Thanks Abhik Chakraborty for a much better explanation in the comments.
I had one table listing events and attendies. To try Database normalization i split this into two tables.
I have made a database listing all the planned games for a team.
Table 1
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+name + organiser + date + location + cost + notes + id+
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
i then have a second database that has everyone how has marked they will be comming
Table 2
++++++++++++++++++++++++++
+id + event + player +
++++++++++++++++++++++++++
The id is unique to each, The id from table 1 is used as the event in table 2.
i have a simple PDO query that pulls the data from table 1 into a HTMl table
if($db->connect_error) {
die("Connection error: ".$db->connect_error);
}
$sql = $db->query('SELECT * FROM event ORDER BY `date` ASC'
) or die($db->error);
echo"";
while($row = mysqli_fetch_assoc($sql))
{
$a = $row['attendees'];//will look up attendies to tick a check box if already aknowledged
$b = htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8');
if (strpos($a,$b) !== false) {
$c = "checked='checked'";
}else{
$c = "";
}
$r=$row['id'];
echo "<div id='results'>";
echo "<CENTER>";
echo "<table BORDER=6 class='fixed'>";
echo "<TR> ";
echo "<TD COLSPAN=3 ALIGN=CENTER><form action='going.php' method='post' name='form".$r."'>Event ".$row['name']." i'm going
<input type='checkbox' name='going'".$c." onclick='document.form".$r.".submit ();'>
<input type='text' name='Organise' value='".$r."'>
<input type='text' name='name' value='".$b."'>
</form></TD>";
echo "</TR> ";
echo "<TR>";
echo "<td>";
echo "<B><u><font color='#0080FF'>Title </font></b></u>".$row['name']."<br></font>";
echo "<B><u><font color='#0080FF'>Orginiser </font></b></u>".$row['organiser']."<br></font>";
echo "<B><u><font color='#0080FF'>When </font></b></u>".date("D j-M-Y GA",$row['dt'])."<br></font>";
echo "<B><u><font color='#0080FF'>Location </font></b></u>".$row['location']."<br></font>";
echo "<B><u><font color='#0080FF'>Cost </font></b></u>£".$row['cost']."<br></font></TD>";
echo "<TD ROWSPAN=3 valign='top'><B><u><font color='#0080FF'>Attendies </font></b></u>".$row['attendees']."<br></font></TD>";//will change to table 2
echo "<TD ROWSPAN=3 valign='top'><B><u><font color='#0080FF'>notes </font></b></u>".$row['notes']."<br></font></TD>";
echo "</tr>";
echo "</table>";
echo "</CENTER>";
echo "</div>";
}
i have tried and joind these using
$sql = $db->query('SELECT t1.*, t2.event as t2event, t2.player as player
FROM `event` as t1
LEFT JOIN `going` as t2 on t1.id = t2.event
ORDER BY t1.`dt` ASC'
but all i got was a HTML table per event and per player. I'm sure its possible but can't work it out, can i create a html table from quering table 1 and add to attendies all those going from table 2 not just one or creating a result each one. ?