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

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

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

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!

Sum variables in an array using while loop only 1 iteration per refresh PHP SQL

Hello stackoverflow, long time lurker first time asker. Anyways I am creating a project for my school and it is almost completely finished but I think I need help with the while loop. I am trying to sum the variables that are stored in the array and then output that into a useable variable that I can sum with another variable. The problem is the loop only does 1 iteration every time I refresh to page. So it will eventually get the full array but only one item at a time. Please let me know what I am going wrong, I'm sure its something dumb!
$bill= mysql_query("SELECT Transaction.date, Transaction.Price, Transaction.customer_customer_id, Service.cost, Service.user_id, Service.uname
FROM *.Transaction,*.Service
WHERE Transaction.customer_customer_id = Service.user_id AND Service.uname = '$uuname'");
$query_row=mysql_fetch_array($bill);
$userservice = ($query_row[cost]);
$userprice = ($query_row[Price]);
$row2=array();
while($row = mysql_fetch_array($bill))
{
$row2[] += $row['cost'];
}
$totalservice = array_sum($row2);
Thanks for any help you guys may have. This one is frying my brain.
Both your SQL and your PHP make no sense.
FROM *.Transaction,*.Service
...will throw an error in MySQL, but your code doesn't check for errors. I suspect it should be:
FROM Transaction, Service
While the PHP will parse and run.....
while($row = mysql_fetch_array($bill)) {
$row2[] += $row['cost'];
}
$totalservice = array_sum($row2);
Is a very strange way to populate an array. Why not just....
while($row = mysql_fetch_array($bill)) {
$totalservice+=$row['cost'];
}
Indeed, if you are just throwing away the rest of the data, then why are you fetching it from the database?
SELECT SUM(Service.cost)
FROM Transaction,Service
WHERE Transaction.customer_customer_id = Service.user_id
AND Service.uname = '$uuname'
In which case the join is also redundant:
SELECT SUM(Service.cost)
FROM Service
WHERE Service.uname = '$uuname'
Rewrite query as
SELECT Service.user_id, Service.uname, SUM(Service.cost) as cost
FROM djqrico_hotel.Transaction LEFT JOIN djqrico_hotel.Service ON Transaction.customer_customer_id = Service.user_id
WHERE Service.uname = '$uuname' GROUP BY Service.user_id
if you want to get sum of all user's transactions.
The problem is the loop only does 1 iteration every time I refresh to page.
Have you ran the query against the database and checked if it's returning more than one row?
Also, if all you want to do is sum the cost column you could do that in sql:
SELECT SUM(cost)[....]

php for loop query in magento

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

Quest system with prerequisites

I'm coding a quest system for my site that pretty much works like any you find in an MMORPG. I've got the whole thing working, but I really need to speed things up since I coded it inefficiently. Not because I can't code, but because I just wasn't sure how to go about it.
Basically I want to display all the quests that are available to the user. There are quests with no requirements, and some with. To see if a quest has already been completed, and a quest is available you would check the questuser table for the value of questuserCompleted. If it's 1, then it's complete.
Here are the tables I have. I left irrelevant things out.
quest table - Holds all the quest data
questID
questNPC
Where they get the Quest from
questPreReq
refers to a quest they would have needed to comple to get this one
questuser table - Holds all the quests the user has accepted, complete or not
questuserID
questuserUser
User's ID
questuserQuest
refers to the ID of the quest from the quest table
questuserCompleted
0 is in progress, 1 is complete
There's definitely a better way to do than I have now. I'm usually more efficient at things like this, but since I've never coded something like this before, I'm not really sure how to go about it.
Basically it just loops through every single quest, and with an if statement, it checks for questuserCompleted. Once there starts to be a lot of quests, this would get pretty slow for each load of the page.
function displayAvailable($npc = 0){
$completed[] = 0;
$notCompleted = array();
$query=mysql_query("
SELECT a.questID, a.questPreReq, a.questTitle, b.questuserCompleted, a.questText , a.questNPC
FROM quest a
LEFT JOIN questuser b ON a.questID = b.questuserQuest AND b.questuserUser = '".$this->userID."'
ORDER BY a.questID");
$comments = $this->ProcessRowSet($query);
$num = mysql_num_rows($query);
if($num){
foreach ($comments as $c){
if($c['questuserCompleted']){
$completed[] = $c['questID'];
}else{
$notCompleted[] = $c['questID'];
}
if(in_array($c['questPreReq'], $completed) && !in_array($c['questID'], $completed) && $c['questuserCompleted'] != '0'){
if($npc == 0 || $c['questNPC'] == $npc){
$count++;
$return .= "<p>".$c['questTitle']."</p>";
}
}
}
}
if(!$count){
$return = "You have no available quests";
}
return $return;
}
Thanks for any help.
Subqueries to the rescue
SELECT a.questID, a.questPreReq, a.questTitle, a.questText , a.questNPC
FROM quest a
WHERE a.questPreReq IS NULL
OR a.questPreReq IN (SELECT questuserQuest FROM questuser WHERE questuserUser = 'UserID' AND questuseCompleted = 1)
ORDER BY a.questID
So you let the database sort it out for you, this should be superfast.
The query is missing the exclusion of quests the user already did, I leave this as an exercise as I am writing on my smartphone ; )

Categories