I have a query a Wordpress include which does the following:
$sql = "SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = 'merchant_id' LIMIT 6";
$results = $wpdb->get_results($sql);
foreach ($results as $row)
{
echo $row->meta_value . ",";
//sprintf("SELECT * FROM retailers WHERE advertiserId = '%s'", $row->meta_value);
}
//clean all results
$wpdb->flush();
It parses all pages custom fields (merchant ID numbers), and returns any unique distinct values, separated by a comma. This bit works great.
ie: The above may return: 1301,345,723,134,1435
What I also have is a separate MySQL table of about 20 fields, three of which are the MerchantID, programmeName, and commissionMax. Each value from the CSV correlates with the MerchantID in the database.
Regardless of the amount of merchant ID's that appear in the CSV - I need to parse them all, but show the three highest commission rates (commissionMax), as well as the programmeName.
I managed to get connected to my external database and retrieve the appropriate values (using the commented code above) however this showed all of the retailers information.
Any advice?
Use the following query with limit:
SELECT * // select all fields
FROM table_name // from your table
WHERE MerchantID IN (your_ids_here) // IDs received from previous query or wherever
ORDER BY commissionMax DESC // descending sort by commissionMax field
LIMIT 3 // take first 3 results
Related
I'm displaying results from a MySQL table based on matching values in one column. I then need to separate these results based on the data in another column, when that data is different.
Here's a cut down example of the table I'm drawing data from:
customer_id customer_timestamp customer_order customer_email
27 2019-02-23 02:52:41 ABC123456789 admin#admin.com
28 2019-02-23 02:52:41 ABC123456789 admin#admin.com
32 2019-02-26 05:51:41 CBA987654321 admin#admin.com
From the above, I need to return all rows with the same customer_email then separate them by customer_order number.
Can this be achieved through a select statement alone and if so how?
Here's an example of a select statement I'm using which returns all rows with the same email;
$select = "select * from mytable where customer_email='admin#admin.com'";
The data I'm getting from the query is being fetched in an array so I need the array to generate a new loop based on the customer_order column.
I figured it out, might look a bit hacky but it works. I rolled back the idea of initially displaying any order data, now it requires user interaction to select a grouped order number to display details from that specific order.
Code below;
// Retrieve order number/s
$select_order = "select * from mytable where customer_email='admin#admin.com' group by customer_order";
$connect_order = mysqli_query($con, $select_order);
while ($row_order=mysqli_fetch_array($connect_order)) {
$customer_order = $row_order['customer_order'];
echo "
<form method='post'>
<input type='submit' value='$customer_order' name='order_current[]'>
</form>
";
}
// Make each grouped order number a separate query
if (isset($_POST['order_current'])) {
$order_all = $_POST['order_current'];
foreach ($order_all as $order_post) {
// Retrieve selected order details
$select_order = "select * from mytable where customer_email='admin#admin.coml' and customer_order='$order_post'";
$connect_order = mysqli_query($con, $select_order);
while ($row_order=mysqli_fetch_array($connect_order)) {
$name = $row_order['customer_name'];
$amount = $row_order['customer_amount'];
// Display selected order details
echo "
$name<br/>
$amount<br/>
";
}
}
}
in Wordpress/WooCommerce MySQL database i have various shortcodes.
If there is 2 orders in the database then one of the orders is a shop_order and the next one is shop_subscription_order. We find those 2 datas in another tabel by calling post_id, which is named wp_posts. There we have to look on the shop_subscription_order if the order is wc_active. We need one mySQL call that looks on how many rows there is on each customer, if there is 2 rows it has to take post_id on the subscription_order and check if it is wc_active, and print all orders with that status.
A not working example but for show what i mean:
SELECT * from post_meta where meta_key=´_customer_id´ and meta_vlaue=´$customerid´ if number of rows='2' select * from wp_post where post_type='shop_supscription' whit the id form post_meta and post_status='wc-active'
and then echo num_of_rows
video example here:
Https:// nltrading.dk/video.mov
First in the video we show an order with 3 rows, and after we show an order with 2 rows.
We only need the orders with 2 rows, where there is an wc_active as shown in the video. We need to call all of this to count the number of rows where there is an wc_active whit only 2 rows of orders.
Use this like code:
//To show number of rows in table
function test()
{
global $wpdb;
$table_name = $wpdb->prefix . 'mydata';
$count_query = "select count(*) from $table_name";
$num = $wpdb->get_var($count_query);
echo $num . 'Rows Found';
}
I have updated my original post based on what I learned from your comments below. It is a much simpler process than I originally thought.
require '../database.php';
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM Orders WHERE id = 430";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
echo 'Order Num: ' . $data['id'] . '<br>';
$sql = "SELECT * FROM Order_items
JOIN Parts ON Parts.id = Order_Items.part_id
WHERE Order_Items.orders_id = 430";
$q = $pdo->prepare($sql);
$q->execute(array($line_item_id));
$data = $q->fetch(PDO::FETCH_ASSOC);
while ($data = $q->fetch(PDO::FETCH_ASSOC))
{
echo '- ' . $data['part_num'] . $data['qty'] . "<br>";
}
Database::disconnect();
Unfortunately, only my first query is producing results. The second query is producing the following ERROR LOG: "Base table or view not found: 1146 Table 'Order_items' doesn't exist" but I am expecting the following results.
Expected Results from Query 1:
Order Num: 430
Expected Results from Query 2:
- Screws 400
- Plates 35
- Clips 37
- Poles 7
- Zip ties 45
Now that I understand where you are coming from, let's explain a couple of things.
1.PDO and mysqli are two ways of accessing the database; they essentially do the same things, but the notation is different.
2.Arrays are variables with multiple "compartments". Most typical array has the compartments identified by a numerical index, like:
$array[0] = 'OR12345'; //order number
$array[1] = '2017-03-15'; //order date
$array[2] = 23; //id of a person/customer placing the order
etc. But this would require us to remember which number index means what. So in PHP there are associative arrays, which allow using text strings as indexes, and are used for fetching SQL query results.
3.The statement
$data = $q->fetch(PDO::FETCH_ASSOC)
or
$row = $result->fetch_assoc()
do exactly the same thing: put a record (row) from a query into an array, using field names as indexes. This way it's easy to use the data, because you can use field names (with a little bit around them) for displaying or manipulating the field values.
4.The
while ($row = $result->fetch_assoc())
does two things. It checks if there is a row still to fetch from the query results. and while there is one - it puts it into the array $row for you to use, and repeats (all the stuff between { and }).
So you fetch the row, display the results in whatever form you want, and then loop to fetch another row. If there are no more rows to fetch - the loop ends.
5.You should avoid using commas in the FROM clause in a query. This notation can be used only if the fields joining the tables are obvious (named the same), but it is bad practice anyway. The joins between tables should be specified explicitly. In the first query you want the header only, and there is no additional table needed in your example, so you should have just
SELECT *
FROM Orders
WHERE Orders.Order_ID = 12345
whereas in the second query I understand you have a table Parts, which contains descriptions of various parts that can be ordered? If so, then the second query should have:
SELECT *
FROM Order_items
JOIN Parts ON Parts.ID = Order_Items.Part_ID
WHEERE Order_Items.Order_ID = 12345
If in your Orders table you had a field for the ID of the supplier Supplier_ID, pointing to a Suppliers table, and an ID of the person placing the order Customer_ID, pointing to a Customers table, then the first query would look like this:
SELECT *
FROM Orders
JOIN Suppliers ON Suppliers.ID = Orders.Supplier_ID
JOIN Customers ON Customers.ID = Orders.Customer_ID
WHERE Orders.Order_ID = 12345
Hope this is enough for you to learn further on your own :).
In my app, the user can type in an indefinite amount of categories to search by. Once the user hits submit, I am using AJAX to call my PHP script to query my DB and return the results that match what the user defined for the categories.
My category column is separated as so for each row: "blue,red,yellow,green" etc.
I have two questions:
How can I pass an array to MySQL (like so: [blue,yellow,green]) and then search for each term in the categories column? If at-least one category is found, it should return that row.
Can MySQL add weight to a row that has more of the categories that the user typed in, therefor putting it further to the top of the returned results? If MySQL cannot do this, what would be the best way to do this with PHP?
Thanks for taking the time and looking at my issue.
For the part 1 you can use the function below:
<?php
function createquery($dataarray){
$query="select * from table where ";
$loop=1;
foreach($dataarray as $data)
{
$query.="col='$data'";
if(count($dataarray)<$loop-1){
$query.=' or ';
}
$loop++;
}
return $query;
}
?>
This will return the long query.
use this some like this:
mysql_query("select * from table where category in (".implode($yourarray,',').")");
1)
Arrays are not passed to a MySQL database. What's past is a query which is a string that tells the database what action you want to preform. An example would be: SELECT * FROM myTable WHERE id = 1.
Since you are trying to use the values inside your array to search in the database, you could preform a foreach loop to create a valid SQL command with all those columns in PHP, and then send that command / query to the database. For example:
$array = array('blue', 'red', 'yellow', 'green');
$sql = "SELECT ";
foreach ($array as $value)
{
$sql .= $value.", ";
}
$sql .= " FROM myTable WHERE id = 1";
IMPORTANT! It is highly recommended to used prepared statements and binding your parameters in order not to get hacked with sql injection!
2)
You are able to order the results you obtained in whichever way you like. An example of ordering your results would be as follows:
SELECT * FROM myTable WHERE SALARY > 2000 ORDER BY column1, column2 DESC
Very new to PHP and JSON, I'm using the following to display a list of rows:
$db = new PDO('mysql:host=localhost;dbname=rugbysuperleague','xxx','xxx');
$stmt = $db->query("SELECT * FROM `table`");
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->execute();
echo json_encode($data);
It returns all the rows in the table OK, But how do I return the rows sorted based on aAscending values of a specific column, if tie, sort by next column. etc.
I'm trying to list in correct order a Sports Team Standings table. So that the team with most points is in 1st position, if there is a tie, sort by point difference etc.
Use ORDER BY and list the the columns in order of how you want it ordered:
SELECT * FROM `table` ORDER BY `points` DESC, `point_diff` ASC
You also don't need execute() and probably not the fetchAll().