PHP/MYSQLi - Display last date query - php

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>';
}

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";

PHP using multiple while loop retrieve only 1 row

Currently, my plan is to add a gender icon next to the username. The problem is that even if there are more than 1 table record in the table, it shows only 1 row and some records suddenly gone. This is how it looks like:
The code I am using:
$pdo = new PDO('connection');
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt1 = $pdo->prepare("SELECT id, user_id, user, bid, date
FROM auction_bids ORDER BY date DESC");
$stmt2 = $pdo->prepare("SELECT user_id, user, bid, date
FROM auction_bids ORDER BY date DESC LIMIT 30");
$stmt11 = $pdo->prepare("SELECT pol FROM tb_users WHERE id = :user_id");
$stmt2->execute();
$r1 = $stmt1->fetch(PDO::FETCH_ASSOC);
$stmt11->execute(array(':user_id' => $r1['user_id']));
$id1 = $r1['id'];
echo '<table>';
while ($r1 = $stmt2->fetch(PDO::FETCH_ASSOC) && $r2 = $stmt11- >fetch(PDO::FETCH_ASSOC)) {
echo '<tr>
<td>' . $id1 . '</td>
<td><img height="16" width="16" alt="gender icon" src
="../images/' . ($r2['pol'] == 1 ? 'male.png' : 'female.png') . '" />
' . $r1['user'] . '</td>
<td class="border-right">' . $r10['level'] . '</td>
<td>' . $r1['bid'] . ' FA</td>
<td><img height="16" width="16" alt="calendar" src
="../images/calendar.png" />
' . date($dateFormatBids, strtotime($r1['date'])) . '</td>
</tr>
';
$id1--;
}
echo '<table>
Using while ($r1 = $stmt2->fetch(PDO::FETCH_ASSOC)) {..} loop without $r2, it is working (except that the gender color is the same, for test it should be red, for Lukas, should be blue):
If there is something that you need, please say. I am quite new to PHP and PDO.
from the line: $stmt11->execute(array(':user_id' => $r1['user_id'])); you are getting a single record so the while loop prints single row.
Write the query like:
$stmt2 = $pdo->prepare("SELECT tu.pol, user_id, user, bid, date
FROM auction_bids ab left join tb_users tu on ab.user_id = tu.id
ORDER BY date DESC LIMIT 30");
now :
while ($r1 = $stmt2->fetch(PDO::FETCH_ASSOC){
//rest of the code should work... user $r1['pol'] instead of $r2
}
Check that link to understand while loop :
http://www.w3schools.com/js/js_loop_while.asp
The problem you have condition should TRUE, and you ($r1 && $r2) = TRUE only when both Variable are TRUE, $r2 first time it's TRUE both second time will get FALSE.
You should loop for only $r1 and call $r1 inside the loop.

Get all products from english version - WooCommerce & WPML

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.

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>
';
}

mysql query 2 tables with count

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.

Categories