PHP MySQL not updating fields with values containing decimals - php

When I try to update a table with the following query string using PHP:
UPDATE card_designs SET `card_price` = '6180',
`annual` = '257.3',
`initial_payment` = '6512.3'
WHERE card_id = '1'
It does not update correctly. card_price value is put in correctly. However annual comes in as 0 and initial_payment comes in as 6255.00.
It doesn't matter if the fields are a VARCHAR, DECIMAL, or DOUBLE. If the value has a decimal it's all messed up.
Also, if I run the above query in a SQL client, the query works fine.
Here is the PHP code that constructs the query. I'm using mysqli:
$sql = "UPDATE ". $table ." SET ";
$updates = array();
foreach ($variables as $field => $value) {
array_push($updates, "`$field` = '$value'");
}
$sql .= implode(', ', $updates);
//Add the $where clauses as needed
if (!empty($where)) {
foreach ($where as $field => $value) {
$value = $value;
$clause[] = "$field = '$value'";
}
$sql .= ' WHERE '. implode(' AND ', $clause);
}
if (!empty( $limit)) {
$sql .= ' LIMIT '. $limit;
}
$query = $this->mysqli->query($sql);

I assume your database table fields datatype is Decimal(9,2)
// Prepare query
$table = "card_designs";
$variables = array(
"card_price" => "6180.00",
"annual" => "257.3",
"initial_payment" => "6512.3"
);
$where = array(
"id" => "1"
);
$sql = "UPDATE ". $table ." SET ";
$updates = array();
foreach ($variables as $field => $value)
{
array_push($updates, "$field = $value");
}
$sql .= implode(', ', $updates);
//Add the $where clauses as needed
if (!empty($where))
{
foreach ($where as $field => $value)
{
$value = $value;
$clause[] = "$field = $value";
}
$sql .= ' WHERE '. implode(' AND ', $clause);
}
if (!empty( $limit))
{
$sql .= ' LIMIT '. $limit;
}
// Run query
if ($mysqli->query($sql))
{
echo "Record updated successfully";
}

Related

PHP CRUD operations with search, and operator

I am using below function ( i got this from internet) to fetch data from DB and its working fine. If i use where and search condition is not working properly or i have missed some thing. Can any one help me to fix this issue.
public function getRows($table,$conditions = array()){
$sql = 'SELECT ';
$sql .= array_key_exists("select",$conditions)?$conditions['select']:'*';
$sql .= ' FROM '.$table;
if(array_key_exists("where",$conditions)){
$sql .= ' WHERE ';
$i = 0;
foreach($conditions['where'] as $key => $value){
$pre = ($i > 0)?' AND ':'';
echo $sql .= $pre.$key." = '".$value."'";
$i++;
}
}
if(array_key_exists("search",$conditions)){
$sql .= (strpos($sql, 'WHERE') !== false)?'':' WHERE ';
$i = 0;
foreach($conditions['search'] as $key => $value){
$pre = ($i > 0)?' OR ':'';
$sql .= $pre.$key." = '".$value."'";
$i++;
}
}
if(array_key_exists("order_by",$conditions)){
$sql .= ' ORDER BY '.$conditions['order_by'];
}
if(array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
$sql .= ' LIMIT '.$conditions['start'].','.$conditions['limit'];
}elseif(!array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
echo $sql .= ' LIMIT '.$conditions['limit'];
}
$query = $this->conn->prepare($sql);
$query->execute();
if(array_key_exists("return_type",$conditions) && $conditions['return_type'] != 'all'){
switch($conditions['return_type']){
case 'count':
$data = $query->rowCount();
break;
case 'single':
$data = $query->fetch(PDO::FETCH_ASSOC);
break;
default:
$data = '';
}
}else{
if($query->rowCount() > 0){
$data = $query->fetchAll();
}
}
return !empty($data)?$data:false;
}
Function used with where and Search condition
if(!empty($_POST['customer_number'])) {
$ajaxData = $auth_user->getRows(
'tablename',
array('where' => array('fieldName'=>$doc)),
array('search'=> array('fieldname1'=>$_POST['customer_number'], 'fieldname2'=>$_POST['customer_number']))
);
}
Result of the above code is
SELECT * FROM tablename WHERE cust_consum_type = '1'
Expected Result is.
select * from tablename where fieldName='somevalue' and fieldname1='somevalue' OR fieldname2='somevalue'
Help me to fix this issue.
This function is so wrong on so many levels, being critically insecure in the first place.
Instead, use vanilla PDO. Make your function this way
public function getRows($sql,$input = array()){
$stmt = $this->conn->prepare($sql);
$stmt->execute($input);
return $stmt;
}
Then just write your query right away with placeholders, pass the data in pparameters and have the result:
$sql = "select * from tablename where fieldName=:fieldName
and (fieldname1=:fieldName1 OR fieldname2=:fieldName2)";
$input = ['fieldName'=>$doc,
'fieldname1'=>$_POST['customer_number'],
'fieldname2'=>$_POST['customer_number']];
$data = $db->getRows($sql, $input)->fetchAll();
it will be safe, clean, always working, safe, flexible, safe from SQL injections and syntax errors.

SQL update with PHP arrays

Let's say i have and array like this
$array= Array('id'=>'3', 'name'=>'NAME', 'age'=>'12');
Keys from this array are name of columns in table and values are value of columns which i need to update.
I want to update the table based on keys and values.
I am using ADODB
Please help me
try this:
$sql = "UPDATE table SET ";
foreach($array as $key=>$value) {
$sql .= $key . " = " . $value . ", ";
}
$sql = trim($sql, ' '); // first trim last space
$sql = trim($sql, ','); // then trim trailing and prefixing commas
and of course the WHERE clause:
$sql .= " WHERE condition = value";
you will get the string:
UPDATE table SET id = 3, name = NAME, age = 12 WHERE condition = value
L.E: You might need to add apostrophes to strings so I have to change my code to something like this:
$sql = "UPDATE table SET ";
foreach($array as $key=>$value) {
if(is_numeric($value))
$sql .= $key . " = " . $value . ", ";
else
$sql .= $key . " = " . "'" . $value . "'" . ", ";
}
$sql = trim($sql, ' '); // first trim last space
$sql = trim($sql, ','); // then trim trailing and prefixing commas
$sql .= " WHERE condition = value";
which will produce this:
UPDATE table SET id = 3, name = 'NAME', age = 12 WHERE condition = value
L.E 2: If you want the id column in your condition, the code becomes this:
$sql = "UPDATE table SET ";
foreach($array as $key=>$value) {
if($key == 'id'){
$sql_condition = " WHERE " . $key . " = " . $value;
continue;
}
if(is_numeric($value))
$sql .= $key . " = " . $value . ", ";
else
$sql .= $key . " = " . "'" . $value . "'" . ", ";
}
$sql = trim($sql, ' '); // first trim last space
$sql = trim($sql, ','); // then trim trailing and prefixing commas
$sql .= $sql_condition;
which will produce this result:
UPDATE table SET name = 'NAME', age = 12 WHERE id = 3
Hope this helps! :D
foreach ($update_array as $key => $testimonials) {
$name = mysql_real_escape_string($testimonials->name);
$content = mysql_real_escape_string($testimonials->content);
$id = intval($testimonials->id);
$sql = "UPDATE testimonials SET name='$name', content='$content' WHERE id=$id";
$result = mysql_query($sql);
if ($result === FALSE) {
die(mysql_error());
}
}
Source : https://stackoverflow.com/a/7884331/3793639
Other sources to check.
PHP SQL Update array and Simple UPDATE MySQl table from php array
You could use something like this for achieving that:
foreach($values as $value) {
if(!key_exists($value, $item)) {
return false;
}
$table->{$value} = $items[$value];
}
Assuming that the key index is always id and that adodb can use named placeholders you could do this:
$array = Array('id'=>'3', 'name'=>'NAME', 'age'=>'12');
$set = array();
$data = array();
while(list($key,$value)=each($array)) {
$data[':'.$key] = $value;
if($key!='id') {
$set[] = $key . ' = :' . $key;
// if no placeholders use $set[] = $key . " = '" . database_escape_function($value) . "'";
}
}
$sql = "UPDATE table SET ".implode($set, ',')." WHERE id=:id";
//$data is now Array(':id'=>'3', ':name'=>'NAME', ':age'=>'12');
//$sql is now "UPDATE table SET name=:name, age=:age WHERE id=:id";
$stmt = $DB->Prepare($sql);
$stmt = $DB->Execute($stmt, $data);
This is probably the shortest and easiest for you, you can also use something like this to achieve it:
$array = Array('id'=>'3', 'name'=>'NAME', 'age'=>'12');
$sql = "UPDATE table SET ";
$sql .= implode(', ', array_map(function($key, $value){
return is_numeric($value) ? "{$key} = {$value}" : "{$key} = '". mysql_real_escape_string($value). "'";
}, array_keys($array), $array));
$sql .= " WHERE id = 123";
// Result : UPDATE table SET id = 3, name = 'NAME', age = 12 WHERE id = 123

update function in php

I have a update function that for now updates the required changes to MySQL database when I run index.php.
This is updating my password buy not the name field, ive been over the code and can not work out why.
Any help is greatly appreciated.
Index that tells what id and fields to update with entered data
<?php
require_once 'core/init.php';
$userInsert = DB::getInstance()->update('users', 1, array(
'password' => 'newpass',
'name' => 'Ben'
));
Function in different php that updated database
public function update($table, $id, $fields) {
$set = '';
$x = 1;
foreach($fields as $name => $value) {
$set .= "{$name} = ?";
if($x < count($fields)) {
$set .= ',';
}
$x++;
}
$sql = "UPDATE {$table} SET {$set} = 'newpassword' WHERE id = {$id}";
if(!$this->query($sql, $fields)->error()) {
return true;
}
return false;
}
I believe it to be a small error or mistype but I can not see the problem.
As you can see bellow the password field has been changed but the name has not
public function update($table, $id, $fields) {
$set = '';
$x = 1;
foreach($fields as $name => $value) {
$set .= "{$name} = \"{$value}\"";
if($x < count($fields)) {
$set .= ',';
}
$x++;
}
$sql = "UPDATE {$table} SET {$set} WHERE id = {$id}";
if(!$this->query($sql, $fields)->error()) {
return true;
}
return false;
}
Simply use of prepare and execute in PDO:
$sql = 'UPDATE '. $table .' SET username = :username, password = :password WHERE id = '. $id;
$sth = $dbh->prepare($sql);
$sth->execute(array(
':username' => 'ben',
':password' => 'newpassword'
));
private function update($table, $primaryKey, $fields) {
$query = 'UPDATE `' . $this->table . '` SET ';
foreach ($fields as $key => $value) {
$query .= '`' . $key . '` = :' . $key . ',';
}
$query = rtrim($query, ',');
$query .= ' WHERE `' . $this->primaryKey . '` = :primaryKey';
$fields['primaryKey'] = $fields['id'];
$this->query($query, $fields);
}
An example of an update function. Attention mine is inside a class and the query is another function and passes as an object.

PDO PHP Adding "AND" in BetweenPlaceholders

I would like to add " AND " in between the key and value pair arguments for my sql query but I don't know how. I have tried search the net but unable to find a solution.
$cdatahome = fetchCategory(array("status"=>"1","home"=>"1"));
function fetchCategory(array $conditions){
$db = Core::getInstance();
$sql = "SELECT id, title FROM ruj_category WHERE ";
$params = array();
foreach ($conditions as $column => $value) {
if (preg_match('/^[a-z-.]+$/', $column)) {
$sql .= "$column = ?";
$params[] = $value;
}
}
$sql .= " order by title asc";
$res = $db->dbh->prepare($sql);
$res->execute(array_values($params));
$res = $res->fetchAll(PDO::FETCH_ASSOC);
return $res;
$where = array();
foreach ($conditions as $column => $value) {
if (preg_match('/^[a-z-.]+$/', $column)) {
$where[] = "$column = ?";
$params[] = $value;
}
}
$sql .= implode(' AND ', $where);
$cdatahome = fetchCategory(array("status"=>"1","home"=>"1"));
function fetchCategory(array $conditions){
$db = Core::getInstance();
$sql = "SELECT id, title FROM ruj_category WHERE ";
$params = array();
$i = 0;
foreach ($conditions as $column => $value) {
if (preg_match('/^[a-z-.]+$/', $column)) {
if($i != 0){
$sql .= ' AND ';
}
$sql .= "$column = ?";
$params[] = $value;
$i++;
}
}
$sql .= " order by title asc";
$res = $db->dbh->prepare($sql);
$res->execute(array_values($params));
$res = $res->fetchAll(PDO::FETCH_ASSOC);
return $res;
Usually, when I want to put something like AND or & (in the case of URLs), I create an array and implode it on the string I want in the middle. For example:
$items = array("a", "b", "c");
$output = implode(" AND ", $items);
Outputs:
"a AND b AND c"
In your case, you can do your foreach loop to build the string pieces and then use AND as glue in the implode() function as listed out by the second answer.
First, you could put the conditions into an array, as you do with the values to $params. Like $cond[]="$column = ?" and then $sql.=implode(' AND ',$cond);
To have it solved in your foreach: before the loop set $first=false; and in the loop do $sql.=($first?'':' AND ')."$column = ?"; $first=false;

implode to fix update sql

I have this function
function updateDbRecord($db, $table, $carry, $carryUrl) {
mysql_select_db($db) or die("Could not select database. " . mysql_error());
$resultInsert = mysql_query("SHOW COLUMNS FROM " . $table . " WHERE Field NOT IN ('id')");
$fieldnames=array();
if (mysql_num_rows($resultInsert) > 0) {
while ($row = mysql_fetch_array($resultInsert)) {
$fieldnames[] = $row['Field'];
$arr = array_intersect_key( $_POST, array_flip($fieldnames) ); #check if value is null otherwise do not INSERT
}
}
$set = "";
foreach($arr as $key => $v) {
$val = is_numeric($v) ? $v : "'" . $v . "'";
$set .= $key . '=' . $val . ', ';
}
$sql = sprintf("UPDATE %s SET %s WHERE id='%s'", $table, $set, $_POST['id']);
mysql_query($sql);
if ($carry == 'yes') {
redirect($carryUrl.'?id='.$_REQUEST['id']);
} else { echo "Done!"; }
echo $sql;
}
It outputs for example: UPDATE projects SET project_name='123', project_bold='123', project_content='123', WHERE id='12'
The last comma before where is preventing it from working. Is there a way of avoiding this? Im aware of the function implode, however I am not sure how to employ it in this situation.
Yes,
$sql = substr($sql,'',-1);
I would use
$sql = rtrim($sql, ',');
Either that or instead of appending to a string, append to an array and use implode.
function updateDbRecord($db, $table, $carry, $carryUrl) {
mysql_select_db($db) or die("Could not select database. " . mysql_error());
$resultInsert = mysql_query("SHOW COLUMNS FROM " . $table . " WHERE Field NOT IN ('id')");
$fieldnames=array();
if (mysql_num_rows($resultInsert) > 0) {
while ($row = mysql_fetch_array($resultInsert)) {
$fieldnames[] = $row['Field'];
$array = array_intersect_key( $_POST, array_flip($fieldnames) ); #check if value is null otherwise do not INSERT
}
}
foreach ($array as $key => $value) {
$value = mysql_real_escape_string($value); // this is dedicated to #Jon
$value = "'$value'";
$updates[] = "$key = $value";
}
$implodeArray = implode(', ', $updates);
$sql = sprintf("UPDATE %s SET %s WHERE id='%s'", $table, $implodeArray, $_POST['id']);
mysql_query($sql);

Categories