How can i create arrays from a query in php - php

in my data base i have a table "options" which contains options from my site like title, language etc.
i want to load all this options and store it in a array query the database.
this code works manual
$option=array("title" => "Site's title", "option2" => "option 2 value");
echo $option[title];
but when i make the query...
$query_options=mysql_query("SELECT * FROM options");
while($data_options = mysql_fetch_row($query_options)){
$option=array($data_options[1] => $data_options[2]);
}
echo $option[title];
it doesn't work.
Hope you can help me.
Thank you

mysql_fetch_row() only allows you to access columns in your query based on the column ordering : $options[0] or $options[1].
Use mysql_fetch_array() instead. With it you can access data with $options["title"] for example. Using the column name.
See the doc at http://www.php.net/manual/fr/function.mysql-fetch-array.php
PS - Don't forget to put title between quotes too!

$query_options=mysql_query("SELECT * FROM options");
$array = array();
while($data_options = mysql_fetch_array($query_options)){
$array[]["title"] = $data_options['title'];
$array[]["value"] = $data_options['value'];
}
var_dump($array);
Should work. lemme know how it goes.
Also, you should know that you shouldn't use any mysql_* commands, they're becoming depreciated as they're in-secure, you should take a look here
http://www.php.net/manual/en/ref.mysql.php
and
http://www.php.net/manual/en/ref.mysqli.php

Related

Trying to print values in multidimensional array to form as presets values

I'm currently working on a project where my current goal is to print information about the specific user on the final checkout form inputs.
First off I gather the information of the specific user through a public function:
public function getUserAddress($dbh)
{
$sql = "SELECT street, zip, city FROM address WHERE user_id=:user";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':user', $this->uid);
$stmt->execute();
$userAddress = $stmt->fetchAll(PDO::FETCH_ASSOC);
$this->userAddress = $userAddress;
return $this->userAddress;
}
Then I store the information in a variable I call $userAddress
$userAddress = $user->getUserAddress($dbh);
Since the user has two addresses, both with a "Street", "City" & "Zip" I'm storing both arrays in $templateData. This way I can specify what index should be printed out in which input tag instead of having to create a new function for each slot.
$templateData['user']['address'] = $userAdress['street']." ".$userAddress['city']." ".$userAddress['zip'];
However, printing these out seems near impossible. When I var_dump
$templateData['user']['address']
I only seem to be getting 2 empty strings and nothing else.
This is just code from my Checkout.controller but somehow the information doesn't seem to be found in my template page. All routes and includes are correct so dw about that.
I'm quite new to all this so I'd appreciate any help I can get!
Image of how the information should be presented https://gyazo.com/40fa06832207bd785ee038af4962bb1e
So in this case: "Postort" = "City" & "Gatuadress" = "Street"
PDO::fetchAll(PDO::FETCH_ASSOC) will return an array of associative arrays; so to access the individual elements you need something like:
$userAdress[0]['street']." ".$userAddress[0]['city']." ".$userAddress[0]['zip']
I could alaways define every single one of them specifically although it seems far fetched. Something like this:
$templateData['user']['address'][0]['street'] = $userAddress[0]['street'];
$templateData['user']['address'][0]['city'] = $userAddress[0]['city'];
$templateData['user']['address'][0]['zip'] = $userAddress[0]['zip'];
$templateData['user']['address'][1]['street'] = $userAddress[1]['street'];
$templateData['user']['address'][1]['city'] = $userAddress[1]['city'];
$templateData['user']['address'][1]['zip'] = $userAddress[1]['zip'];
I'm basically looking for another solution which doesn't require so much repetition.

Show names separated (Getting names from database)

In my database I have one column named name and in each row of that column I'm saving names like this /Mary/Sam/Bob/Michael/. To show the values in my page I need to separate them by breaking the line in each /. Can someone help me?
If I make one echo of my column I will get /Mary/Sam/Bob/Michael/ but I want:
Mary
Sam
Bob
Michael
$names=explode('/', $dbrow['name']);
foreach($names as $aname){
echo $aname.'<br>';
}
Use the explode function with array_filter function
$database_column_string = "/Mary/Sam/Bob/Michael/";
$names = array_filter(explode('/',trim($database_column_string )));
foreach($names as $name){
echo $name;
echo "<br/>";
}
\n may not render a new line in the web browser. So it's better to replace \ with the br tag:
str_replace ("/" , "<br>" , "/Mary/Sam/Bob/Michael/");
The explode function will fix your problem but you should be aware that the way you're using your database is violating the first normal form. Each record should have the same number of attributes.
Here is a guide to the normal forms http://www.bkent.net/Doc/simple5.htm
You should redesign your database to have a table called, for example, Names(id, name)

Simple Dom HTML tags without attributes

Hello I am trying to pull back roster information from ESPN.com. Each team's roster is saved into a table. I am trying to figure a way to save each tag into a variable as appropriate however each tag does not have an ID such as "jersey_number"/"player_name" so search through this has given me some problems. Here is what I have so far - If you could give me a pointer or 2 that would be much appreciated.
<?php
require_once("../tools/simple_html_dom.php");
require_once("../tools/Utilities.php");
$url = "http://espn.go.com/nfl/team/roster/_/name/den/denver-broncos";
$espnHTML = file_get_html("http://espn.go.com/nfl/team/roster/_/name/den/denver-broncos");
foreach($espnHTML->find("table.tablehead",0)->find('tr[class^=odd]') as $rosterRow)
{
foreach($rosterRow->find("td") as $playerInfo)
{
echo $playerInfo->plaintext."<br>";
}
}
?>
How can I assign these td tags into appropriate variables without "ids"? Attached is a sample screenshot that may help you understand what I am talking about.
If the columns are in the same order for every player, using your $rosterrow->find("td") should return an indexed array that you can access using $playerrow[0..n].
Then, by analyzing what corresponds to what you can make a function like this:
$players = array();
foreach($espnHTML->find("table.tablehead",0)->find('tr[class^=odd]') as $rosterRow)
{
$playerRow = $rosterRow->find("td");
$name = $playerRow[0];
$jersey = $playerRow[1];
// more can be added, of course.
$players[$name] = array();
$players[$name]["jersey"] = $jersey;
// and others
}
For table
John Appleseed | 12
---------------|----
Richard Brooks | 34
this will result in an array like
{ "John Appleseed" => { "jersey" => 12 }, "Richard Brooks" => { "jersey" => 34}}
Please let me know if this helped.
If you're open to a different approach that may be more scalable/robust, then you may also want to take a look at Kimono Labs. You can use it to create structured API based on ESPN's data. I think you'd be able to define which part of the table held names, scores, etc. and would easily be able to call the API for the desired info.

Adding an Array multiple times in the DB via Controller

I'm having an issue producing this array multiple times upon how many coupons purchased.
Now it looks like
$coupon_array = array(
'user_id'=>$_POST["user_id"],
'mergent_id'=>$_POST["merchant_id"],
'deals_id'=>$_POST["deal_id"],
'order_id'=>$order_id,
'secret'=>$secret,
'expire_time'=>$time,
'create_time'=>$time,
'status'=>1
);
$this->common_model->insertData('coupon', $coupon_array);
But i have a post value such as:
"quantity"=>$_POST["quantity"]
and i would like to produce this X times. Example:
$quantity x $this->common_model->insertData('coupon', $coupon_array);
Sorry for my english, and i hope i explain this so it's understandable... ;)
Another one! when we insert the coupons they all have the same md5($secret), is it possible to have that also with all the different code...
$secret = md5($secret);
$coupon_array = array(
'user_id'=>$_POST["user_id"],
'mergent_id'=>$_POST["merchant_id"],
'deals_id'=>$_POST["deal_id"],
'order_id'=>$order_id,
'secret'=>$secret,
'expire_time'=>$time,
'create_time'=>$time,
'status'=>1
);
Well, if I understand what you want, you can use for, but that's obvious:
for($i=0; $i<$this->input->post('quantity');$i++) {
$coupon_array['secret'] = md5($coupon_array['secret'].$i);
$this->common_model->insertData('coupon', $coupon_array);
}
Also, never use $_POST["..."] in CodeIgniter, use only $this->input->post('...') as it escapes properly. More info about input class can be found here.
for ($i=0; $i<$quanity; $i++) {
$this->common_model->insertData('coupon', $coupon_array);
}

How do I get the Position of an Attribute-Option in Magento?

I've got the following problem. In an extra module, I want to sort the options of an attribute, based on their position. When I try to get the Option of an Attribute, I can get the Id and the Label, but there is nothing mor ein that object.
I can do, for example, this:
$attribute = $_product->getResource()->getAttribute($code)->getOptionsText($value):
Or just getOptionId($value), but there is nothing to get the Position, which is editable in the backend. So, how to get this? Havn't found anything (useful) on the net yet.
(Also the similar question magento sort attribute option collection by position? doesnt give any help)
EDIT:
What I managed to do, is doing a direct SQL statement, like this:
SELECT sort_order FROM mag_eav_attribute_option WHERE option_id = 114 AND attribute_id = 533;
But I think, there is a better option to get that value.
I found the answer myself and want to share it with you.
$attribute = Mage::getModel('eav/entity_attribute')->load( $code, 'attribute_code');
$option_col = Mage::getResourceModel( 'eav/entity_attribute_option_collection')
->setAttributeFilter( $attribute->getId() )
->setStoreFilter()
->setPositionOrder( 'ASC' );
$option_col->getSelect()->order('main_table.sort_order '.$orderby);
I hope it helps someone.
This is actually quite simple if you take a look # Mage_Eav_Block_Adminhtml_Attribute_Edit_Options_Abstract
$attributeId = 230;
$options = Mage::getResourceModel('eav/entity_attribute_option_collection')
->setAttributeFilter($attributeId)
->setPositionOrder('desc', true)
->load();
foreach($options as $opt){
Mage::log($opt->getSortOrder());
}
I see you came up with something similar already but I thought I would post this as it may be helpful to others.
Start to debug then:
print_r($_product->getResource()->getAttribute($code));
print_r($_product->getResource()->getAttribute($code)->getData());
print_r(get_class_methods($_product->getResource()->getAttribute($code)));
Okay, so you have your attribute code $code and your attribute option value $value. Then you can get the corresponding sort order like that:
$source = $product->getResource()->getAttribute($code)->getSource();
$optionId = $source->getOptionId($product->getData($code));
$optionSortOrder = Mage::getResourceModel('eav/entity_attribute_option_collection')
->setIdFilter($_optionId)
->getFirstItem()
->getSortOrder();
From: http://www.phptechi.com/getting-product-attributes-values-and-labels.html
How to fetch attribute value sort order?
Here is the Quick and Easy way using SQL to get attribute value sort positing.
Change value for variables in following code:
$CurtAtr is current attribute like color, size, etc
$attrVal is attribute value e.g. size has "small, medium, Large, etc"
$resource = Mage::getSingleton('core/resource');
$read = $resource->getConnection('catalog_read');
$read->fetchAll("SELECT ao.sort_order FROM eav_attribute_option_value as aov, eav_attribute_option as ao where value='$attrVal' and aov.option_id = ao.option_id and attribute_id=$CurtAtr limit 1");

Categories