Echo variable which has same name in php join - php

I have a mysql join which is pulling from two tables name product & cart and they're both being pulled from a variable $row_checkout
If i have to echo a certain field, i can normally go $row_checkout['cartid'] and that works fine.
However, i have a coloumn in each table which is called the same 'Status'.
How do i echo from one of the tables? I thought something like $row_checkout['cart.status'] might work but it doesnt appear to?
My database code is as follows:
$colname_checkout = "-1";
if (isset($row_booking['sessionid'])) {
$colname_checkout = (get_magic_quotes_gpc()) ? $row_booking['sessionid'] : addslashes($row_booking['sessionid']);
}
mysql_select_db($database_main, $main);
$query_checkout = sprintf("SELECT * FROM cart, productdatabase WHERE cart.productid = productdatabase.productid AND cart.status != 1 AND cart.status != 0 AND cart.sessionid = '%s' ORDER BY `name` ASC", $colname_checkout);
$checkout = mysql_query($query_checkout, $main) or die(mysql_error());
$row_checkout = mysql_fetch_assoc($checkout);
$totalRows_checkout = mysql_num_rows($checkout);

You can use alias to change a tables field name, to a name that you want.
the cart.status filter, you could make simpler, simpler by asking > 1
SELECT c.status as car_status, pro.status as pro_status
FROM cart as c, productdatabase as pro
WHERE c.productid = pro.productid AND c.status >1 AND c.sessionid = '%s'
ORDER BY `name` ASC", $colname_checkout
Seeing what you get, it will display an associative array with all names and values, that you can use to address the data
while ($row_checkout = mysql_fetch_assoc($checkout)) {
print_r($row_checkout);
}
or specific the fields:
while ($row_checkout = mysql_fetch_assoc($checkout)) {
echo $row_checkout["car_status"];
echo $row_checkout["pro_status"];
}
another comment, the mysql function is not recommended anymore. You could use MySQLi or PDO_MySQL. They are both object oriented and may need a little more time to learn.

Use alias.
Refernce :
http://www.tutorialspoint.com/sql/sql-alias-syntax.htm
$query_checkout =
sprintf("SELECT *,**cart.status AS cart_status, productdatabase.status as
pdb_status** FROM cart, productdatabase WHERE
cart.productid = productdatabase.productid AND
cart.status != 1 AND cart.status != 0
AND cart.sessionid = '%s' ORDER BY `name` ASC", $colname_checkout);

Related

How to create an alphabetized drop down menu in PHP

I'm trying to re-write this code so that the drop down menu is alphabetized:
$activeProjectDropdown.="<option value=''>Select Project</option>";
$getInfo = "SELECT id, customer, job_name, haul_info
FROM dispatch_jobs
WHERE (:mydate BETWEEN delivery_date AND delivery_date_end)
ORDER BY customer, job_name";
$result=DB::run($getInfo, ['mydate' => $myDate]);
while($row=$result->fetch(PDO::FETCH_BOTH)) {
if(!empty($row['haul_info'])) {
$haulinfo = "($row[haul_info])";
}else{
$haulinfo = "";
}
if($checkit == $row['id']){
$woot = 'selected=selected';
}else{
$woot = '';
}
$customerName = pdo_getName('name', 'customer', "$row[customer]");
$activeProjectDropdown.="<option value='$row[customer]|$row[id]' $woot>$customerName $haulinfo</option>\n";
}
In this code the query returns some rows from the database where customer is a numeric code which isn't in any kind of alphabetical order. Further down in the code a function called pdo_getName is called which takes a column of name table of customer and the id from $row['customer'] and queries the database, returning the stringified name of the customer. Because the name isn't being retrieved until later on down the loop I'm having trouble figuring out a way that I can alphabetize the $activeProjectDropdown. I've tried putting the $customerName and drop down code into an associative array, then sort that by $customerName and concat everything into a string, but that didn't work because there are duplicate keys. Down that same path, I could potentially have a nested array but I figure there must an easier solution I'm missing. Thanks for the help!
write a JOIN query and get all the data in one query then you can sort on the customers name as I think you are asking to do.
This will improve performance as well as simplify the code.
$getInfo = "SELECT dj.id, dj.customer, dj.job_name, dj.haul_info
c.name
FROM dispatch_jobs dj
LEFT JOIN customer c ON c.id = dj.customer
WHERE (:mydate BETWEEN dj.delivery_date AND dj.delivery_date_end)
ORDER BY c.name, dj.job_name";
$result=DB::run($getInfo, ['mydate' => $myDate]);
while($row=$result->fetch(PDO::FETCH_BOTH)) {
if(!empty($row['haul_info'])) {
$haulinfo = "($row[haul_info])";
}else{
$haulinfo = "";
}
if($checkit == $row['id']){
$woot = 'selected=selected';
}else{
$woot = '';
}
$activeProjectDropdown.="<option value='$row[customer]|$row[id]' $woot>$row[name] $haulinfo</option>\n";
}
Try this:
SELECT ... ORDER BY customer ASC, job_name
This sorts everything by costumer (ascending) first, and then by job_name (ascending, which is the default) whenever the costumer fields for two or more rows are equal.
more info here

Using form to show all records where certain value is greater than X

For this problem I need to make a PHP page where the user can search an invoice table by inputting a "quantity" value. The form then takes that quantity and spits out a table with the name, invoice number, quantity, and item description for all invoices where the quantity exceeds the quantity the user submitted.
For the most part I have my page set up and working fine. Where I'm getting stuck is on the query side -- specifically, the code below is providing me a list of invoices where the quantity is identical to the input quantity.
I've tried changing "WHERE ii.quantity LIKE ?" to "WHERE ii.quantity > ?" but all that does is provide me a list of all invoices without filtering by the user submitted quantity.
$query =
"SELECT c.first_name, c.last_name, ii.invoice_id, ii.quantity, it.description
FROM `c2092`.`customer` c
JOIN `c2092`.`invoice` i ON c.customer_id = i.customer_id
JOIN `c2092`.`invoice_item` ii ON ii.invoice_id = i.invoice_id
JOIN `c2092`.`item` it ON it.item_id = ii.item_id
WHERE ii.quantity LIKE ?
ORDER BY ii.invoice_id";
This is too complex query. Try to make explain on it. I am sure it will use filesort, and even temp table.
The better approach is to make several queries:
$invoiceItems = $db->query(
"SELECT ii.invoice_id, ii.id, ii.quantity, it.description
FROM `c2092`.`invoice_item` ii
JOIN `c2092`.`item` it ON it.item_id = ii.item_id
WHERE ii.quantity > ?
ORDER BY ii.invoice_id");
$invoiceItemMap = [];
$invoiceIds = [];
foreach ($invoiceItems as $invoiceItem) {
$invoiceItemMap[$invoiceItem['invoice_id']][] = $invoiceItem;
$invoiceIds[$invoiceItem['invoice_id']] = $invoiceItem['invoice_id'];
}
$invoiceIds = array_values($invoiceIds);
$userInvoices = $db->query(
"SELECT c.first_name, c.last_name, i.invoice_id
FROM `c2092`.`invoice` i
JOIN `c2092`.`customer` c ON c.customer_id = i.customer_id
WHERE i.id IN (".implode(',', $invoiceIds).")");
$result = [];
foreach ($userInvoices as $row) {
$result[] = array_merge($row, $invoiceIds[$row['invoice_id']]);
}
Hello,
What is the value of your variable?
Prefer the use of named parameter instead of ? syntax.

Set all products to use default values all stores

I have a Magento 1.5.0.1 install with 3 different store views. At some point along the way two of the stores dont use the default values for product attributes. I am trying to find a way to make all products use default values for all stores, that way the client only has to update things in one place. I found this article but it seems like it only applies to specifically called products. Can anyone explain how to employ that code in my situation? Or suggest new code?
The only way I could get this to work was via MySQL:
DELETE FROM `catalog_product_entity_text` where store_id != 0;
DELETE FROM `catalog_product_entity_datetime` where store_id != 0;
DELETE FROM `catalog_product_entity_decimal` where store_id != 0;
DELETE FROM `catalog_product_entity_int` where store_id != 0;
DELETE FROM `catalog_product_entity_varchar` where store_id != 0;
The above will reset all products to use default values for all attributes.
You should use the Mage::getSingleton('catalog/product_action') to update a lot of product in a row.
1°) Get the ids of product you want, for all product use :
$ids = Mage::getModel('catalog/product')->getCollection()->getAllIds();
2°) Make the list of the attribute and associate the value "false"
$attributes = array('name'=>false,'description'=>false,....)
3°) Pick up the list of store ids to change and set it in an array too :
$stores = array(1,2,3);
Then create your script :
foreach ($stores as $store_id)
{
Mage::getSingleton('catalog/product_action')->updateAttributes($ids, $attributes, $store_id);
}
It will update all products (ids) to set the attributes to default (thanks to the "false" value) in the store_id.
This will take values that have been set on any store and merge those into the default values for all products:
<?php
$cat = mysql_connect("host", "user", "password") or die(mysql_error());
mysql_select_db("database",$cat) or die(mysql_error());
$types = array(
'catalog_product_entity_text',
'catalog_product_entity_datetime',
'catalog_product_entity_decimal',
'catalog_product_entity_int',
'catalog_product_entity_varchar'
);
foreach($types as $type){
$result = mysql_query("select * from $type where store_id != 0",$cat) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
if(!is_null($row['value'])){
mysql_query("update $type set value = '".mysql_real_escape_string(stripslashes($row['value']))."'
where store_id = '0'
and entity_id = '".$row['entity_id']."'
and attribute_id = '".$row['attribute_id']."'",$cat) or die(mysql_error());
}
mysql_query("delete from $type where value_id = '".$row['value_id']."'",$cat) or die(mysql_error());
}
}
?>

How to get a session value from a second table?

I have two tables for the users; a login table and the user profile table.
I want to compare a value from 'userprofiletable' to another value from another table called posts. If the value is equal, it shows a list.
I have the following code. The problem is that it is not comparing the value in the posts table with the value of the session from user profile table.
Could someone help me please?
<?php
$limit = '5';
$dbreq = 'SELECT * FROM `posts` ORDER BY `pos` DESC';
$dbdata = mysql_query($dbreq);
while($dbval = mysql_fetch_array($dbdata))
{
if (($dbval['city'] == $_SESSION['student_city'])) { //checks for last 4 accomodation
if ($limit >= '1') {
echo '<tr><td>'.$dbval['title'].'</td></tr>';
$limit = $limit -'1';
}
}
}
?>
I also want to get the value of userprofiletable and post it in the posts table. For example, when somebody make a new post.
Your post is a bit unclear, but I think this is what you want:
<?php
$userid = 11542;//Sample uid. You will have to figure this out and set it.
$limit = 5;
$dbreq = "SELECT * FROM `posts` WHERE `userid`=".$userid." ORDER BY `pos` DESC LIMIT=".$limit.";";
$dbdata = mysql_query($dbreq);
while($dbval = mysql_fetch_array($dbdata))
{
if (($dbval['city'] == $_SESSION['student_city'])) { //checks for last 4 accomodation
echo '<tr><td>'.$dbval['title'].'</td></tr>';
}
}
?>
The question is not clear, but there could be two answers:
To reproduce your code, you can do in ONE sql query:
$dbreq = 'SELECT *
FROM `posts`
WHERE city="'.mysql_real_escape_string($_SESSION['student_city']).'"
ORDER BY `pos` DESC
LIMIT 4';
If, however, there are two tables, then you need "LEFT JOIN" linking the posts table to the userprofile table
$dbreq = 'SELECT p.*, u.*
FROM posts p
LEFT JOIN userprofiletable up ON p.UserID=up.UserID
WHERE up.city="'.mysql_real_escape_string($_SESSION['student_city']).'"
ORDER BY p.pos DESC
LIMIT 4';
(UserID in the table above is the name of the field in the posts table and userprofiletable that links the two.)

mysql - if value = 0 shorten where statement

I wonder if it's possible to shorten query depending on some variable value in elegant way.
For example: I have value named $var = 0 and I would like to send a query that looks like this:
$query = "SELECT id, name, quantity FROM products WHERE quantity > 100";
But whan the $var != 1 I'd like to send a query like this:
$query = "SELECT id, name, quantity FROM products WHERE quantity > 100 AND id = '$var'";
So depending on value of $var I want to execute one of queries. They differ only with last expression.
I found two possible solutions but they are not elegant and I dont like them at all.
One is made in php:
if ( $var == 0 ) {
$query_without_second_expression
} else {
$query_with_second_expression
}
Second is made in mysql:
SELECT WHEN '$var' <> 0 THEN id, name, quantity
FROM products WHERE quantity > 100 AND id = '$var' ELSE id, name, quantity
FROM products WHERE quantity > 100 END
but i dont like it - each idea doubles queries in some whay. Can I do something like this?
SELECT id, name, quantity
FROM products WHERE quantity > 100
CASE WHEN $var <> 0 THEN AND id = '$var'
It's much shorter, and adds part of query if needed. Of course real query is much more complicated and shorter statement would be really expected. Anyone has an idea?
If I understand well..
$query = "SELECT id, name, quantity FROM products WHERE quantity > 100";
if ( $var != 0 ) {
$query .= " AND id = '$var'";
}
do you like it?
You could so something like this on the SQL side:
"SELECT id, name, quantity FROM products WHERE quantity > 100 AND (id = '$var' OR '$var' = 0)
But performance could be impacted. I would suggest building the appropriate query on the PHP side.
I'm no PHP developer (it is PHP, right?), but wouldn't it be easiest to build your query from a concatenated string?
Pseudo-code:
$my_query = "SELECT id, name, quantity FROM products WHERE quantity > 100"
if ($var != 1)
$my_query = $my_query + " AND id = '$var'";
end if;
/*go ahead with your query*/
You can do this:
SELECT id, name, quantity
FROM products
WHERE 1 = 1
AND ( $q IS NULL OR quantity > $q)
AND ( $var IS NULL OR id = $var)
If you want only the first condition to run then pass $q = 100 and $var = NULL, therefore the second condition will be ignored. And for the second query pass the $q = 100 and $var = id value and you will got the your second query.
If they only differ in additional where-statements, I would probably still stay in PHP and do the following:
$conditions = array();
$conditions[] = "(quantity > 100)"
if ($var == 0)
$conditions[] = "(id = '$var')";
if (some-other-expression)
$conditions[] = "(myfield = 'foo' OR myfield = 'bar')";
$sql = "
SElECT id, name, quantity
FROM products
WHERE
";
$sql .= $conditions.join(" AND ");
/ Carsten
I would use a ternary for this:
$query = "SELECT id, name, quantity FROM products WHERE quantity > 100" . ( $var != 0 ? " AND id = '$var'" : '' );
I'm an Oracle guy, but could you use the IF() function in your constraints, e.g.:
SELECT id, name, quantity
FROM products
WHERE quantity > 100
AND id = IF('$var'=0,'%','$var');
The '%' is a wildcard that would match anything, effectively ignoring the 2nd expression.
So if you are using the
If or the CASE
Why don't you use them in your sql query.
It would be some like
if ( $var == 0 ) {
$query_without_second_expression
}
else
{
$query_with_second_expression
}
But in you sql query.
DECLARE #var int
if(#var=1)
BEGIN
query 1
END
else
BEGIN
query 2
end
I guess this will solve your problem.
But as a personal advice try to make one query. Even with the variable. We don't believe in changing standard query depending on the conditions.
Still your wish and your desire
Cheers!!
For this particular problem, go with Paper-bat's simple condition append snippet.
However, if you have entirely different where statements, consider appending the appropriate where statement to the query once you know what you want. For instance,
$query = "SELECT id, name, quantity FROM products ";
if ( $var == 0 ) {
$query .= "quantity > 100";
} elseif {
$query .= "quantity > 120 AND id = '$var'";
} elseif {
...
}
...
It all depends on your needs, but neither this or Paper-bat's solutions duplicate query code.

Categories