I have my table that one of my column shows empty. It has the column of Id, Date, Cust name, Product + Qty, and amount. But only in Product + Qty shows empty even it has data in database.
PHP code
<?php
include('connect.php');
$start = isset($_GET['d1']) ? $_GET['d1'] : '';
$end = isset($_GET['d2']) ? $_GET['d2'] : '';
if(isset($_GET['submit']) && $_GET['submit']=='Search')
{
$result = mysql_query(
"SELECT
t1.qty,
t2.lastname,
t2.firstname,
t2.date,
t3.name,
t2.reservation_id,
t2.payable FROM prodinventory AS t1
INNER JOIN reservation AS t2
ON t1.confirmation=t2.confirmation
INNER JOIN products AS t3
ON t1.room=t3.id
WHERE str_to_date(t2.date, '%d/%m/%Y') BETWEEN
str_to_date('$start', '%d/%m/%Y') AND
str_to_date('$end', '%d/%m/%Y')
GROUP BY t2.confirmation") or die(mysql_error());
while ($row = mysql_fetch_array($result)){
echo'<tr class="record">';
echo '<td>'.$row['reservation_id'].'</td>';
echo '<td>'.$row['date'].'</td>';
echo '<td>'.$row['firstname'].' '.$row['lastname'].'</td>';
echo '<td><div align="left">';
$rrr=$row['confirmation'];
$results = mysql_query("SELECT * FROM prodinventory where confirmation='$rrr'");
while($row1 = mysql_fetch_array($results))
{
$roomid=$row1['room'];
$resulta = mysql_query("SELECT * FROM products where id='$roomid'");
while($rowa = mysql_fetch_array($resulta))
{
echo $rowa['name'].' x';
}
echo ' '.$row1['qty'].'<br>';
}
echo '<td>'.'PHP ' . number_format(floatval($row['payable']));
}
?>
Hmmmm I have deleted my answer but noone tried so...
I think this echo ' '.$row1['qty'].'<br>'; is the row you asked about. And all this looks like a typo. If this is the case:
You have no confirmation in the SELECT clause (it's used only in JOIN and GROUP BY) and it possible your $rrr to be blank. Echo it to be sure there is a value.
Check does your query works and return results. Echo the query string (or take it from the mysql log file) and test it.
You have SELECT *. Is the field name 'qty' correct in a case-sensivity environment? 'Qty' may be different and the query may work but you don't get the result.
i think that's because you have inner join and maybe the intersection tables have no data
try to do left join first if it works
insure that all of tables have data in it
Related
I am trying to pull data from my database which ahs the following:
x3 tables:
docs
doc_id - index
cat
cat_id - index
doc_cat_join
doc_id - foreign key to docs/doc_id
cat_id - foreign key to cats/cat_id
I have inserted some data so that I have a row in cats and a rows in docs and in the join table bound a cat_id with a doc_id which all works fine. I am tying to pull that from the tables and show it, here is my approach so far but not getting anything out and am wondering where my failings are as I am getting no errors?
when I visit the cateroy page in my scripts I GET the id from the url:
$id = $_GET['cat_id'];
$q = sprintf("
SELECT
docs.doc_id,doc_name
FROM docs
INNER JOIN doc_cat_join
ON cats.cat_id = doc_cat_join.cat_id
WHERE doc_cat_join.doc_id = '%s'
",
mysqli_real_escape_string($dbc, $id) );
$r = mysqli_query($dbc,$q)
or die ("Couldn't execute query: ".mysqli_error($dbc));
// FETCH AND PRINT ALL THE RECORDS
echo '<div class="view_body">';
while ($row = mysqli_fetch_array($r)) {
echo ' '.$row["doc_name"]. '<br>';
}
echo '</div>';
}
for some bizarre reason I get nothing, if I do a var_dump on $r I get the following:
string(168) " SELECT docs.doc_id,doc_name FROM docs INNER JOIN doc_cat_join ON cats.cat_id = doc_cat_join.cat_id WHERE doc_cat_join.doc_id = '24' "
So it gets the correct category ID I am in.
I am now getting th following output:
Couldn't execute query: Unknown column 'cats.cat_id' in 'on clause'
as per your input and query design, your query should be as per below-
SELECT d.doc_id, d.doc_name
FROM docs AS d
INNER JOIN doc_cat_join AS dc ON dc.doc_id = d.doc_id WHERE dc.cat_id = '24';
Note: If it is not then show what output you require.
$id = $_GET['cat_id'];
$q = sprintf("
SELECT
*
FROM docs
INNER JOIN doc_cat_join
ON docs.doc_id = doc_cat_join.doc_id
INNER JOIN cat
ON doc_cat_join.cat_id = cat.cat_id
WHERE doc_cat_join.cat_id = '$id'
",
mysqli_real_escape_string($dbc, $id) );
print_r ($q);
// FETCH AND PRINT ALL THE RECORDS
echo '<div class="view_body">';
while ($row = mysqli_fetch_array($r)) {
echo ' '.$row["doc_name"]. '<br>';
}
echo '</div>';
}
your query is wrong I think.
I have a bilingual dictionary database that I've created, and the tables are set up like so:
lemma (lemmaID, lemma, meaning)
collocate (collocateID, lemmaID, collocate, notes, connection)
collusage (usageID, lemmaID_u, collocateID_u, japanese, english, englishalt)
partofspeech (posID, partofspeech)
postolemma (lemmaID_p, posID_p)
So far, I have a query that returns tables for the results, and it works just how I'd like it to. (It looks like this)
$q = 'SELECT *
FROM lemma, collocates, collusage
WHERE lemma.lemmaID = collocates.lemmaID AND lemma.lemmaID = collusage.lemmaID_u AND collusage.collocateID_u = collocates.collocateID
ORDER BY lemma.lemmaID;';
$result = mysqli_query($con, $q) or die(mysql_error());
if (!$result || mysqli_num_rows($result) == 0) {
echo 'No rows found';
exit;
}
$lastCatID = 0;
while ($row = mysqli_fetch_assoc($result)) {
$reading = $row['reading'];
$headword = $row['lemma'];
$collocate = $row['collocate'];
if (isset($row['notes'])) {
$notes = '('.$row['notes'].')';
} else {
$notes = $row['notes'];
}
$japanese = $row['japanese'];
$english = $row['english'];
if (isset($row['englishalt'])) {
$englishalt = ', '.$row['englishalt'].'';
} else {
$englishalt = $row['englishalt'];
}
if ($lastCatID != $row['lemmaID']) {
//starting a new category
if ($lastCatID != 0) {
//close up previous table
echo ' </tbody>
</table> </div>';
}
//start a new div
echo '<div class="entry">
<h4>'.$reading.'【'.$headword.'】 <span class="pos">'.$WANT TO LIST PARTS OF SPEECH HERE.'</span></h4>
<table class="table table-striped table-hover">
<tbody>';
$lastCatID = $row['lemmaID'];
}
echo '<tr>
<td><span>'.$collocate.'</span><span class="notes">'.$notes.'</span></td>
<td>'.$japanese.'</td>
<td>'.$english.''.$englishalt.'</td>
</tr>';
}
if ($lastCatID != 0) {
//close up the final table
echo ' </tbody>
</table></div>';
}
mysqli_free_result($result);
What I can't figure out how to do is to use the postolemma junction table to get all of the partofspeech values for each lemmaID so I can list them next to the lemma in the table. Everything SELECT query I have done so far has duplicated collocation entries, which I don't want. Any help is appreciated!
Edit: Here is a link to the SQL Fiddle with data. I couldn't get my foreign key constraints to work so just that is missing.
if I understand you correctly you want to select all values from table partofspeech based on lemma table. Your query should look like this:
SELECT part.partofspeech
FROM partofspeech part
INNER JOIN postolemma post
ON part.posID = post.posID_p
INNER JOIN lemma l
ON post.lemmaID_p = l.lemmaID
Also I would suggest you to change the query you use and start using JOIN operator in syntax, it's good practice and it's not hard to switch from one to another... So your query:
SELECT *
FROM lemma, collocates, collusage
WHERE lemma.lemmaID = collocates.lemmaID
AND lemma.lemmaID = collusage.lemmaID_u
AND collusage.collocateID_u = collocates.collocateID
ORDER BY lemma.lemmaID;
Will look like this:
SELECT *
FROM lemma
INNER JOIN collocates
ON lemma.lemmaID = collocates.lemmaID
INNER JOIN collusage
ON collusage.collocateID_u = collocates.collocateID
AND lemma.lemmaID = collusage.lemmaID_u
ORDER BY lemma.lemmaID;
Also you can use aliases for table in you query like i do in first query I wrote here. It will make your life easier because you don't need to type whole name of table over and over...
GL!
P.S. also it's good to post your desired result in you question and provide SQL Fiddle with some data for our better understanding of your queston...
EDIT
After we consulted in the comments we come to this solution:
SELECT *
FROM lemma
INNER JOIN collocates
ON lemma.lemmaID = collocates.lemmaID
INNER JOIN collusage
ON collusage.collocateID_u = collocates.collocateID
AND lemma.lemmaID = collusage.lemmaID_u
INNER JOIN (SELECT post.lemmaID_p AS lemmaID, group_concat(part.partofspeech SEPARATOR ', ') AS partofspeach
FROM partofspeech part
INNER JOIN postolemma post
ON part.posID = post.posID_p
INNER JOIN lemma l
ON post.lemmaID_p = l.lemmaID
GROUP BY post.lemmaID_p) tmp
ON lemma.lemmaID = tmp.lemmaID
ORDER BY lemma.lemmaID;
Here is SQL Fiddle for that...
I have this code, that fetches data from two tables in MySQLi.
It first has to get the title, description, status and project_id from table 1, and then get the name from table 2 using the id from table 1.
Is there a better/faster way to do this? I have about 600 rows in the tables, and it takes about 5 sec to run this query. I will also add that this example is a bit simplified, so please don't comment on the db-structure.
<?php
$results = $connect()->db_connection->query(
'SELECT title, description, status, project_id
FROM table
WHERE created_by ='.$user_id
);
if ($results) {
while ($result = $results->fetch_object()) {
$res = $connect()->db_connection->query(
"SELECT name FROM projects WHERE id = ".$result->project_id
);
if ($res) {
while ($r = $res->fetch_object()) {
echo $r->name;
}
}
echo $result->title;
echo $result->status;
}
}
?>
Use Query:
SELECT title,description,status,project_id
FROM table tb
inner join projects pr on pr.id = tb.project_id
WHERE created_by = $user_id
Try to use JOIN in your query.
You can find examples and description of this command here: http://www.w3schools.com/sql/sql_join.asp
Check out also this infographics:
http://www.codeproject.com/KB/database/Visual_SQL_Joins/Visual_SQL_JOINS_orig.jpg
You can use JOIN on project_id:
$results = $connect()->db_connection->query('SELECT t.title title,t.description,t.status status,t.project_id, p.name name FROM `table` t JOIN projects p ON p.id= t.project_id WHERE t.created_by ='.$user_id);
if($results){
while($result = $results->fetch_object()){
echo $result->name;
echo $result->title;
echo $result->status;
}
}
tables have aliases here - t for table and p for projects.
Also to make it faster, add index to project_id in table table, if you haven't done it yet:
$connect()->db_connection->query('ALTER TABLE `table` ADD INDEX `product_id`');
I have this query which gives me the transactions for a user, and the output is a table with the information. There is this row named basket_value which contains some numbers, and I need to get the sum of those numbers. Could you please help me?
$query3 = 'SELECT users.first_name,users.last_name,users.phone,
retailer.date, SUM(retailer.basket_value),
retailer.time,retailer.location,retailer.type_of_payment
FROM users ,retailer
WHERE users.user_id="'.$id_user.'"
AND users.user_id=retailer.user_id GROUP BY users.user_id';
$result3 = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result3)) {
echo "Total ". $row['user_id']. " = $". $row['SUM(basket_value)'];
echo "<br />";
}
I suppose that also your query have some problem and suppose that you have an id to retrieve users, I would do in that way
$query3 = 'SELECT users.user_id,users.first_name,users.last_name,
users.phone, retailer.date,
SUM(retailer.basket_value) as total_sum,
retailer.time,retailer.location,retailer.type_of_payment
FROM users ,retailer WHERE users.user_id="'.$id_user.'"
AND users.user_id=retailer.user_id
GROUP BY users.user_id,users.first_name,users.last_name,
users.phone, retailer.date,retailer.time,retailer.location,
retailer.type_of_payment '
$result = $mysqli->query($query3);
Now if you want the sum for each user:
while ($row = $result->fetch_row()) {
echo "Player: ".$row['user_id']." total: ".$row['total_sum'];
}
If you want the WHOLE GLOBAL sum, you have to way:
Modify your query in that way:
SELECT SUM(retailer.basket_value) as total_sum
FROM retailer
Sum into while loop like: $total += $row['total_sum'];
You're missing a GROUP BY on your query. You most likely want to add GROUP BY users.user_id
Try this query:
SELECT u.first_name, u.last_name, u.phone, SUM(r.basket_value) as total_sum
FROM users u
JOIN retailers r
ON u.user_id = r.user_id
WHERE u.user_id="'.$id_user.'"
GROUP BY u.user_id
You can omit all other columns in the select list and only have the sum() aggregate run on the set to avoid the GROUP BY clause.
$query3 = 'SELECT SUM(retailer.basket_value) as total_sum
FROM users ,retailer WHERE users.user_id="'.$id_user.'"
AND users.user_id=retailer.user_id';
I have two tables which both have a unique PID. I need to know how I should setup the primary/foreign keys so I can access fields from both tables in one SQL statement.
For example: With the following data structure i'd like to echo out the players name and photo but also echo out all their stats via PHP as well. I have successfully done this with just the player Stats, but I do not know how to get access to fields in another table.
Here is my database structure so far:
Players
-PID (Set as Primary Key)
-Name
-Height
-College
-Photo
Stats
-PID
-Touchdowns
-Receptions
Current PHP Code:
$query="
SELECT * FROM Stats
ORDER BY Stats.FantasyPoints DESC";
$res=mysql_query($query);
$num=mysql_numrows($res);
$i=0;
while($i< $num){
$Name = mysql_result($res, $i, "Name");
$FantasyPoints = mysql_result($res, $i, "FantasyPoints");
echo $Name . ': '. $FantasyPoints . "<br />";
$i++;
}
$sql = "
SELECT p.*, s.*
FROM Players AS p
LEFT JOIN Stats AS s ON p.PID = s.PID
ORDER BY s.FantasyPoints DESC
";
You could also use a JOIN rather than a LEFT JOIN which would limit the result to only players who have stats
Edited sql to produce result similar to your own sql.
======================================================
This is how I would go about it...
$query =
"
SELECT s.*, p.*
FROM Stats AS s
LEFT JOIN Players AS p ON p.PID = s.PID
ORDER BY s.FantasyPoints DESC
";
$res = mysql_query($query);
while ($row = mysql_fetch_assoc($res))
{
echo "{$row['name']}: {$row['FantasyPoints']}<br />";
}