php for loop query in magento - php

Hello all i am new but got so many helps from here. Thanks to all the people who helped.
Now i am facing a problem in magento e-commerce for making a loop query of top 10 point holders. Well i have made a separate database which contain the points .
my database is table : magentodatabase_points
Now here is total 3 colums -
1. ID
2. User_id
3. points
well now, here i would like to make a loop of top 10 members contain the highest points i have tried but failed so can anybody help me on that.
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
$table = $resource->getTableName('database_points');
$query = 'SELECT user_id FROM ' . $table . ' ORDER BY points DESC LIMIT 10';
$results = $readConnection->fetchAll($query);
well but after that i have tried with php for loop but that is not supporting for magento. So can anybody know what will be the loop code for magento.
Well, one more help would be greatful for me how do i get magento customer names from the using the top results of user_id because i will get only the results not the names.
Anyways that is not that important because i hope i will solve it by my own.
So, please if anyone can help me on the loop query of top 10 point holders.
Thanks in advace
and sorry for my bad english

If your table name and fields exist then you can just add this below your code:
foreach ($results as $result) {
$user_id = $result['user_id'];
echo $user_id; // or do whatever you wanted to with the variable
}
You should consider using Magento's Models to do this instead. There's an excellent tutorial series from Alan Storm on MagentoCommerce's website: http://www.magentocommerce.com/knowledge-base/entry/magento-for-dev-part-5-magento-models-and-orm-basics
For the customer's names you can try this in your loop:
foreach ($results as $result) {
$user_id = $result['user_id'];
$customer = Mage::getModel('customer/customer')->load($user_id);
print_r($customer);
}

May be because your field name has uppercase for u of user_id correctd "User_id" and you are using lowercase in your query.
else your method is fine to work with magento
for gettting customer, if User_id u get from this result is a customer id then $customer_data = Mage::getModel('customer/customer')->load(User_Id); would give u all detail of customer. you can fetch name from this using $customer_data->getName() method

Related

PHP SQL Request: select only the lowest value of time where name = $name and stage = $stage

Hi so I've already got a php script working working for this but it use a massive amount of data for a really easy task so I really would like to improve it.
My problem is the following: I have a SQL database build like this
and I would to do request like this one:
http://myphppage.php?username=Whataname&stage=1
and I would like it to echo the result so that if I read my php page content I can read the following:
21
so basicly all I want is to do a request with the username and the stage as parameters and I would like it to return the lowest value of the column "time" WHERE name=the name parameter entered AND stage = the stage parameter entered
I'm not really good in sql but I'm pretty I can make this kind of sql request in a single line or two instead of this massive script I have right now.
here's the current script I have:
<?php
$q2 = "SELECT username FROM DB WHERE stage='$stage' GROUP BY username ORDER BY time ASC";
$result2 = mysql_query($q2);
$times = array();
$userusernames = array();
$usernames = mysql_fetch_assoc($result2);
while($rows=mysql_fetch_assoc($result2))
{
$temp = $rows['username'];
$q3 = "SELECT time FROM DB WHERE stage='$stage' AND username='$temp' GROUP BY time ORDER BY time ASC";
$result3 = mysql_query($q3);
while($aaa = mysql_fetch_assoc($result3))
{
array_push($times, $aaa['time']);
array_push($userusernames, $rows['username']);
if($rows['username']==$username)
{
echo $aaa['time'];
}
break;
}
}
?>
may someone please help me figuring out how to do this
EDIT: I have been looking around on internet but I can't find what I'm looking for, I'm pretty sure there's the answer somewhere so maybe you can just help me reformulate my question and I could find the answer by myself. I'm pretty stuck due to my lack of english vocabulary...
thx in advance
You can archive the wanted result with only one query:
SELECT username, MIN(time) AS lowertime
FROM test_table
WHERE stage='$stage' AND username='$temp'
GROUP BY username
ORDER BY time

How can I "predict" the outcome of a query?

This is my first question on here, but after some excessive searching I could not find a answer on my question and thought maybe you nice folks can help me out :) I am writing a script that behaves differently depending on what products someone had in their order. For explaining purposes: I have 10 customers. They all have a order_id. Within that order_id in a other table are all products_id's stored.
I want toe "predict" if an order has product_id 1 AND product_id 2, cause I need the script to behave differently. All others combinations are fine (so only product 1, or only product 2 or everything >= product 3.
Here is what I got so far (for readabillity, i left non-important stuff out),
<?php
$qGetMailadressen = 'A select EMAIL query';
while($emailrow = mysqli_fetch_assoc($mailadressenresult)) {
$customers_email = $emailrow['emailadres'];
$qGetLaatsteOrderid = 'A select LAST order from this email QUERY';
$orderidrow = mysqli_fetch_assoc($GetLaatsteOrderidresult);
$orderid = $orderidrow['orders_id'];
$lecountry = $orderidrow['customers_country'];
$country = $orderidrow['order_language'];
$qGetLaatsteProducten = "A select ALL PRODUCTS from this ORDERID QUERY";
while($productenrow = mysqli_fetch_assoc($GetLaatsteProductenresult)){
$productnaam = $productenrow['products_name'];
$productquantity = $productenrow['products_quantity'];
$productid = $productenrow['products_id'];
}
}
So in this last WHILE loop you see I get the product ID I need. And Ideally what I want is:
if ($productid == '1' AND $productid == '2'){
//do this
}else{
// do that
}
However im aware that is not possible cause its only IN the while loop that I know it. I tried putting all the data in an Array, but since I am out of the while loop im not sure how to do this.
I understand it might be very unclear, and im sorry for this. I hope you guys can help me out so I can clearify myself better if something is not clear.
Thank you!
/love Grumpy

PHP or SQL for Large Data and Sub/Related Data Sets

I can't imagine I'm the first or the last to ask about this, but I was unable to find the answer by searching.
I have a large dataset of orders in SQL Server. I need to return every order with each of their line items and each of their payments. I'm looking for the most efficient way to query and iterate through this data. I am using PHP/MSSQL to pull the orders, looping through those with foreach and querying for a list of items and payments would be incredibly inefficient.
I've thought about creating a union to create one massive dataset that has a bunch of columns, one of which is a column indicating what type of record (payment,line_item,order_data). But that also seems pretty inefficient.
This is an outline of the process I have been working with:
<?php
// query for orders
$records = sql_function("select * from v_migration_orders");
$json_output = array();
foreach($record as $r){
$data['order']['org_code'] = $r['org_code'];
$data['order']['po_number'] = $r['po_number'];
...
// query for line items
$data['order']['line_items'] = array();
$items = sql_function("select * from v_migration_line_items where invoice = ".sanitize_function($r['invoice']));
foreach($items as $i){
$line['line_item_type'] = $i['line_item_type'];
$line['sku'] = $i['sku'];
$line['legacy_id'] = $i['legacy_id'];
...
array_push($data['order']['line_items'],$line);
}
// query for payments
$data['order']['payments'] = array();
$payments = sql_function("select * from v_migration_payments where invoice = ".sanitize_function($r['invoice']));
foreach($payments as $p){
$pyt['Amount'] = $p['Amount'];
$pyt['payment_type'] = $p['payment_type'];
$pyt['Check_Number'] = $p['Check_Number'];
...
array_push($data['order']['payments'],$pyt);
}
array_push($json_output,$data);
}
echo json_encode($json_output);
With a focus on efficiency, I'm hoping someone in the community can help point me in the right direction here. The number of calls from the web server to the database server are triple what I'd like them to be. The alternative I can think of is to find a way to place them all into a single trip to the database and have PHP parse the full response once it receives it.
Below is the structure of the needed data I've put into views. Note that I'm using the integer, Invoice as the key to join on.
v_migration_orders:
line_type (value is: "Order")
Org_Code
PO_Number
Invoice
Tax_Total
Order_Total
EMAIL
status
order_t_stamp
order_legacy_id
v_migration_orders_line_items:
line_type (value is "line_item")
line_item_type
Invoice
sku
legacy_id
TITLE
quantity
unit_price
v_migration_orders_payments:
line_type (value is "payment")
Invoice
Amount
payment_type
Check_Number
Card_Processor
cc_message
card_type
cardholder_name
card_expiry
payment_token
payment_t_stamp
Thanks in advance!

Number of records returned after using prepared statement

I am currently taking an IT course in which people can bring in their computer(s) and the class works on them to get experience. Right now, the instructor has the customers fill out a sheet of paper giving their name, phone number and the computer's issue(s). However, he would like to use a PHP page to allow the students or himself look back to see what this person's previous issues were (if any). I am using PDO and prepared statements to query the database, but I am having trouble figuring out how to get the number of records returned by the prepared statement. I've tried using stmt_num_rows, but it doesn't appear to be working. Here is the code I have so far:
$custID = $_GET["id"];
$compID = $_GET["compID"];
$stmtIssues = $db->prepare("SELECT IssueID, DateRequested, Issue, ActionsTaken FROM ISSUES WHERE ComputerID=:compID AND CustomerID=:custID ORDER BY DateRequested");
$stmtIssues->bindParam(":custID", $custID);
$stmtIssues->bindParam(":compID", $compID);
$stmtIssues->execute();
$numIssues = stmt_num_rows($stmtIssues);
Am I doing this right?
Any and all help is greatly appreciated.
Chris
You could do a few things:
Solution one, if you just want the count, let the database count for you:
$stmtIssues = $db->prepare("SELECT COUNT(IssueID) FROM ISSUES WHERE ComputerID=:compID AND CustomerID=:custID ORDER BY DateRequested");
$stmtIssues->bindParam(":custID", $custID);
$stmtIssues->bindParam(":compID", $compID);
$stmtIssues->execute();
$numIssues = $stmtIssues->fetchColumn();
Solution two, if you're going to display the results in addition to the count:
$stmtIssues = $db->prepare("SELECT IssueID, DateRequested, Issue, ActionsTaken FROM ISSUES WHERE ComputerID=:compID AND CustomerID=:custID ORDER BY DateRequested");
$stmtIssues->bindParam(":custID", $custID);
$stmtIssues->bindParam(":compID", $compID);
$stmtIssues->execute();
$rows = $db->fetchAll();
$numIssues = count($rows);
foreach ($rows as $row) {
echo $row['IssueID']; // you can add other columns and/or formatting here too.
}
Solution one is quicker and returns only the count. Solution two, on the other hand, returns all details you may want to display.

how to write OSClass custom query to fetch result from DB

I m new to OSClass(OpenSource Classifieds).
i know its similar to wordpress., but i'm not sure how to write my own query like how i do in wordpress.
The right side bar will have cities/regions as links to display advertisements from that city/region.
The City/Region name is passed through the URL, and as per requirement i need to change the URL as virtual subdomain.
For example if the user click city1, then the URL should be http://city1.domainname.com/ and results asusual.
I used htaccess to change the virtual subdomain redirection but stuck with city and region.
to determine whether its a city or region i need to do a check with the database, for that i need write a custom query to match the value with the table..
so that i can display the results regarding the city/region.
Any ideas for this problem i'm facing..
Thanks.
I suggest you take a look to the models inside ./oc-includes/osclass/models/ to search regions and cities and other common queries.
Here is how I did in one of my plugins:
$conn = DBConnectionClass::newInstance();
$data = $conn->getOsclassDb();
$comm = new DBCommandClass($data);
$db_prefix = DB_TABLE_PREFIX;
$query = "SELECT * FROM `{$db_prefix}t_item` WHERE b_active=1 AND b_enabled=1";
$result = $comm->query($query);
if ($result) {
$items = $result->result();
foreach ($items as $item) {
var_dump($item);
}
}

Categories