How to execute a php loop in an andWhere clause using QueryBuilder? - symfony

I would like to execute this type of query using QueryBuilder in my FakeRepository.php (it's for a search form where the user can check some boxes).
if (sizeof($p['types']) > 0) {
$qb->andWhere(
foreach ($p['types'] as $type_id)
{'type.id=' .$type_id.' OR ' }
'1=0');
}
But I have an error with my syntax but I don't know how to fix it :
Parse error: syntax error, unexpected T_FOREACH, expecting ')' in /MyBundle/Entity/FakeRepository.php
Thanks a lot for your help

You need to first construct your OR condition and then pass it to the query builder
$first = true;
$orQuery = '';
foreach ($p['types'] as $type_id)
if ($first) {
$first = false;
} else {
$orQuery .= ' OR ';
}
$orQuery .= 'type.id=' .$type_id;
}
$qb->andWhere($orQuery);

You can also resove this problem:
$arr = array();
foreach ($p['types'] as $type_id){
$arr[] = $qb->expr()->orX("type.id = $type_id");
}
$qb->andWhere(join(' OR ', $arr));

Another solution to keep QueryBuilder functionality
$orX = $qb->expr()->orX();
foreach ($types as $key => $type) {
$orX->add($qb->expr()->eq('types', ':types'.$key));
$qb->setParameter('types'.$key, $type->getId());
}
$qb->andWhere($orX);

Related

T_OBJECT_OPERATOR - Drupal 7

this is the php code:
<?php
$tid = $job_node->field_job_cv_destination['und'][0]['tid'];
$term = taxonomy_term_load($tid);
$name = $term->name;
?>
and that is the error:
ParseError: syntax error, unexpected '->' (T_OBJECT_OPERATOR) in -
rules_php_eval() (line 2 -/web/maavarim/sites/all/modules/contrib/rules/modules/php.eval.inc(125) : eval()'d code)
can anyonw know what to do?
Try to implement your code as below
function mytheme_preprocess_page(&$vars, $hook) {
if (isset($vars['node']) && in_array($vars['node']->type, array('article', 'column'))) {
// Set header to topic for articles and columns
// #TODO: consider primary topic field (no multiselect), default to below if empty
$term = taxonomy_term_load($vars['node']->field_topic_ref[LANGUAGE_NONE][0]['tid']);
$vars['head_title'] = $term->name;
}
else {
$vars['head_title'] = $vars['title'];
}
}

ORA-6502, from WEB

I have a problem with Oracle DB.
<?php
require_once 'includes/conn.php';
function connect_db()
{
if ($c=oci_pconnect(uname,pwd, host,'AL32UTF8'))
return $c;
else
die( "ERROR");
}
$conn=connect_db();
$query = "BEGIN :ds_id :=DS.REG_DS1(:F_NAME);END;";
$stmt=oci_parse($conn,$query);
$f_name='John Doe';
$ds_id=-1;
oci_bind_by_name($stmt, ":ds_id", $ds_id);
oci_bind_by_name($stmt, ":F_NAME", $f_name);
if(oci_execute($stmt))
{
echo 'good';
}
else
print_r(oci_error($stmt));
?>
Here is function REG_DS1
FUNCTION REG_DS1(F_NAME IN VARCHAR) RETURN NUMBER AS
DS_ID NUMBER(8,0):=9988;
BEGIN
-- INSERT INTO TEST VALUES(F_NAME,SYSDATE);
RETURN DS_ID;
END REG_DS1;
When I try to execute this function from Sql Developer, it runs with no problem.
But if I execute from PHP script above, it gives me error:
ORA-06502: PL/SQL: numeric or value error: character string buffer too small ORA-06512: at line 1 [offset] => 0 [sqltext] => BEGIN :ds_id :=DS.REG_DS1(:F_NAME);END; )
If i change DS_ID variable to another number less than 100, it works great from both. but if i set it to a number more than 99, it gets me error from php script.
What can be a problem?
--jst idea and this is not solutioN
variable decleration or some defination problem
oci_connect($ODBuser,$ODBpass,$ODBhost,$db_charset);
should try like this
not like
oci_pconnect(uname,pwd, host,'AL32UTF8')
sample code :
-- just idea
<?php
$file = "../script/param.CML";
$encryptObj = new cast128;
$encryptObj->setkey("SABBIllustrateKey");
$fp=fopen($file,'r');
$strContent = fread($fp, filesize($file));
fclose($fp);
$strContent=$encryptObj->decrypt($strContent);
$ArConnect=split(" ",$strContent);
$OraService=$ArConnect[8];
$OraUser=$ArConnect[9];
$OraDBpass=$ArConnect[10];
$db_charset = 'AL32UTF8';
$cursor=oci_connect($OraUser,$OraDBpass,$OraService,$db_charset);
if(!$cursor)
{
echo "<br>Error In connection:- reason<BR>";
$e = oci_error(); // For oci_connect errors pass no handle
}
?>
<?php
$file = "../script/param.CML";
$encryptObj = new cast128;
$encryptObj->setkey("SABBIllustrateKey");
$fp=fopen($file,'r');
$strContent = fread($fp, filesize($file));
fclose($fp);
$strContent=$encryptObj->decrypt($strContent);
$con=split(" ",$strContent);
$OraService=$con[8];
$OraUser=$con[9];
$OraDBpass=$con[10];
$db_charset = 'AL32UTF8';
$cursor=oci_connect($OraUser,$OraDBpass,$OraService,$db_charset);
if(!$cursor)
{
echo "<br>Error In connection:- reason<BR>";
$e = oci_error(); // For oci_connect errors pass no handle
}
?>
Thx guys, finally I solved problem myself.
The problem was in variable size of returning value
By changing
oci_bind_by_name($stmt, ":ds_id", $ds_id);
to
oci_bind_by_name($stmt, ":ds_id", $ds_id,10,SQLT_INT );
the problem was solved.

Wordpress get_results parsing the symbol "&"

I have a strange Thing, where I do not know where the failure is.
$name = "Fast & Furious 8";
$res1 = $wpdb->prepare(
"
SELECT
*
FROM
wp_dbtable
WHERE
filmname = '%s'
LIMIT 1
",
$name
);
$res = $wpdb->get_results( $res1 );
foreach($res as $reseachG) {
}
I have a Problem with the Symbol &. For some reasons it does not pull anything out of my table, even if it should do this.
If I use instead of the variable the text it self, like this:
$res1 = $wpdb->prepare(
"
SELECT
*
FROM
wp_dbtable
WHERE
filmname = '%s'
LIMIT 1
",
"Fast & Furious 8"
);
it works. Also, other text inside the variable works well.
So it seems that prepare, or get_results does not accept this Symbol, or changes it. How can I solve it? I couldn't find any hint on the Internet.
It might not be a PHP-Problem, or a My-SQL-Problem, it might be a Problem of WordPress classes.
Thanks a lot.
The code above is correct. The Problem was, that I pulled the text for the filmname out of the data base. He transformed the & into html-special-chars. So I had to run: htmlspecialchars_decode($filmname);. It was not easy to find, becase every print method printed the correct text.
I found an function on the Internet, which shows me hidden chars and every single real entiti. Maybe it will help some of you also:
function hexdump ($data, $htmloutput = true, $uppercase = false, $return = false){
// Init
$hexi = '';
$ascii = '';
$dump = ($htmloutput === true) ? '<pre>' : '';
$offset = 0;
$len = strlen($data);
// Upper or lower case hexadecimal
$x = ($uppercase === false) ? 'x' : 'X';
// Iterate string
for ($i = $j = 0; $i < $len; $i++)
{
// Convert to hexidecimal
$hexi .= sprintf("%02$x ", ord($data[$i]));
// Replace non-viewable bytes with '.'
if (ord($data[$i]) >= 32) {
$ascii .= ($htmloutput === true) ?
htmlentities($data[$i]) :
$data[$i];
} else {
$ascii .= '.';
}
// Add extra column spacing
if ($j === 7) {
$hexi .= ' ';
$ascii .= ' ';
}
// Add row
if (++$j === 16 || $i === $len - 1) {
// Join the hexi / ascii output
$dump .= sprintf("%04$x %-49s %s", $offset, $hexi, $ascii);
// Reset vars
$hexi = $ascii = '';
$offset += 16;
$j = 0;
// Add newline
if ($i !== $len - 1) {
$dump .= "\n";
}
}
}
// Finish dump
$dump .= $htmloutput === true ?
'</pre>' :
'';
$dump .= "\n";
// Output method
if ($return === false) {
echo $dump;
} else {
return $dump;
}
}
Which shows you the hexa-codes for each char and also every single space, line, special trasformed symbol, or line-braker. It helps to see the real data.
thx to all.

Symfony2 + DBAL. How to use bindValue for multiple insert?

I'm using DBAL and I want to execute multiple insert query. But I have the problem: bindValue() method not working in loop. This is my code:
$insertQuery = "INSERT INTO `phonebook`(`number`, `company`, `user`) VALUES %s
ON DUPLICATE KEY UPDATE company=VALUES(company), user=VALUES(user)";
for ($i = 0; $i < count($data); $i++) {
$inserted[] = "(':number', ':company', ':user')";
}
$insertQuery = sprintf($insertQuery, implode(",", $inserted));
$result = $db->getConnection()->prepare($insertQuery);
for ($i = 0; $i < count($data); $i++) {
$result->bindValue($data[$i]["number"]);
$result->bindValue($data[$i]["company"]);
$result->bindValue($data[$i]["user"]);
}
$result->execute();
As result I received one-line table with fields: :number, :company, :user.
What am I doing wrong?
Thanks a lot for any help!
The problem you're having is that your binding has no way to determine to which placeholder it should be doing the binding with. To visualize it better, think on the final DBAL query you're generating:
INSERT INTO `phonebook`(`number`, `company`, `user`) VALUES
(':number', ':company', ':user'),
(':number', ':company', ':user'),
(':number', ':company', ':user');
When you do the binding, you're replacing all the parameters at the same time, ending up with a single row inserted.
One possible solution would be to give different parameter names to each row and then replace each one accordingly.
It would look like something similar to this:
public function randomParameterName()
{
return uniqid('param_');
}
...
$parameters = [];
for ($i = 0; $i < count($data); $i++) {
$parameterNames = [
'number' => $this->randomParameterName(),
'company' => $this->randomParameterName(),
'user' => $this->randomParameterName(),
];
$parameters[$i] = $parameterNames;
$inserted[] = sprintf("(':%s', ':%s', ':%s')",
$parameterNames['number'],
$parameterNames['company'],
$parameterNames['user']
);
}
$insertQuery = sprintf($insertQuery, implode(",", $inserted));
$result = $db->getConnection()->prepare($insertQuery);
foreach ($parameters as $i => $parameter) {
$result->bindValue($parameter['number'], $data[$i]["number"]);
$result->bindValue($parameter['company'], $data[$i]["company"]);
$result->bindValue($parameter['user'], $data[$i]["user"]);
}
You could probably extend your $data variable and incorporate the new parameter names into it. This would remove the need of yet another array $parameters to hold reference to the newly created parameter names.
Hope this helps
There is another alternative:
$queryStart = "INSERT INTO {$tableName} (" . implode(', ', array_keys($buffer[0])) . ") VALUES ";
$queryRows = $params = $types = [];
foreach ($rowBuffer as $row) {
$rowQuery = '(' . implode(', ', array_fill(0, count($row), '?')) . ')';
$rowParams = array_values($row);
list($rowQuery, $rowParams, $types) = SQLParserUtils::expandListParameters($rowQuery, $rowParams, $types);
$queryRows[] = $rowQuery;
$params = array_merge($params, $rowParams);
}
$query = $queryStart . implode(', ', $queryRows);
$connection->executeQuery($query, $params, $types);

Wrap the code to translate with wordpress/poedit?

Current I have WP code like this. I need to make it translateable by poedit. How do I wrap the code to make it work? Im not sure which method is use for this case. Some thing like:
<?php my_e( 'Total sales' ); ?> or __('Total sales', 'my')
This is the code. I need to translate ["Sales amount"], ["Number of sales"]
foreach ($results as $result) {
$date = $result->formatted_post_date;
$statistics[$date]["Sales amount"] += $wp_list_table->column_total_sales($result->ID);
$statistics[$date]["Number of sales"]++;
$statistics[$date]["date"] = $date;
$max_number_of_sales = max(array($max_number_of_sales,$statistics[$date]["Number of sales"] )); }
Thank you for help
You have to use __('string','textdomain') to assign a translated string to some variable. And _e('string','textdomain') to echo a translated string. See I18n_for_WordPress_Developers.
Two observations:
you'll not be able to translate array keys, see php.net/manual/en/language.types.array.php
what you're doing seems wrong. I'd do it like:
$sales_amount = 0;
$sales_number = 0;
foreach ($results as $result) {
$sales_amount += $wp_list_table->column_total_sales($result->ID);
$sales_number++;
$date = $result->formatted_post_date;
$statistics[$date]["sales_amount"] = $sales_amount;
$statistics[$date]["sales_number"] = $sales_number;
}
echo __( 'Sales Amount', 'my' ) . $sales_amount;

Resources