Returning an array using PDO - postgresql

I'm trying to use PDO using the following code, I want to select the array of values for the context_list, but it returns one record, any ideas where I'm going wrong?
try {
$sql2 = "SELECT area_easting, area_northing, context_number FROM excavation.contexts";
$sth = $conn->prepare($sql2);
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC))
{
$easting_list = $row['area_easting'];
$northing_list = $row['area_northing'];
$context_list = $row['context_number'];
}
}
catch(PDOException $e )
{
echo "Error: ".$e;
}
echo "context list: ";
echo $context_list;
A partial solution:
This worked:
$query = $conn->prepare("SELECT area_easting, area_northing, context_number FROM excavation.contexts");
$query->execute();
while($r = $query->fetch(PDO::FETCH_OBJ)){
echo $r->area_easting, '|';
echo $r->area_northing;
echo '<br/>';
}
But Now I need to make the $r->area_easting accessible to the session, but that's another question.

Your query may return several records (provided they actually exist in the table).
Your code loops through all the records (with the while loop) but the values ($easting_list, $northing_list and $context_list) are overwritten in the loop.
I suggest the following changes to your code:
$easting_list = array();
$northing_list = array();
$context_list = array();
try {
$sql2 = "SELECT area_easting, area_northing, context_number FROM excavation.contexts";
$sth = $conn->prepare($sql2);
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC))
{
$easting_list[] = $row['area_easting'];
$northing_list[] = $row['area_northing'];
$context_list[] = $row['context_number'];
}
}
catch(PDOException $e )
{
echo "Error: ".$e;
}
echo "context list: ";
echo implode(', ', $context_list);
Now all the values are stored in 3 arrays. explode is used to print a comma-separated list of all values in $context_list array.

Related

Getting sum in PHP MySQL

I want to get sum of integers that are selected from mysql
Here is my code
<?php
Include 'init.php';
$page = '2459';
$ttl = array();
$search = $db->link->query("SELECT id,packid,rating FROM pakrate WHERE packid LIKE '%$q%'");
if($search->num_rows>0){
while($result=$search->fetch_assoc()){
$ttl[] = $row['rating'];
echo $ttl;
echo $result[SUM('rating')];
}
}
else {
echo "no such query";
}
So what I am doing wrong here, any other suggestions?
Just run the sum in your query
<?php
Include 'init.php';
$page = '2459';
$ttl = array();
// Not sure why you're doing this but there should only be one leading connection ($conn->query) unless you're doing some object item elsewhere in init.
// I would also use prepared statements since they're more secure:
$q = "%$q%"; // create your like variable, wherever $q is coming from??
$query = "SELECT sum(rating) from pakrate WHERE packid LIKE ?);
$stmt = $db->prepare($query); // assuming $db is your connection variable
if($stmt){
$stmt->bind_param("s",$q); // Bind the variable in
$stmt->execute(); // Execute
$stmt->bind_result($rating); // Bind the result variable
$stmt->store_result(); // Store it so you can get num_rows
$rows = $stmt->num_rows; // assign rows found
if($rows > 0){
while($stmt->fetch()){ // Loop the result
$ttl[] = $rating; // add to your array
// You can't echo an array like this.... echo $ttl;
// if you really want to, print_r($ttl);
}
}
$stmt->close(); // Close it
}
?>

How can set up the table correctly for receiving the string converted from dates?

I have a problem and don't know how to solve it. After i run the code i didn't receive corectly a period of time. I put the code here.
I think something is wrong with table from database (i use PhpMyAdmin 4.2.0 module from EasyPhp). I put an image too to see what happens. The dates marked with red need to be at the end of table.
<?php
function data_range($first, $last, $step = '+1 day', $output - format = 'd-m-Y')
{
$dates = array();
$current = strtotime($first);
$last = strtotime($last);
while ($current <= $last)
{
$dates[] = date($output_format, $current);
$current = strtotime($step, $current);
}
foreach($dates as $zile)
{
$krr = explode('-', $zile);
var_dump($krr);
$result2 = implode('/', $krr);
echo $result2 . "<br/>";
$sql4 = "INSERT INTO studenti3 (data) VALUES ('$result2')";
$rez4 = mysql_query($sql4);
}
var_dump($dates);
}
$first = "06-04-2015";
$last = "07-05-2015";
$step = "+1day";
$output_format = 'd-m-Y';
date_range($first, $last, $step, $output_format); ?>

Result binding in mysqli

In the following example, can any folks show me how to code the binding part as I select all fields from the table
$stmt = $mysqli_conn->stmt_init();
if ($stmt->prepare("SELECT * FROM books")) {
$stmt->execute();
$stmt->bind_result( **WHAT DO I PUT HERE** );
$stmt->close();
}
In bind_result, you put in the variables where you want to fetch the data into, instead of using an array returned otherwise.
$stmt->bind_result($col1, $col2, $col3, $col4);
while($stmt->fetch_assoc())
echo "$col1 $col2 $col3 $col4";
Alternatively, if you don't want to bind the result
while($resultArray = $stmt->fetch_assoc()) {
echo "$resultArray[columnName1] $resultArray[columnName2] ...";
}

Magento - Get list of all Manufacturers with product count

I am using the following code to list all the manufacturers and it works like a charm:
$attribute = Mage::getModel('eav/entity_attribute')
->loadByCode('catalog_product', 'manufacturer');
$valuesCollection = Mage::getResourceModel('eav/entity_attribute_option_collection')
->setAttributeFilter($attribute->getData('attribute_id'))
->setStoreFilter(0, false);
$preparedManufacturers = array();
foreach($valuesCollection as $value) {
$preparedManufacturers[$value->getOptionId()] = $value->getValue();
}
if (count($preparedManufacturers)) {
echo "<h2>Manufacturers</h2><ul>";
foreach($preparedManufacturers as $optionId => $value) {
echo "<li>" . $value . " - (" . $optionId . ")</li>";
}
echo "</ul>";
}
What I am looking for is a way to display the number of products associated with each of the manufacturers. Can someone please tell me the way of doing this?
Many thanks
Not all mine, but works for me in 1.6+?
<?php
include_once 'app/Mage.php';
Mage::app();
$attribute = Mage::getModel('eav/entity_attribute')
->loadByCode('catalog_product', 'manufacturer');
$valuesCollection = Mage::getResourceModel('eav/entity_attribute_option_collection')
->setAttributeFilter($attribute->getData('attribute_id'))
->setStoreFilter(0, false);
$preparedManufacturers = array();
foreach ($valuesCollection as $value) {
$preparedManufacturers[$value->getOptionId()] = $value->getValue();
}
if (count($preparedManufacturers)) {
echo "<h2>Manufacturers</h2><ul>";
foreach ($preparedManufacturers as $optionId => $value) {
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addFieldToFilter(array(array('attribute' => 'manufacturer', 'eq' => $optionId)));
$mumberOfProducrt = count($collection);
echo "<li>" . $value . " - (" . $mumberOfProducrt . ")</li>";
}
echo "</ul>";
}
?>
This would work but won't be the most efficient:
foreach($valuesCollection as $value) {
$preparedManufacturers[$value->getOptionId()] = $value->getValue();
$collection = Mage::getModel('catalog/product')->getCollection();
$collection
->addAttributeToSelect('*') // '*' not efficient though
->addAttributeToFilter('manufacturer', array('eq' => $value->getOptionId()))
//->addAttributeToFilter('manufacturer', $value->getOptionId())
;
$count = $collection->->getSize();
}
It's an extra query for each manufacturer so it's not great, if you have some caching etc it won't be too bad though.
Working code should do it
$collection = Mage::getModel('catalog/product')->getCollection()->groupByAttribute('manufacturer')
->addFieldToFilter('status',Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
->addExpressionAttributeToSelect("count",'COUNT({{entity_id}})', 'entity_id');
Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($collection);

insert_id mysqli

I'm trying to return the inserted id from a mysql INSERT query. Each time I run the function I get 0 as the result. Can someone please explain at what point I can retrieve the value because although the script below executes I cannot retireve the inserted id. Probably done something stupid.
<?php
public function execSQL($sql, $params, $close){
$mysqli = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$stmt = $mysqli->prepare($sql) or die ("Failed to prepared the statement!");
call_user_func_array(array($stmt, 'bind_param'), $this->refValues($params));
$this->insert_id($this->connection);
$stmt->execute();
if($close){
$result = $mysqli->affected_rows;
} else {
$meta = $stmt->result_metadata();
while ( $field = $meta->fetch_field() ) {
$parameters[] = &$row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $this->refValues($parameters));
while ( $stmt->fetch() ) {
$x = array();
foreach( $row as $key => $val ) {
$x[$key] = $val;
}
$results[] = $x;
}
$result = $results;
}
$stmt->close();
$mysqli->close();
return $result;
}
?>
Check $mysqli->insert_id after executing insert query.