Get database records in TYPO3 viewHelper - sql

I want to create a database query in a view helper, this works with the following code:
$uid = 11;
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('tx_test_domain_model_author');
$query = $queryBuilder
->select('*')
->addSelectLiteral(
$queryBuilder->expr()->count('tx_test_domain_model_author.author', 'counter')
)
->from('tx_test_domain_model_author')
->join(
'tx_test_domain_model_author',
'tx_test_publication_author_mm',
'tx_test_publication_author_mm',
$queryBuilder->expr()->eq(
'tx_test_domain_model_author.uid',
$queryBuilder->quoteIdentifier('tx_test_publication_author_mm.uid_foreign')
)
)
->where(
$queryBuilder->expr()->eq(
'tx_test_publication_author_mm.uid_local',
$queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
)
)
->orderBy('tx_test_domain_model_author.uid', 'ASC');
$result = $query->execute();
$res = [];
while ($row = $result->fetch()) {
$res[] = $row;
}
print_r($res);
However, I only get one record, although the counter tells me it would be 3.
What am I doing wrong?

If the counter says its three items, then try change this:
$result = $query->execute();
$res = [];
while ($row = $result->fetch()) {
$res[] = $row;
}
into this:
$result = $query->execute()->fetchAll();
That fetches all rows into an array that you walk throug with:
foreach($result as $row){
...
}

It seems the QueryBuilder works differently, this gives me one result namely the first entry in the table:
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('tx_test_publication_author_mm');
$query = $queryBuilder
->select('*')
->from('tx_test_publication_author_mm');
$result = $query->execute()->fetchAll();
foreach($result as $row){
echo $row['field'];;
}
This gives me all results:
$db = mysqli_connect($dbHost, $dbUser, $dbPassword, $dbName) or die (mysql_error ());
$sql = "SELECT * FROM tx_test_publication_author_mm";
foreach ($db->query($sql) as $row) {
echo $row['field'];
}

Related

how to check array in where condition in codeigniter?

in code igniter a group of student details check in fore-each loop ,the student get by the bases of student admission number
my admission numbers are in $ad_no=$this->input->post('adn_no'); :-
array(5) { [0]=> string(5) "11784" [1]=> string(5) "11837" [2]=>
string(5) "11775" [3]=> string(5) "11937" [4]=> string(5) "12061" }
i try to select these admission numbers student, but the result show only first student result
.
my code:
foreach($ad_no as $key => $id) {
$this - > db - > where_in('ad_no', $id);
$query = $this - > db - > get('duration');
$r = $query - > result_array();
$dur = $r[0]['tot_hr'];
$start = explode(':', $dur);
$end = explode(':', $tm);
$total_hours = $start[0] - $end[0];
$total_hours1 = $start[1] - $end[1];
$mins = abs($total_hours1);
$dur = $total_hours.":".$mins;
$durs[$key] =
array(
'ad_no' => $ad_no[$key],
'tot_hr' => $dur
);
}
$reslt = $this - > Daily_temp_model - > duration($durs);
using array push in foreach loop
$result=[];
foreach($ad_no as $key => $id) {
$this->db->where_in('ad_no', $id);
$query = $this-> db-> get('duration');
$r = $query-> result_array();
array_push($result, $r);
$dur = $r[0]['tot_hr'];
$start = explode(':', $dur);
$end = explode(':', $tm);
$total_hours = $start[0] - $end[0];
$total_hours1 = $start[1] - $end[1];
$mins = abs($total_hours1);
$dur = $total_hours.":".$mins;
$durs[$key] =
array(
'ad_no' => $ad_no[$key],
'tot_hr' => $dur
);
}
$reslt = $this->Daily_temp_model->duration($durs);
using in_array
<?php
$a = array('1.10', 12.4, 1.13);
if (in_array('12.4', $a, true)) {
echo "'12.4' found with strict check\n";
}
if (in_array(1.13, $a, true)) {
echo "1.13 found with strict check\n";
}
?>

Codeigniter Active record query

How can I write this procedural query as codeigniter active record query (update_batch mode )
UPDATE products SET current_stock = current_stock + 1 where product_id = 1
You can use update_batch like this:
$products = $this->db->get('products'))->result();
for( $i = 0; $i < count($products); $i++){
$data[] = array(
'product_id' => $product[$i]->product_id,
'current_stock' => $product[$i]->current_stock + 1
);
}
$this->db->update_batch('products', $data, 'product_id');
You can use below query as explained on Codeigniter Query Builder Class:
$this->db->set('current_stock', 'current_stock+1', FALSE);
$this->db->where('product_id', 2);
$result = $this->db->update('products');

PDO bindParam with unknown number of parameters

I would like to run an update query for every row with a specific ID:
e.g.
$ids = array(111, 112, 113);
$query = "UPDATE mytable SET columnName = 'Y' WHERE id = :id1 or id = :id2 or id = :id3";
$stmt->bindParam(':id1', $ids[0], PDO::PARAM_INT);
$stmt->bindParam(':id2', $ids[1], PDO::PARAM_INT);
$stmt->bindParam(':id3', $ids[2], PDO::PARAM_INT);
This works fine if I know there are 3 ids to update, but how would I do this if the number of id fields is variable?
Something like this would do the trick.
$ids = array(111, 112, 113);
$valueString = "";
foreach($ids as $key => $val) {
$valueString .= ":id" . $key . " = " . $val;
if (end($ids) != $val) {
$valueString .= ", ";
}
}
$query = "UPDATE mytable SET columnName = 'Y' WHERE ". $valueString;
foreach($ids as $key => $val) {
$stmt->bindParam(':id' . $key, $val, PDO::PARAM_INT);
}

how to get `dataProvider ` with each product_id

i have order table where in product_id is string Like 10,11,12,13. And have Product table with this id.
how to get dataProvider with each product_id
My code is
public function getProducts($id){
$idarray = explode(',', $id);
$dataProviderProduct = Array();
foreach($idarray as $i=>$id){
$dataProviderProduct[$i]=new CActiveDataProvider('Product',
array( 'criteria'=>array(
'condition'=>'id=:id',
'params'=>array(':id' => $id),
),
'pagination'=>array( 'pageSize'=>10),
)
);
}
return $dataProviderProduct;
}
But this is wrong code
Use addInCondition like this:
$idarray = explode(',', $id);
$criteria = new CDbCriteria();
$criteria->addInCondition('id', $idarray);
$data = ModelName::model()->findAll($criteria);

Illegal String Offset within PDO For Each loop

PHP Query:
<?php
$query = $db->prepare('SELECT * FROM Locations WHERE user_id = :id LIMIT 0, 5');
$query->bindParam(":id",$id);
$result = $query->execute();
$rows = $query->fetch();
foreach ($rows as $row) {
echo $row["timestamp"]; "<br />";
}
?>
The two rows that should be printed (timestamp):
What actually prints:
1188((22
The error within the console:
PHP Warning: Illegal string offset 'timestamp' in /Sites/pages/user_account.php on line 73 - Line 73 being the echo $row... inside the forloop.
Any help would be greatly appreciated.
You are using fetch, which retrieves a single row, instead of fetchAll:
$rows = $query->fetchAll();
You have two rows (user_id = 8)
$rows = $query->fetchAll();
For all rows
foreach ($rows as $row) {
echo $row . "<br />";
}
For 1 row , all column
while ($row = $rows) {
foreach ($row as $column) {
echo $column . "<br />";
}
}