mysql query 2 tables with count - php

Hi i have the following query/table from a local bookstore
$queryadmin ="SELECT last_name, first_name, user_id FROM users";
$recordz = #mysqli_query ($dbc, $queryadmin);
while ($row = mysqli_fetch_array($recordz, MYSQLI_ASSOC)) {
echo '<tr>
<td align="left">' . $row['first_name'] . '</td>
<td align="left">' . $row['last_name'] . '</td>
<td align="left">' . $row['user_id'] . '</td>
</tr>'
;}
now i want an additional column from another table where the numbers of books each user has lend out are displayed.
So the query if nested seperately would go something like this
$query2 = mysql_query("SELECT FROM mirror3 WHERE userid='".$row['user_id']."'", $link);
$anzahl = mysql_num_rows($query2);
placing this query nested inside the while query (right after while starting) from above does not work. How to do that?
supplied argument is not a valid MySQL
result resource
thanks

Your query is wrong. Specify a field name:
$query2 = mysql_query("SELECT
SOMETHING FROM mirror3 WHERE userid='".$row['user_id']."'", $link);

You could probably do this in one query:
$query = mysqli_query('SELECT u.last_name, u.first_name, u.user_id, m.PUT_SOMETHING_HERE
FROM users u
LEFT JOIN mirror3 m ON u.user_id = m.userid
WHERE m.PUT_SOMETHING_HERE IS NOT NULL');
But Parkyprg has a point, you need to be selecting something from that second query.

Related

PHP output from SQL into a table

I have a query that works (see query results) temporarily taken out I don't have enough points for more than two links
However, when I try to output in PHP the category name is the same for both the offeredcategory.categoryName and wantedcategory.categoryName for categoryName on output to a table (see screenshot):
I'm trying to use the alias in the query to output categoryName differently for offered and wanted.
I've also tried using $row["offeredcategory.categoryName"] and $row["wantedcategory.categoryName"] which yields an error:
Notice: Undefined index: offeredcategory.categoryName in C:\Program Files (x86)
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
$sql = "SELECT customers.*, ads.*, categoriesselected.categoryselectedID, categoriesselected.offeredcategoryID, offeredcategory.categoryID, offeredcategory.categoryName, categoriesselected.wantedcategoryID, wantedcategory.categoryID, wantedcategory.categoryName
FROM customers
INNER JOIN ads ON ads.customerId = customers.customerID
INNER JOIN categoriesselected ON categoriesselected.adID = ads.adID
LEFT OUTER JOIN categories AS offeredcategory ON offeredcategory.categoryID = categoriesselected.offeredcategoryID
LEFT OUTER JOIN categories AS wantedcategory ON wantedcategory.categoryID = categoriesselected.wantedcategoryID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table>
<tr><th></th><th colspan=2>OFFERING</th><th colspan=2>WANTING</th><th>Location</th></tr>";
//need to prevent SQL injection using ...
while($row = $result->fetch_assoc())
{
echo
'<tr>
<td><img src="images/'.$row["fileUploadLocation"]. '" width="80" height="80" class="descImage"/></td>
<td>' ."<h6>" . $row["categoryName"]. "</h6>" . "<br>"
. $row["servicesOfferedTitle"]. '</td>
<td>' . $row["servicesOfferedDescription"]. '</td>
<td>' . $row["categoryName"]. "<br>"
. $row["servicesWantedTitle"]. '</td>
<td>' . $row["servicesWantedDescription"]. ' </td>
<td>' . $row["location"]. '</td>
</tr>';
}
echo "</table>";
} else {
echo "0 results";
}
I've now tried as suggested changing alias from joins to Select but now the joins won't work
Haven't to the $row part yet.
I've now tried as suggested changing alias from joins to Select but now the joins won't work (see screenshots):
Haven't to the $row part yet.
from manasschlcatz
Next tried 2nd suggestion but yields error:
Notice: Undefined index: offeredName in C:\Program Files (x86)
$sql = "SELECT customers.*, ads.*, categoriesselected.categoryselectedID, categoriesselected.offeredcategoryID, offeredName.categoryID, offeredName.categoryName, categoriesselected.wantedcategoryID, wantedName.categoryID, wantedName.categoryName
FROM customers
INNER JOIN ads ON ads.customerId = customers.customerID
INNER JOIN categoriesselected ON categoriesselected.adID = ads.adID
LEFT OUTER JOIN categories AS offeredName ON offeredName.categoryID = categoriesselected.offeredcategoryID
LEFT OUTER JOIN categories AS wantedName ON wantedName.categoryID = categoriesselected.wantedcategoryID" ;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table>
<tr><th></th><th colspan=2>OFFERING</th><th colspan=2>WANTING</th><th>Location</th></tr>";
//need to prevent SQL injection using ...
while($row = $result->fetch_assoc())
{
echo
'<tr>
<td><img src="images/'.$row["fileUploadLocation"]. '" width="80" height="80" class="descImage"/></td>
<td>' . $row["offeredName"]. "<br>"
. $row["servicesOfferedTitle"]. '</td>
<td>' . $row["servicesOfferedDescription"]. '</td>
<td>' . $row["wantedName"]. "<br>"
. $row["servicesWantedTitle"]. '</td>
<td>' . $row["servicesWantedDescription"]. ' </td>
<td>' . $row["location"]. '</td>
</tr>';
}
You have duplicate field names: offeredcategory.categoryNameand wantedcategory.categoryName will both be retrieved $row['categoryName'] so only one will show up - categoryName is ambiguous but not rejected by MySQL because the SQL statement is clear and the problem is processing the results in PHP. Simple solution is:
offeredcategory.categoryName as offeredName
wantedcategory.categoryName as wantedName
and retrieve with $row['offeredName'] or $row['wantedName'] depending on what you actually want to display.
Complete SQL becomes:
SELECT customers.*, ads.*, categoriesselected.categoryselectedID, categoriesselected.offeredcategoryID, offeredcategory.categoryID, offeredcategory.categoryName as offeredName, categoriesselected.wantedcategoryID, wantedcategory.categoryID, wantedcategory.categoryName as wantedName
FROM customers
INNER JOIN ads ON ads.customerId = customers.customerID
INNER JOIN categoriesselected ON categoriesselected.adID = ads.adID
LEFT OUTER JOIN categories AS offeredcategory ON offeredcategory.categoryID = categoriesselected.offeredcategoryID
LEFT OUTER JOIN categories AS wantedcategory ON wantedcategory.categoryID = categoriesselected.wantedcategoryID";

SQL Join doesn't show up correctly

i'm trying to find a solution, i'm trying to get a data from different tables using same id. Here is my code
"SELECT * FROM menucat LEFT JOIN vmenutab ON menucat.cat_id = vmenutab.menu_id";
I need to create sections, and fill them later with some content, table menucat is parent table with sections, vmenutab is child table with content.
But i have a problem, it doesn't show up correctly. It should be like this:
Section1
Link1
Link2
But it shows up like this:
Section1
Link1
Section1
Link2
I've been using search, GROUP BY and DISTINCT didn't worked.
tables:
menucat:
cat_id menu_cat_est menu_cat_ru menu_cat_en
vmenutab:
id (unique link id) menu_id (id to related section) menu_name_est menu_name_ru menu_name_en
menu_cat_xxx and menu_name_xxx are different languages data
PHP Code
<?php
$target = "SELECT * FROM menucat LEFT JOIN vmenutab ON menucat.cat_id = vmenutab.menu_id";
$mq = mysql_query($target);
while ($row = mysql_fetch_array($mq)) {
$menu_cat_est = $row['menu_cat_est'];
$menu_cat_ru = $row['menu_cat_ru'];
$menu_cat_en = $row['menu_cat_en'];
$menu_name_est = $row['menu_name_est'];
$menu_name_ru = $row['menu_name_ru'];
$menu_name_en = $row['menu_name_en'];
$cat_id = $row['cat_id'];
$id = $row['id'];
echo '<tr>
<td>' . $menu_cat_est . ''.$menu_name_est.'</td>
<td>' . $menu_cat_ru . ''.$menu_name_ru.'</td>
<td>' . $menu_cat_en . ''.$menu_name_en.'</td>
<td scope="col"><center><img src="style/stylesheet/images/edit.png"></center></td>
<td scope="col"><center><img src="style/stylesheet/images/delete.png"></center></td>
<td scope="col"><center>Добавить</center></td>
</tr>';
}
?>
Sorry for my english. Best Regards.
EDIT: Added entire PHP Code.
EDIT #2: Added table rows.
an example as i don't know your db data. also sort db by cat id
' . $menu_cat_xxx . ''.$menu_name_xxx.' its a bit confusing
$target = "SELECT * FROM menucat LEFT JOIN vmenutab ON menucat.cat_id = vmenutab.menu_id" order by menucat.cat_id;
$mq = mysql_query($target);
while ($row = mysql_fetch_array($mq)) {
$menu_cat_est = $row['menu_cat_est'];
$menu_cat_ru = $row['menu_cat_ru'];
$menu_cat_en = $row['menu_cat_en'];
$menu_name_est = $row['menu_name_est'];
$menu_name_ru = $row['menu_name_ru'];
$menu_name_en = $row['menu_name_en'];
$cat_id = $row['cat_id'];
$id = $row['id'];
if(!$nocat[$cat_id]){ $nocat[$cat_id] = $cat_id; $section='<tr><td colspan="6"> section' . $cat_id . '</td></tr>
';}else{$section='';} // customise as i need sleep
echo $section.
'<tr>
<td>' . $menu_cat_est . ''.$menu_name_est.'</td>
<td>' . $menu_cat_ru . ''.$menu_name_ru.'</td>
<td>' . $menu_cat_en . ''.$menu_name_en.'</td>
<td scope="col"><center><img src="style/stylesheet/images/edit.png"></center></td>
<td scope="col"><center><img src="style/stylesheet/images/delete.png"></center></td>
<td scope="col"><center>Добавить</center></td>
';
}

how to link a customer and a project to oneanother?

I'm kind of new to PHP/MySQl so I would like some guidelines on how these thing work, hard to google this...
So, im trying to learn php/mysql and I'm about to write a small page with customers and each customer could have a few projects.
so, my db is set up as follows (guess this would need heavy modifications):
- customers (id, name, description)
- projects (id, name, description)
- users (id, name )
<?php
if(isset($_GET['id'])) {
$query = "SELECT * FROM customers WHERE id = '". $_GET['id']."'";
$results = mysql_query($query);
while($row = mysql_fetch_array( $results ))
{
echo "<h3>" . $row['name'] . "</h3>";
echo "<br />";
$query = "SELECT * FROM projects ORDER by name ASC";
$results = mysql_query($query);
echo "<table>
<tbody>";
while($row = mysql_fetch_array( $results ))
{
echo "<tr>
<td><a href='main.php?id=" . $row['id'] . "'>" . $row['name'] . "</a></td>
<td>" . $row['description'] . "</td>
</tr>";
}
echo "</tbody>
</table>";
}
} else {
$query = "SELECT * FROM customers ORDER by name ASC";
$results = mysql_query($query);
echo "<table>
<thead>
<tr>
<th width='20%'>Customer</th>
<th width='80%'>Description</th>
</tr>
</thead>
<tbody>";
while($row = mysql_fetch_array( $results ))
{
echo "<tr>
<td><a href='main.php?id=" . $row['id'] . "'>" . $row['name'] . "</a></td>
<td>" . $row['description'] . "</td>
</tr>";
}
echo "</tbody>
</table>";
}
?>
As you can see it missing some heavy things, for instance, if I choose Customer A or B I receive the same projects, I don't know how to separate the projects and "bind" them to a certain customer. And my intention is to "bind" users to projects and customers as well.
Any hints into the correct direction is appreciated!
You can have an INNER JOIN in the select query, like so:
"SELECT * FROM customers c INNER JOIN projects p ON p.name = c.name WHERE c.id = '". $_GET['id']."'";
Here, I have considered that you DO HAVE a name column in customer table which is the same as that in project.
You would need to add some tables.
First a table that represents the relation from Customers to Projects. This would be like
Customer ID | Project ID
1 | 1
2 | 3
....
Same would be needed for Customer and User.
Now you can reference to this table to get your needed information and perform the necessary joins to get your data.
You need another table which has the key (customers.id,projects.id) In this way you link each customer to their own projects, and you'd need to select the data from that table depending on the id of the customer. Probably you'll need a customer/user table too, to link user id to customer id.
Edit for clarity: The new table should look something like:
CREATE TABLE customer_projects (
customer_id INT NOT NULL,
project_id INT NOT NULL,
PRIMARY KEY (customer_id, project_id));
Then you assign each customer to their projects in this table. To get the details (customer name, project name), you'd need to do a "join" with other tables, something like:
SELECT customers.*, projects.* FROM customer_projects
LEFT JOIN customers ON customers.id = customer_projects.customer_id
LEFT JOIN projects ON projects.id = customer_projects.project_id
WHERE customer_projects.customer_id = '1' // 1 is an example of a customer id.

PHP/MYSQLi - Display last date query

My database table have 5 columns: 'id', 'date_visited', 'page_title', 'ip' and 'total_views'.
I am not able to display ORDER BY 'date_visited'.
My PHP Query is:
<?php
[...]
$query = "SELECT *,count(*) FROM table WHERE ip GROUP BY page_title";
$result = mysqli_query($link,$query) or die(mysqli_error($link). "Q=".$query);
if(!$result == 0) {
while ($row = mysqli_fetch_array($result)) {
$dataList_br .= '<tr>
<td>' .$row['date_visited']. '</td>
<td>' .$row['page_title']. '</td>
<td>' .$row['count(*)']. '</td>
</tr>';
}
} else {
$dataList_br .= '<p class="warning">No data found in database.</p>';
}
?>
When it outputs, it displays [date][page title] and [total views].
Please someone help me, how do I display last date from the query, instead now it displays the very first day the page was visited.
Thank you.
MySQL is lenient about the contents of the GROUP BY and will return a row for the group somewhat arbitrarily if columns aren't in the GROUP BY but are SELECTed. In your case, it just gave you the first row (lowest date) for each group.
Get the page_name of the row with the MAX(date_visited) per group and join that against the main table to pull in the remaining columns from the main table.
SELECT
table.id,
table.ip,
table.total_views,
maxdates.date_visited,
maxdates.page_name,
maxdates.thecount
FROM
table
JOIN (
/* Subquery returns the aggregates to join against
the main table so other columns can be pulled in */
SELECT
page_title,
MAX(date_visited) AS maxdate,
COUNT(*) AS thecount
FROM table
GROUP BY page_title
) maxdates
ON table.page_name = maxdates.page_name
AND table.date_visited = maxdates.maxdate
You want to use ORDER BY. Like so:
$query = "SELECT *, count(*)
FROM table
WHERE ip
GROUP BY page_title
ORDER BY date_visited ASC";
Try this whit "ORDER BY":
$query = "SELECT date_visited, page_title,count(*) FROM table WHERE ip ORDER BY page_title ASC";
$result = mysqli_query($link,$query) or die(mysqli_error($link). "Q=".$query);
if(!$result == 0) {
while ($row = mysqli_fetch_array($result)) {
$dataList_br .= '<tr>
<td>' .$row['date_visited']. '</td>
<td>' .$row['page_title']. '</td>
<td>' .$row['count(*)']. '</td>
</tr>';
}
} else {
$dataList_br .= '<p class="warning">No data found in database.</p>';
}

php variable not displaying correctly

Im trying to build a feeds application in php in which im using a simple table with 2 columns..one for name and one for the respective feeds...my feed is appearing properly but there is some problem with the name heres the code...
<?php
include_once "connect_to_mysql.php";
$sql = mysql_query("SELECT id, feed, feeddate FROM feeds ORDER BY feeddate DESC LIMIT 20");
while($row = mysql_fetch_array($sql))
{
$name = $row["name"];
$uid = $row["userid"];
$ufeed = $row["feed"];
$feeddate = $row["feeddate"];
$feeds .= '
<table width="90%" align="center" cellpadding="4" bgcolor="#A6D2FF">
<tr>
<td width="7%" bgcolor="#FFFFFF">' . $name . '<br />
</td>
<td width="93%" bgcolor="#D9ECFF"> <span style="font-size:10px; font-weight:bold; color:#A6A6A6;">' . $feeddate . '</span><br />
' . $ufeed . '</td>
</tr>
</table>';
}?>
<?php print "$feeds"; ?>
here the $name thing is simply not displaying as a link!please help..
You are selecting only three columns:
SELECT id, feed, feeddate
"name" is not among them, so it will be always empty.
$row["name"] is not set, because you did not include the name column in the select expression of the database query. Consequently, the statement
$name = $row["name"];
sets $name to null. The same holds for $uid and $row["userid"].
Your sql query should be
$sql = mysql_query("SELECT name, id, feed, feeddate FROM feeds ORDER BY feeddate DESC LIMIT 20");
Also, you have $uid = $row["userid"];. I believe it should be $uid = $row["id"]; as you have id in sql query. You have to change either of them.
If you have id use above query, else use below query.
$sql = mysql_query("SELECT name, userid, feed, feeddate FROM feeds ORDER BY feeddate DESC LIMIT 20");
You are selecting 3 columns id,feed,feed date.But you are printing name,id,feed,feed date. Please select name column also. It will display proper output.

Categories