SQL query working in phpmyadmin but not in php - php

i have made a query to select only the last date for each user. It works in phpmyadmin but when i want to execute it in a mysqli_query() in PHP it doesnt give anything back, not even an error.
the code is:
select * from table t inner join ( select User_ID, max(Date) as MaxDate from table group by User_ID ) tm on t.User_ID = tm.User_ID and t.Date = tm.MaxDate
If you have any idea why please let me know :)
EDIT
the PHP code is :
$id = $_SESSION["ID"];
$SqlQuery = "SELECT * from 'tablename' t inner join ( select 'User_ID', max('Date') as 'MaxDate' from 'tablename' group by 'User_ID' ) tm on 't.User_ID' = 'tm.User_ID' and 't.Date' = 'tm.MaxDate'";
$Result = mysqli_query($link, $SqlQuery) or die ("not possible to execute query: $sql on $link");
if ($Result->num_rows > 0) {
while($row = $Result->fetch_assoc()) {
echo "<br> id: ". $row['Sick_ID']. " - UserID: ". $row['User_ID']. "- Reason " . $row['Reason'] . "<br>";
}
} else {
echo "0 results";
}

Add the schema owner prefix to the select query. It usually happens when executing mysql queries on PHP.
Select * from data.table_name as t1 inner join data.table_name_2 as t2 .....
Better if:
Select data.t1.id, data.t2.name from data_table_name as t1 .....

Related

inner join not working in PHP, but working in phpMyAdmin SQL

I have a MySql Query that is not returning correct values in PHP, but if I run the same MySql Query in phpMyAdmin, it returns a value. If I display the select in a web browser, I get a 'Resource id #27' on the end of it.
PHP Code
$SQL_PhotoQueryList = "SELECT count(*) FROM `invoice_detail`".
" INNER JOIN `photos` ON invoice_detail.photo_id = photos.photo_id".
" INNER JOIN `invoice` ON invoice_detail.invoice_id = invoice.invoice_id".
" WHERE invoice.invoice_active = '$PassStatus' AND photos.user_id = '$SessionUserID'".
$SQL_PhotoResultList = mysql_query($SQL_PhotoQueryList);
$ListPhotoCount = mysql_result($SQL_PhotoResultList,0);
echo "SQL Query = $SQL_PhotoQueryList<br>";
echo "ListCount = $ListPhotoCount<br>";
Screen Output
SQL Query = SELECT count(*) FROM `invoice_detail` INNER JOIN `photos` ON invoice_detail.photo_id = photos.photo_id INNER JOIN `invoice` ON invoice_detail.invoice_id = invoice.invoice_id WHERE invoice.invoice_active = '2' AND photos.user_id = '2'Resource id #27
ListCount = 0
Code calling the routine ($SessionUserID is a $_SESSION Variable)
$PassStatus = "2"; // Active
require("get_invoice.php");
$InfoTotalSales = $ListGalleryCount;
It looks like you have a typo.
$SQL_PhotoQueryList = "SELECT count(*) FROM `invoice_detail`".
" INNER JOIN `photos` ON invoice_detail.photo_id = photos.photo_id".
" INNER JOIN `invoice` ON invoice_detail.invoice_id = invoice.invoice_id".
" WHERE invoice.invoice_active = '$PassStatus' AND photos.user_id = '$SessionUserID'".
$SQL_PhotoResultList = mysql_query($SQL_PhotoQueryList);
$ListPhotoCount = mysql_result($SQL_PhotoResultList,0);
echo "SQL Query = $SQL_PhotoQueryList<br>";
echo "ListCount = $ListPhotoCount<br>";
Note the full stop (actually, concatenation operator) on the last line of the query:
" WHERE invoice.invoice_active = '$PassStatus' AND photos.user_id = '$SessionUserID'".
This should be a semicolon. Yep, I've done that too. Sometimes the hardest mistake to find.
The resource ID at the end is from the result of mysql_query().

PHP and Postgresql product

Need help getting a sum for quantity and accessory_price in my current query to display in my table.
Here is my query:
$query = ('SELECT accessories.accessory_name,accessory_only_solds.transaction_id,accessory_only_solds.quantity,accessory_only_solds.accessory_price,transactions.date_purchased, FROM accessory_only_solds
left join accessories on accessory_only_solds.accessory_id = accessories.id
left join transactions on transactions.id = accessory_only_solds.transaction_id
ORDER BY transactions.date_purchased DESC');
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
while($myrow = pg_fetch_assoc($result)) {
printf ("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>", htmlspecialchars($myrow['transaction_id']), htmlspecialchars($myrow['date_purchased']), htmlspecialchars($myrow['accessory_name']), htmlspecialchars($myrow['accessory_price']), htmlspecialchars($myrow['quantity']), number_format($myrow['**sumhere**'], 2));
}
I tried adding this to my query but keep getting server error
TO_CHAR(CAST(accessory_only_solds.accessory_price AS NUMERIC)* accessory_only_solds.quantity),'999,999.99') AS atotal
!!!was able to solve my problem though i still need to convert the value to euro currency format.
$query = ('SELECT accessories.accessory_name,accessory_only_solds.transaction_id,accessory_only_solds.quantity,accessory_only_solds.accessory_price,transactions.date_purchased,CAST(accessory_only_solds.accessory_price AS NUMERIC)*accessory_only_solds.quantity AS atotal FROM accessory_only_solds
left join accessories on accessory_only_solds.accessory_id = accessories.id
left join transactions on transactions.id = accessory_only_solds.transaction_id
ORDER BY transactions.date_purchased DESC');

Select all customers and each customer's total orders

For each customer, I want to return: id, name, address, city, cap, country and total of orders. Table names are: customers (10 records) and orders (20 records)
I've tried this code, but it doesn't works
<?php
$conn = mysqli_connect('127.0.0.1','...','...','...') or die("Connection failed: " . $conn->connect_error);
$select = mysqli_query($conn,"SELECT customers.id,customers.name,customers.address,customers.city,customers.cap,customers.country COUNT(customerid) as TotalOrders FROM customers LEFT JOIN orders GROUP BY customer.id");
while($row = mysqli_fetch_array($select,MYSQLI_ASSOC))
{
$tb = <<<table
...{$row['totalorders']}...
table;
echo $tb;
}
mysqli_free_result($select);
echo $num_record = mysqli_affected_rows($conn);
$conn->close();
?>
So something like...
<?php
include('../path/to/connection/stateme.nts');
$query =
"
SELECT c.id
, c.name
, c.address
, c.city
, c.cap
, c.country
COUNT(o.customerid) TotalOrders
FROM customers c
LEFT
JOIN orders o
ON o.customerid = c.id
GROUP
BY c.id;
";
$result = mysqli_query($db,$query); ** where $db is something like mysqli_connect("myhost", "myusername", "mypassword");
while($row = mysqli_fetch_assoc($result))
{
$tb = <<<table
...{$row['totalorders']}...
table;
echo $tb;
}
mysqli_free_result($result);
echo $num_record = mysqli_affected_rows($db);
$db->close();
?>
(I'm no php coder)
You have a comma missing -
customers.country COUNT(customerid)
-----------------^
and you have left out an ON condition -
FROM customers LEFT JOIN orders //ON would be here
One thing you should always do is to create and run your queries against your database before you put those queries in your code. And always, always include error checking.

Where is the error with this query?

I have attacked this from many different ways today, I have no figured out the best way to display my data is with a single query that can be displayed in one table. The problem is I have three queries I am trying to combine, and it is not going very well. I feel like its close but clearly not correct.
$sql = (SELECT SUM(datamb) AS value_sum FROM maindata GROUP BY phonenumber UNION select dataplan as currentplan from maindata
GROUP BY phonenumber UNION SELECT DISTINCT phonenumber AS value_sum1 FROM maindata);
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)){
echo "<TABLE id='display'>";
echo "<td><b>Data Usage This Period: ". ROUND ($row["value_sum"],2) . "MB</b></td> ";
echo "<td><b>Data Plan: ". $row["currentplan"] . "</b></td> ";
echo "<td><b>Phone Number: ". $row["value_sum1"] . "</b></td> ";
echo "</TABLE>";
}
The Problem is I want three columns of data and I get just one column with all data
UNION adds extra rows to the query. It looks like you just want multiple columns. See if this query gets you any closer; if not please show some sample data and expected results:
SELECT
phonenumber AS value_sum1
dataplan AS currentplan,
SUM(datamb) AS value_sum
FROM maindata
GROUP BY
phonenumber,
dataplan
Also, consider not aliasing the phonenumber and dataplan columns - the aliases in this case just confuse things. You'll need to change the index values in the PHP code accordingly.
First replace this line :
$sql = (SELECT SUM(datamb) AS value_sum FROM maindata GROUP BY phonenumber UNION select dataplan as currentplan from maindata GROUP BY phonenumber UNION SELECT DISTINCT phonenumber AS value_sum1 FROM maindata);
By
$sql = "(SELECT SUM(datamb) AS value_sum FROM maindata GROUP BY phonenumber UNION select dataplan as currentplan from maindata GROUP BY phonenumber UNION SELECT DISTINCT phonenumber AS value_sum1 FROM maindata);"

Php multiple mySQL query

is it possible to retrieve an array of data from more than one table within one query? For example , I am getting an array from table1, but I want to retrieve data from several other tables too:
<?php
$con = mysql_connect($hostname,$username, $password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname, $con);
$today = date('Y-m-d H:i:s', time());
$today1DayAgo = date('Y-m-d H:i:s', strtotime("$today -1 day"));
$query = "SELECT * FROM table1 WHERE omtr_date BETWEEN '$today1DayAgo' AND '$today'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
echo $row["omtr_page_view"]);
}
mysql_close($con);
?>
Thanks
Use Mysql Joins.
Here is an example:
<?php
// Make a MySQL Connection
// Construct our join query
$query = "SELECT family.Position, food.Meal ";
$query .= "FROM family INNER JOIN food ";
$query .= "WHERE family.Position = food.Position";
//Execute query
$result = mysql_query($query) or die(mysql_error());
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
echo $row['Position']. " - ". $row['Meal'];
echo "<br />";
}
?>
More examples of mysql joins are listed here: http://phpweby.com/tutorials/mysql/32
You can use joins to do this:
E.g.
SELECT t1.*, t2.id, t2.someothercolumn FROM table1 t1 LEFT JOIN table2 t2 ON t1.id=t2.t1_id WHERE omtr_date BETWEEN '$today1DayAgo' AND '$today'
(Untested)
Might be worth reading up on them.. http://www.sitepoint.com/understanding-sql-joins-mysql-database/
If your tables have something in common, like 1 column of table1 is the primary key of table2, or any kind of a relation (like same column), you can use JOINS.
Otherwise you can use UNION as well, like
SELECT omtr_date1.a AS a1, omtr_date1.b AS b1 FROM table1 WHERE omtr_date1 BETWEEN '$today1DayAgo' AND '$today'
UNION
SELECT omtr_date2.c AS a1, omtr_date2.d AS b1 FROM table1 WHERE omtr_date2 BETWEEN '$today1DayAgo' AND '$today'
But both the select statements must produce same number of columns with same column names.
That will do you good.

Categories