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";
Related
I'm trying to get information about an SQL table via a php script however, whenever I add a SUM function I get the following error "Notice: Trying to get property 'num_rows' of non-object"
I don't know what's going on but if anyone can please explain/point me in the right direction as to how to fix this problem that would be greatly appreciated
Here's the 'broken' code
<?php
require("connect.php");
$inNo = $_POST["inNo"];
$sql = "SELECT invoice.invoice_no, invoice.date, invoice.cust_id, invoice.emp_id, invoice_line.prod_id,
invoice_line.qty, product.cost_price, (product.cost_price * invoice_line.qty) AS `multi`,
customer.first_name AS `customer_fname`, customer.last_name AS `customer_lname`,
employee.first_name AS `emp_fname`, employee.last_name AS `emp_lname`,
product.name AS `proname`
FROM invoice INNER JOIN invoice_line ON invoice.invoice_no = invoice_line.invoice_no
INNER JOIN product ON invoice_line.prod_id = product.id
INNER JOIN customer ON invoice.cust_id = customer.id
INNER JOIN employee ON invoice.emp_id = employee.id, SUM(multi) AS `invoicetotal`
WHERE cust_id = '" . $inNo . "'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
//open table
echo '<table class="table table-striped" id="outTable">';
echo "<tr><th>Product</th><th>Qty</th><th>Price</th><th>Total cost</th></tr>";
// output data of each row
$ctr = 0;
while($row = $result->fetch_assoc()) {
if ($ctr == 0)
{
echo "<h1>Invoice Number: " . $row["invoice_no"]. "</h1>";
echo "<p>Customer: " . $row["customer_fname"]. " " . $row["customer_lname"]."</p>";
echo "<p>Employee: " . $row["emp_fname"]. " " . $row["emp_lname"]. "</p>";
echo "<p>Date: " . $row["date"]. "</p>";
}
echo "
<tr>
<td>" . $row["proname"]. "</td>
<td>" . $row["qty"]. "</td>
<td>" . $row["cost_price"]. "</td>
<td>" . $row["multi"]. "</td>
</tr>";
$ctr++;
}
} else {
echo "0 results";
}
$conn->close();
?>
You need to insert the SUM() in the SELECT part above FROM:
SELECT
invoice.invoice_no,
invoice.date,
invoice.cust_id,
invoice.emp_id,
invoice_line.prod_id,
invoice_line.qty,
product.cost_price,
(product.cost_price * invoice_line.qty) AS `multi`,
customer.first_name AS `customer_fname`,
customer.last_name AS `customer_lname`,
employee.first_name AS `emp_fname`,
employee.last_name AS `emp_lname`,
product.name AS `proname`,
SUM(multi) AS `invoicetotal`
FROM invoice
INNER JOIN invoice_line
ON invoice.invoice_no = invoice_line.invoice_no
INNER JOIN product
ON invoice_line.prod_id = product.id
INNER JOIN customer
ON invoice.cust_id = customer.id
INNER JOIN employee
ON invoice.emp_id = employee.id` WHERE cust_id = 99
BTW, it's wise to format code - SQL code too - fine.
I'm developing a web application that works with WordPress database. In my website,(which works with WooCommerce and WPML) I have products in two languages - english (1st), serbian(2nd). I wrote an SQL code that get the products from database, with their regular and sale prices and etc., but I want to get ONLY products where lang = en (the products from english version). The problem is I don't know how to get them.
Simple SQL:
$sql = 'SELECT * from `wp_posts` WHERE post_type = product';
This is the method that SELECT from database:
// SELECT
public function select (
$table_1 = ' wp_posts ',
$table_2 = ' wp_postmeta ',
$rows = ' t1.id, t1.post_title, guid, post_type ',
$where = ' t1.post_status = "publish" AND t1.post_type = "product" OR t1.post_type = "product_variation" ',
$groupby = ' t1.ID, t1.post_title '
) {
// Connect to database and set charset
$this->connect();
$this->conn->set_charset('utf8');
// Published products
$sql = "SELECT $rows,
max(case when meta_key = '_regular_price' then t2.meta_value end) AS price,
max(case when meta_key = '_sale_price' then t2.meta_value end) AS sale,
max(case when meta_key = 'attribute_colors' then t2.meta_value end) AS colors,
max(case when meta_key = 'attribute_number' then t2.meta_value end)
FROM $table_1 AS t1
INNER JOIN $table_2 AS t2 ON ( t1.ID = t2.post_id )
WHERE $where
GROUP BY $groupby";
$result = mysqli_query($this->conn, $sql);
$published_products_count = mysqli_num_rows($result);
// Trashed products
$trashed_sql = "SELECT post_status FROM `wp_posts`
WHERE post_status = 'trash'";
$trashed_result = mysqli_query($this->conn, $trashed_sql);
$trashed_products_count = mysqli_num_rows($trashed_result);
// If results -> show them
if ($result) {
printf( "\t\t" . "<p>There are <strong>%d published</strong> products and <strong>%d trashed</strong>.</p>", $published_products_count, $trashed_products_count);
$table = '
<table class="pure-table pure-table-bordered">
<thead>
<tr>
<th>Row. №</th>
<th>ID</th>
<th>Product</th>
<th>Regular price</th>
<th>Sale price</th>
<th>Type</th>
<th>Edit</th>
</tr>
</thead>';
$row_number = 1;
while ($row = $result->fetch_assoc()) {
$table .= '
<tr>
<td>' . $row_number++ . '</td>
<td>' . $row["id"] . '</td>
<td>' . $row["post_title"] . '</td>
<td class="price">' . $row["price"] . '</td>
<td class="sale">' . $row["sale"] . '</td>
<td>' . $row["post_type"] . '</td>
<td>Edit</td>
</tr>';
}
$table .= '
</table>';
echo $table;
}
// If no results
else {
echo 'There isn't any products';
}
}
I hope somebody help me!
Thanks in advance! :)
P.S. The application is not based on WordPress!
WPML plugin creates several new tables to manage multilang, not affecting the standard WP posts tables. Specifically, it creates the wp_icl_translations table, where it stores relations between posts and languages.
You need to add two new JOIN statements to your query:
JOIN wp_icl_translations t ON wp_posts.ID = t.element_id AND t.element_type = 'post_product' JOIN wp_icl_languages l ON t.language_code=l.code AND l.active=1
Then, you can add a new condition to your WHERE statement like this:
AND t.language_code='en'
Hope this helps.
Regards.
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>
';
}
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>';
}
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.