PHP PDO dynamically updating db table with multiple records to a specific user ID - pdo

/* Newbie need some help; I am creating a class to auto update my apps db record when instructed to, but I am consistently getting this message below, and for the heck of it, I just not seeing what I am doing wrong. Can someone please look at my codes for me? Thank you.
Warning: PDOStatement::bindParam() expects at least 2 parameters, 1 given in……..on line 331; that where the "else if(is_string($val)){" is located.
*/
// vars given
// DBDriver: MySQL
$myTable = 'seeYou';
$loginDate = NULL;
$ip = $_SERVER['REMOTE_ADDR'];
$date = #date('m/d/Y \a\\t h:i a');
$_id =1;
// data array
$idata = array("last_logged_in"=>$loginDate,
"login_date"=>$date,
"ip_addr"=>$ip
);
class name
{
///------------ other methods here---------///
/**
*--------------------------------------------
* Method - PDO: SET FIELD VALUE PLACEHOLDER
*--------------------------------------------
* #return fields with prefix as placeholder
*/
protected function set_fieldValPlaceHolders(array $data)
{
$set = '';
foreach($data as $field => $value)
{
$set .= $field .'= :'.$field . ',';
}
// remove the last comma
$set = substr($set, 0, -1);
return $set;
}
public function save($data=NULL, $_id = NULL, $rows= NULL, $dbTable= NULL)
{
//----------------- some other codes goes here ----------------//
$id = (int)$_id;
// update row with a specific id
if (isset($id) !== NULL && $rows === NULL)
{
$set = $this->set_fieldValPlaceHolders($data);
$sql = "UPDATE {$dbTable} SET {$set} WHERE user_id = :uid";
try
{
// Build the database statement
$_stmt = $this->_dbConn->prepare($sql);
$_stmt->bindValue(':uid',$id, PDO::PARAM_INT);
foreach ($data as $field => $val)
{
if(is_int($val)){
$_stmt->bindValue(':'.$field.'\', '.$val.', PDO::PARAM_INT');
}
else if(is_string($val)){
$_stmt->bindValue(':'.$field.'\', '.$val.', PDO::PARAM_STR');
}
else if(is_bool($val)){
$_stmt->bindValue(':'.$field.'\', '.$val.', PDO::PARAM_BOOL');
}
else if(is_null($val)){
$_stmt->bindValue(':'.$field.'\', '.$val="null".', PDO::PARAM_NULL');
}
else {
$_stmt->bindValue(':'.$field.'\', '.$val.', NULL');
}
$result = $_stmt->execute();
$num = $_stmt->rowCount();
}
}
catch(PDOException $e)
{
die('Error! The process failed while updating your record. <br /> Line #'.__LINE__ .' '.$e);
}
if ($result === true)
{
return true;
}
}

Check your bindValue calls: You give 1 parameter (a long string). It needs at least two. Check all the '
for example, it should be:
$_stmt->bindValue(':'.$field, $val, PDO::PARAM_INT);

Related

Yii2 Update the entry if it exists

Item $title defined earlier. I want what if found $find_title, update it with all fields from $title. Otherwise, create a new object
$find_title = Title::find()->where(["upc" => $title->upc])->one();
if ($find_title != null) {
$title->id = $find_title->id;
$title->save();
} else {
$title->save();
}
It worked in the laravel.
$find_title = Title::find()->where(["upc" => $title->upc])->one();
if ($find_title != null) {
$id = $title->id;
$find_title->attributes = $title->attributes;
$find_title->id = $id;
$find_title->save();
} else {
$title->save();
}
Here you assign all attributes of $title to $find_title, restore id, and then save;

Prestashop 1.6 l method

There is an issue with the translations, if the translation is missing prestashop is returining empty string, rather than the key.
Does anyone know the location of the 'l' method used in the controllers?
$this->l('string', 'mod'); //This will output '' if string is not translated.
I want to modify the method and make it return the key if the value is empty, but I cant find it.
I'll assume you are referring to an AdminController, since it's the only one using that function. It uses the function:
protected function l($string, $class = null, $addslashes = false, $htmlentities = true)
{
if ($class === null || $class == 'AdminTab') {
$class = substr(get_class($this), 0, -10);
} elseif (strtolower(substr($class, -10)) == 'controller') {
/* classname has changed, from AdminXXX to AdminXXXController, so we remove 10 characters and we keep same keys */
$class = substr($class, 0, -10);
}
return Translate::getAdminTranslation($string, $class, $addslashes, $htmlentities);
}
In your case it would call Translate::getAdminTranslation('string', 'mod', false, true)
In Translate::getAdminTranslation
We have:
...
$string = preg_replace("/\\\*'/", "\'", $string);
$key = md5($string);
if (isset($_LANGADM[$class.$key])) {
$str = $_LANGADM[$class.$key];
} else {
$str = Translate::getGenericAdminTranslation($string, $key, $_LANGADM);
}
...
Since it won't have the $_LANGADM[$class.$key], it will call:
$str = Translate::getGenericAdminTranslation($string, $key, $_LANGADM);
in your case $str = Translate::getGenericAdminTranslation('string', md5('string'), $_LANGADM);
In there we have:
...
if (isset($lang_array['AdminController'.$key])) {
$str = $lang_array['AdminController'.$key];
} elseif (isset($lang_array['Helper'.$key])) {
$str = $lang_array['Helper'.$key];
} elseif (isset($lang_array['AdminTab'.$key])) {
$str = $lang_array['AdminTab'.$key];
} else {
// note in 1.5, some translations has moved from AdminXX to helper/*.tpl
$str = $string;
}
return $str;
So by default if no key is found, the same string that is trying to be translated is returned. So there is no need to change the function.
On the otherhand, make sure the string it's translated to an empty string. You can also debug these functions to make sure your class is correct, and the file that is storing the corresponding translations doesn't have the empty translation for those strings.

working with option of $query in yii2

i want use where for $query.
foreach ($oppId as $o) {
$id = $o['opportunity_id'];
$query->Where("id=$id");
}
When I use this. All items shown
$query->orWhere("id=$id");
i need get this query :
SELECT * FROM `opportunity` WHERE id =27 or id =28
this is all of my function :
public function actionShow($type = 0, $city = 0, $client = 0) {
$query = (new \yii\db\Query())->select(['*'])->from('opportunity ')->innerJoin('profile_details', 'opportunity.user_id=profile_details.user_id')->orderBy('id desc');
$query->Where('id !=-1');
if (isset($_REQUEST['type'])) {
$type = $_REQUEST['type'];
if ($type != 0) {
$query->andWhere("project_type_id=$type");
}
}
if (isset($_REQUEST['city'])) {
$city = $_REQUEST['city'];
if ($city != 0) {
$query->andWhere("state_id=$city");
}
}
if (isset($_REQUEST['client'])) {
$client = $_REQUEST['client'];
if ($client != 0) {
$oppId = \app\models\OpportunityControl::find()
->where('project_type_id = :project_type_id', [':project_type_id' => $client])
->all();
foreach ($oppId as $o) {
$id = $o['opportunity_id'];
$query->orWhere("id=$id");
}
}
}
You very much do not want to use strings to add to the query under any circumstances as that is ripe for SQL injection. I'd format it like this:
...
$params = [];
foreach ($oppId as $o) {
$params[] = $o->opportunity_id;
}
$query->andWhere(['in', 'id', $params]);
...
You should also adjust your other query params so that you are not passing variables into SQL via a string.
if (isset($_REQUEST['type'])) {
$type = $_REQUEST['type'];
if ($type != 0) {
$query->andWhere(['project_type_id' => $type]);
}
}
if (isset($_REQUEST['city'])) {
$city = $_REQUEST['city'];
if ($city != 0) {
$query->andWhere(['state_id' => $city]);
}
}
See the Yii2 guide on using variables in queries for what you are trying to avoid here. Specifically:
Do NOT embed variables directly in the condition like the following, especially if the variable values come from end user inputs, because this will make your application subject to SQL injection attacks.
// Dangerous! Do NOT do this unless you are very certain $status must be an integer.
$query->where("status=$status");
I do it with Arrays
$query->where(['or',['id'=>27],['id'=>28]]);
But in your case save all ids in a Array is not possible,I do it with string inside foreach
$StringWhere='';
$LastElement = end($oppId);
foreach ($oppId as $o)
{
$id = $o['opportunity_id'];
$StringWhere.=' id='.$id;
if($o!=$LastElement)
{
$StringWhere.=' or ';
}
}
$query->where($StringWhere);
$query->where(['or',['id'=>27],['id'=>28]]);
I use this and it works perfectly as mentioned by metola. :)

Get raw sql from Phalcon query builder

Is it possible to extract raw sql query from the query builder instance in Phalcon? Something like this?
$queryBuilder = new Phalcon\Mvc\Model\Query\Builder();
$queryBuilder
->from(…)
->where(…);
$rawSql = $queryBuilder->hypotheticalGetRawQueryMethod();
By error and trial the below seems to working. Would be great if someone could confirm if there's a better way.
$queryBuilder = new Builder();
$queryBuilder->from(…)->where(…);
$intermediate = $queryBuilder->getQuery()->parse();
$dialect = DI::getDefault()->get('db')->getDialect();
$sql = $dialect->select($intermediate);
Edit: As of 2.0.3 you can do it super simple, see comment for full details:
$modelsManager->createBuilder()
->from('Some\Robots')
->getQuery()
->getSql()
you can use getRealSqlStatement() (or similar function name) on the DbAdapter. See http://docs.phalconphp.com/en/latest/api/Phalcon_Db_Adapter.html
According to documentation you can get this way the resulting sql query.
Or wait, this might not work on querybuilder. Otherwise you can setup low level query logging: http://docs.phalconphp.com/en/latest/reference/models.html#logging-low-level-sql-statements
$db = Phalcon\DI::getDefault()->getDb();
$sql = $db->getSQLStatement();
$vars = $db->getSQLVariables();
if ($vars) {
$keys = array();
$values = array();
foreach ($vars as $placeHolder=>$var) {
// fill array of placeholders
if (is_string($placeHolder)) {
$keys[] = '/:'.ltrim($placeHolder, ':').'/';
} else {
$keys[] = '/[?]/';
}
// fill array of values
// It makes sense to use RawValue only in INSERT and UPDATE queries and only as values
// in all other cases it will be inserted as a quoted string
if ((strpos($sql, 'INSERT') === 0 || strpos($sql, 'UPDATE') === 0) && $var instanceof \Phalcon\Db\RawValue) {
$var = $var->getValue();
} elseif (is_null($var)) {
$var = 'NULL';
} elseif (is_numeric($var)) {
$var = $var;
} else {
$var = '"'.$var.'"';
}
$values[] = $var;
}
$sql = preg_replace($keys, $values, $sql, 1);
}
More you can read there
The following is the common solution:
$result = $modelsManager->createBuilder()
->from(Foo::class)
->where('slug = :bar:', ['bar' => "some-slug"])
->getQuery()
->getSql();
But you might not expect to see the query without its values, like in:
die(print_r($result, true));
Array
(
[sql] => SELECT `foo`.`id`, `foo`.`slug` FROM `foo` WHERE `foo`.`slug` = :bar
[bind] => Array
(
[bar] => some-slug
)
[bindTypes] =>
)
So, this simple code might be useful:
public static function toSql(\Phalcon\Mvc\Model\Query\BuilderInterface $builder) : string
{
$data = $builder->getQuery()->getSql();
['sql' => $sql, 'bind' => $binds, 'bindTypes' => $bindTypes] = $data;
$finalSql = $sql;
foreach ($binds as $name => $value) {
$formattedValue = $value;
if (\is_object($value)) {
$formattedValue = (string)$value;
}
if (\is_string($formattedValue)) {
$formattedValue = sprintf("'%s'", $formattedValue);
}
$finalSql = str_replace(":$name", $formattedValue, $finalSql);
}
return $finalSql;
}
If you're using query builder then like given below then getPhql function can serve the purpose as per phalcon 3.4.4 version.
$queryBuilder = new Builder();
$queryBuilder->from(…)->where(…)->getQuery();
$queryBuilder->getPhql();
if (!function_exists("getParsedBuilderQuery")) {
/**
* #param \Phalcon\Mvc\Model\Query\BuilderInterface $builder
*
* #return null|string|string[]
*/
function getParsedBuilderQuery (\Phalcon\Mvc\Model\Query\BuilderInterface $builder) {
$dialect = Phalcon\Di::getDefault()->get('db')->getDialect();
$sql = $dialect->select($builder->getQuery()->parse());
foreach ($builder->getQuery()->getBindParams() as $key => $value) {
// For strings work fine. You can add other types below
$sql = preg_replace("/:?\s?($key)\s?:?/","'$value'",$sql);
}
return $sql;
}
}
Simple function that im using for debugging.

Applying a SQL function on Zend_Db_Table_Row::save()

Is it possible, when saving a Zend_Db_Table_Row, to make ZF apply a SQL function on one column?
For example, if $row->save() generates by default this SQL query:
UPDATE table SET field = ? WHERE id = ?;
I would like it to automatically apply the GeomFromText() function on this field:
UPDATE table SET field = GeomFromText(?) WHERE id = ?;
Thanks for any hint on how to do this with Zend_Db!
Define a custom update method in your class that inherits from Zend_Db_Table (not from the Zend_Db_Table_Row) and use a Zend_Db_Expr to set the column to the function return value.
See the docs here: http://framework.zend.com/manual/en/zend.db.table.html#zend.db.table.extending.insert-update.
I am just guessing but you could try this:
<?php
class MyTable extends Zend_Db_Table_Abstract
{
protected $_name = 'my_table';
public function update(array $data, $where) {
/**
* Build "col = ?" pairs for the statement,
* except for Zend_Db_Expr which is treated literally.
*/
$set = array();
$i = 0;
foreach ($data as $col => $val) {
if ($val instanceof Zend_Db_Expr) {
$val = $val->__toString();
unset($data[$col]);
} else {
if ($this->_db->supportsParameters('positional')) {
$val = ($col == 'field') ? 'GeomFromText(?)' : '?';
} else {
if ($this->_db->supportsParameters('named')) {
unset($data[$col]);
$data[':col'.$i] = $val;
$val = ($col == 'field') ? 'GeomFromText(:col'.$i.')' : ':col'.$i;
$i++;
} else {
/** #see Zend_Db_Adapter_Exception */
require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception(get_class($this) ." doesn't support positional or named binding");
}
}
}
$set[] = $this->_db->quoteIdentifier($col, true) . ' = ' . $val;
}
$where = $this->_whereExpr($where);
/**
* Build the UPDATE statement
*/
$sql = "UPDATE "
. $this->_db->quoteIdentifier($this->_name , true)
. ' SET ' . implode(', ', $set)
. (($where) ? " WHERE $where" : '');
/**
* Execute the statement and return the number of affected rows
*/
if ($this->_db->supportsParameters('positional')) {
$stmt = $this->_db->query($sql, array_values($data));
} else {
$stmt = $this->_db->query($sql, $data);
}
$result = $stmt->rowCount();
return $result;
}
protected function _whereExpr($where)
{
if (empty($where)) {
return $where;
}
if (!is_array($where)) {
$where = array($where);
}
foreach ($where as $cond => &$term) {
// is $cond an int? (i.e. Not a condition)
if (is_int($cond)) {
// $term is the full condition
if ($term instanceof Zend_Db_Expr) {
$term = $term->__toString();
}
} else {
// $cond is the condition with placeholder,
// and $term is quoted into the condition
$term = $this->quoteInto($cond, $term);
}
$term = '(' . $term . ')';
}
$where = implode(' AND ', $where);
return $where;
}
}
?>